Sei sulla pagina 1di 197

SYNTACTIC ASPECTS

C -Programming
By
Prof Imran Qureshi
(Computer Science)

Lecture Prepared By Prof Imran Qureshi


Compiler And Its Processes
• Write a program using Text Editor
• Pre Process Program using
preprocessor
• Compiles Program using
Compiler
• Links The Program using Linker
• Loads The Program Using Loader
• Run or Execute the Program
using exe file

High-level Compiler Assembler


language Assembly Machine
(A program) language (A program) code
source code

• Compiling the source code :


• The program is compiled using cc filename.c
• The command cc translates a C source program into an executable
program. This process takes place in two stages – compiling and linking.
• The compiler translates the C statements into machine language
instructions. The output of the compiler is called object file which has .obj
and .out extension which depends on operating system.
• Type a.out to execute the program. Then Loader loads the program into
the computer’s memory, initiating it’s execution.

2
Language : Media of communication
• Natural Language

Paragraph
Alphabets Words Sentences Pages
s

• Programming Language
Alphabets/ C-
C-Words/ C C
Digits/Sp. Statements/
Tokens Functions Programs
char Instructions

3
General Structure of C Programs
Documentation Section
Link Section or Header Section
Definition Section
Global Declaration Section
main( ) Function Section
{
Variable declaration/Initialization;
Program statements;
}
Subprogram Section
function1( )
.
.
functionn( )

4
#include<string.h>
strcat(s1,s2) Concatenates string s1to the end of s1.
strcmp(s1,s2) Compares strings s1 and s2.
strcpy(s1,s2) Copies the string s2 to s1.
#include<ctype.h>
tolower(x) Returns lower case equivalent of character x
toupper(x) Returns upper case equivalent of character x
#include<stdio.h>
printf( ) Writes arguments to stdout in specified format.
scanf( ) Reads arguments from stdin in specified format.
fopen( ) Opens the identified file.
fclose( ) Closes the identified file.
#include<math.h>
sin(x) Sine of x, x in radians
cos(x) Cosine of x, x in radians
exp(x) Exponential function ex
log(x) Natural logarithm ln(x), x>0
pow(x,y) xy
ceil(x) Smallest integer grater than x.
floor(x) Largest integerProf
smaller than x.
Imran Qureshi 5
First C Program
#include<stdio.h>
void main()
{
printf(“Hi! This is our First Program”);
}
• Type above code and save it as first.c
using text editor and compile it using..
– gcc first.c
– Execute it using…
– ./a.out
6
C Character Set
Letters Digits
Uppercase A……Z Decimal digits 0…..9
Lowercase a…….z
Special Characters White Spaces
! * + \ “ Blank space
< # ( = |
Horizontal tab
{ > % ) ~
; } / ^ - Carriage return
[ : , ? &
_ ] . ‘ New line
Form feed

7
C Words or tokens

Prof Imran Qureshi 8


Keywords
• C language has 32 reserved words or keywords.
• Since keywords have specific meaning, we cannot
use them as identifiers.
• All keywords are to be written in lower-case letters.
auto extern sizeof break float static

case for struct char goto switc


h
const if typedef continue int union

default long unsigne do register void


d
double return volatile else short while

enum signed

9
Identifiers
• Identifiers are used for naming variables,
functions and arrays.
• Identifiers follow the below listed rules :
– Alphabets, digits, underscores and dollar signs are
permitted.
– They must not begin with a digit.
– First character must be a letter or an underscore.
– Uppercase and lower case letters are distinct.
– They can be of any length however the first 8
characters are treated as significant by the C
compiler.
– Special Characters are not allowed
– Keywords, cannot be used as identifier.

10
Variables
• A variable is an identifier that is used to store a data
value.
• It is a symbolic name assigned to the memory location
where data is stored.🡺 Range depends on size of
memory location
• A variable can have only single data item/value at any
given time during the program execution.
• A variable can take different values at different times
during execution.
• Which values are stored in variable depends on Data
Types
• For assigning a value to a variable, we use
assignment operator (=).

3 X

11
Constants And Literals
• Constants are the identifier that represent fixed
values. This Value is not to be altered during
execution They are called as a symbolic
constant and they are associated with literals
• Literals means values or data items which can
be directly used within the programs
• There are total 2 types of the constant or literal
– String Constant
• Character Constant
• String Constant
– Numeric Constant
• Integer Constant
• Floating Point Constant

12
String Constants
• Character Constants
– It is a single character, enclosed in apostrophes (single quotation
marks).
– All the character constants has their own unique ASCII values

• Backslash Character Constants (Escape Sequences)


– Escape sequences are used in output functions.
– An escape sequence always begins with a backslash and is
followed by a character.

• String Constant
– It contains sequence of characters enclosed in double quotation
marks.

13

Numeric
Integer Constant
Constants
– It’s an integer valued number.
– It consists a sequence of digits.
– Types of Integer Constants as follows;

Types Rules Examples


Decimal Integer Digits 0…9,Sign is allowed but 0, -23, +45
at preeding of the number
Octal Integer Digits 0…7,it should start with 0673,024,01
0
Hexadecimal Integer digits 0…9 & letters A…F and 0X9F,0x7Ed,0xabc
a…f,it should start with 0x or
OX
Unsigned Integer End with Sign not allowed 45784u,32869U
Qualifiers
Unsigned Long (Access
Sign not allowed 98562314ul,9863272UL
Integer Specifiers)
•Long
Floating Point Constant
Integer Sign allowed 9876543l,9876543L
– These represent numbers containing fractional parts.
– Number can be present with exponent
• Exponent may be +ev or –ev and It may be either 1 digit or 2 digit wide

14
Special Symbols
Name Uses
parenthesis ( ) Used for defining precedence in expressions.
Used for surrounding cast types.
braces { } Used to initialize the arrays.
Used to define a block of code.
brackets [ ] Used to declare array types.
semicolon ; Used to separate statements.
comma , Usedtoseparateidentifiers in a variable
declaration.
Used inside a ‘for’ statement.
-> pointer to structure member reference.
dot . Structure member reference.
ampersand & Is called as address of operator.
Used to assign addressof the location of a
variable.
Used in the scanf function.
asterisk * Pointer reference(indirection).
15
Data Types

16
Fundamental Data Types
Datatyp Description Memory
e Requirement

int integer quantity (stores whole numbers) 2 bytes

char single character 1 byte

float floating point number (contains fractional 4 bytes


part)
double double precision floating number 8 bytes

bool Single bit (true or false) 1 bit

void Not Passing or return anything ---

17
Type Size(in bytes) Range
char 1 –128 to 127
int 2/4 –32,768 to 32,767
unsigned char 1 0 to 255
signed char 1 –128 to 127
unsigned int 2 0 to 65535
signed int 2 –32,768 to 32,767
short int 2 –32,768 to 32,767
unsigned short int 2 0 to 65535
signed short int 2 –32,768 to 32,767
long int 4 –2147483648 to 2147483647
signed long int 4 –2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float 4 3.4e-38 to 3.4e+38
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e-4932 to 1.1e+4932
bool 1(bit) 0 to 1

18
User-defined Data Types

• The struct and union data types are explained in the


Seperate chapters.

• The typedef Data type


• It represents the type definition that allows the user to define an
identifier that would represent the existing data type.
• This user-defined datatype identifier can later be used to declare the
variables.
• Syntax
– typedef type identifier;
• Example
– Typedef int item_qty;
– item_qty nut, bolt;

19
The enum Data Type
• The enum Data Type
– An enumeration is a list of constant values.
– It is used to declare variables that can have
one of the values enclosed within the braces.
These values are also called as enumeration
constants.
• Example
enum color {green, blue, red, pink}; //green, blue, red, pink are constants
// or values
enum color flowers, leaves; //flowers and leaves are variables
flowers = red;

leaves = green;

20
Operators
Operators

Unary Relational
Operator Operator
(-,++,--) (<,>,<=,>=.
.)

21
Expressions
• An expression is a combination of
variables, constants and operators
arranged as per the syntax of the language.
Algebraic expression C expression

ab – c (a * b) – c
ab/c a*b/c
(m + n)(x – y) (m + n) * (x – y)
4x2 + x (4 * x * x) + x

22
Operators Precedence and Associativity
Operators Category Operators Associativity Level

Unary Operators - ++ -- ! sizeof (type) Right to Left 1


Arithmetic multiply, * / % Left to Right 2
divide and modulus
Arithmetic add and + - Left to Right 3
subtracts
Left shift and Right shift << >> Left to Right 4
Relational Operators < <= > >= Left to Right 5
Equality Operators == != Left to Right 6
Bitwise AND & Left to Right 7
Bitwise XOR ^ Left to Right 8
Bitwise OR | Left to Right 9
Logical AND && Left to Right 10
Logical OR || Left to Right 11
Conditional Operator ?: Right to Left 12
Assignment Operator = += -= *= /= %= Right to Left 13

23
Automatic Type Conversion
• It is also possible to store value of one type into a variable of
another type without a cast i.e. automatic conversion.
• It is possible only if the destination type has enough memory space
to store the source value.
• When operands in an expression are of different data types, the
lower type is converted in to the higher type before the operation
proceeds.
• If one operand is floating point and other is integer, the integer is
converted in to floating point and the result is floating point.
• If one of the operands is long double, convert the other to long
double and result is long double.
• And in the final, the result of the expression is converted in to the
type of the variable on the left of the ‘=’ sign and in this process the
following changes may occur:
– float to int causes truncation of the fractional part to zero.
– double to float causes rounding of digits.

24
Type Casting
• Type casting forcefully converts the value
of one type into another type.
• Syntax : (type) expression;
• Example :
– x =(int)10.456; //10.456 converts to 10.
– int a = 34; z = (float) a; // 34 converts to
34.000000
– y = (int)a + b; // Result of a+b is
converted to integer

25
Formatted Input and Output
• The scanf() function :This function is used to accept formatted
data from the keyboard , where format of string is depends on the
control string.
• Syntax :
• int scanf(“control string”,&var1,&var2,&var3…&varn);
• Where &var1,&var2…&var3 are the parameters of functions that
means variable names, showing the addresses of memory
location where data is to be stores.
• The control string consist of
• 1. White space characters (space,\t,\n,\v,\r,\f)
• 2. Conversion characters (d,c,i%.,o,u,s,e,f,g,x,[..])
• 3. A printable characters which specifies delimiter in between
two data items.
• 4. Modifier which tells size and type of the data item.
• Syntax :
• %[modifier]conversion_character

26
The scanf statement
Modifier Conversion Characters

Modi Meaning Conversio Explanation


fie n
r Character
s
* Field is to be skiped d Decimal number
size Maximum size of data item c Single character

h Value to be stored in short i Integer(Octal/Decimal/


int Hex)
l Value to be stored in long o Octal integer
or double
L Value to be stored in long u Unsigned decimal integer
or double
s Character string
e,f,g Floating point number
x
Prof Imran Qureshi Hexadecimal number 27
# include <stdio.h>
void main (void)
{
int num;
char c;
float pi = 3.141;

printf("\nEnter your favorite number");


scanf("%d",&num);
printf("\nYou have entered your favorite
number as %d ",num);
printf("\nEnter your favorite character");
scanf("%c",&c);
printf("\nYou have entered your favorite
character as %c",c);
printf("\nThe value of pi is %.3f ",pi);
return;
}
/*program to display the ASCII code
Exerise 1 set A Assignment no:8*/
#include<stdio.h>
main()
{
char ch;
printf("Enter any charecter:");
scanf("%c",&ch);
printf("ASCII code for %c is %d\n",ch,ch);
}
/*output
[fy125145@localhost setA]$ cc ascii.c
[fy125145@localhost setA]$ ./a.out
Enter any charecter:e
ASCII code for e is 101
*/

Prof Imran Qureshi 29


/*program to display the Arithmatic &
Harmonic mean of two no
Exerise 1 set A Assignment no:5*/
#include <stdio.h>
main()
{
float a,b,c,d;
printf("Enter Two no:");
scanf("%f %f",&a,&b);
c=(a+b)/2.0;
d=a*b/(a+b);
printf("Arithmatic mean is %.2f & Harmonic
mean is %.2f\n",c,d);
}
/*[fy125145@localhost setA]$ cc arth.c
[fy125145@localhost setA]$ ./a.out
Enter Two no:147 22
Arithmatic mean is 84.50 & Harmonic
mean is 19.13
*/

Prof Imran Qureshi 30


/*program to display its prev & next
charecter
Exerise 1 set A Assignment no:7*/
#include <stdio.h>
main()
{
char ch;
printf("Enter a charecter:");
scanf("%c",&ch);
printf("Preveious chr is %c and next chr is
%c",ch-1,ch+1);
}
/*output
[fy125145@localhost setA]$ cc character.c
[fy125145@localhost setA]$ ./a.out
Enter a charecter:u
Preveious chr is t and next chr is v
*/

Prof Imran Qureshi 31


/*program to display the Surface Area &
Volume of cuboid
Exerise 1 set A Assignment no:6*/
#include<stdio.h>
main()
{
float l,b,h,a,v;
printf("Give length,breadth,height of
cuboid:");
scanf("%f %f %f",&l,&b,&h);
a=2*(l*b+l*h+b*h);
v=l*b*h;
printf("The value of area is %.2f and value
of volume is %.2f\n",a,v);
}
/*output
[fy125145@localhost setA]$ cc cuboid.c
[fy125145@localhost setA]$ ./a.out
Give lendth,breadth,height of cuboid:2 4 5
The value of area is 76.00 and value of
volume is 40.00
*/
Prof Imran Qureshi 32
/*program to display the Temperature in
Celsius & Kelvin
Exerise 1 set A Assignment no:2*/
#include <stdio.h>
main()
{
float F,C,K;
printf("Give temp in Kelvin:");
scanf("%f",&F);
C=0.54*(F-32);
K=C+273.15;
printf("Result=%.2f\n",C);
printf("Result=%.2f\n",K);
}
/*output
[fy125145@localhost setA]$ cc
fahrenheit.c
[fy125145@localhost setA]$ ./a.out
Give temp in Kelvin:150
Result=63.72
Result=336.87
*/
Prof Imran Qureshi 33
/*program to Interchange the numbers
Exerise 1 set B Assignment no:2*/
#include<stdio.h>
main()
{
int a,b,t;
printf("Give the numbers to interchange:");
scanf("%d %d",&a,&b);
t=a;
a=b;
b=t;
printf("The number after interchange is %d
and %d\n",a,b);
}
/*output
[fy125145@localhost setB]$ cc
interchange.c
[fy125145@localhost setB]$ ./a.out
Give the numbers to interchange:15 18
The number after interchange is 18 and 15
*/

Prof Imran Qureshi 34


points
Exerise 1 set B Assignment no:1*/
#include<stdio.h>
#include<math.h>
main()
{
int x1,y1,x2,y2;
float z;
printf("Enter the coordinates of
X=(x1,y1):");
scanf("%d %d",&x1,&y1);
printf("Enter the coordinates of
Y=(x2,y2):");
scanf("%d %d",&x2,&y2);
z=sqrt((x2*x2-2*x1*x2+x1*x1)+(y2*y2-
2*y1*y2+y1*y1));
printf("The value of distance is %.2f\n",z);
}
/*output
[fy125145@localhost setB]$ cc -lm
codrdinate.c
[fy125145@localhost setB]$ ./a.out
Enter the coordinates of X=(x1,y1):15 25
Enter the coordinates of Y=(x2,y2):16 8
Prof Imran Qureshi 35
The value of distance is 17.03
Control Statements
C Statements
• C provides different kinds of statements.
1. Null statement :-🡪 ;

1. Jump Statements :-🡪 goto, continue, break.

1. Labelled Statements :-🡪 : Label_Identifier.

1. Expression Statement :-🡪 a=a+1;

1. Compound Statement :-🡪 { ….. }

1. Control Statement :
The control statements are used to control the flow of the program.
This is done by testing the conditions and then taking decisions
that which statements to be executed and which not to be.

37
Flow Control Structures

38
The goto Statement
• The goto statement changes the normal
sequence of a the program execution by
transferring control to other part of the
program.
• The goto statement is usually not used
because C is completely structured
language and most probably, the break
and continue statements are used.
• goto aa;

39
Simple if Statement
• It is a two-way decision statement. Depending
on whether the value of expression is ‘true’ or
‘false’, it transfers the control to a particular
statement.
• Syntax
• if (test expression)
• {
• True-block statements;
• }
• statement-x;

40
The If…else Statement
• This statement allows selecting one of the two available options
depending upon the output of the test expression
if (test expression)

{
True-block statements;
}

else

{
False-block statements;

}
statement-x

41
/* program to accept an integer & check it
is even or odd */
/* Exerise 2 set A Assignment no:1 */
#include<stdio.h>
main()
{
int a;
printf("Enter a no:");
scanf("%d",&a);
if(a%2==0)
printf("The No is even\n");
else
printf("The N0 is odd\n");
}
/*output
[fy125145@localhost setA]$ cc odd.c
[fy125145@localhost setA]$ ./a.out
Enter a no:15
The N0 is odd
[fy125145@localhost setA]$ ./a.out
Enter a no:16
The No is even
*/
Prof Imran Qureshi 42
/* program to accept an character & check
wheather it is a digit*/
/* Exerise 2 set A Assignment no:3 */
#include<stdio.h>
main()
{
char ch;
printf("Enter the Charecter:");
scanf("%c",&ch);
if(ch>'0' && ch<'9')
printf("%c is a digit\n",ch);
else
printf("%c is a not digit\n",ch);
}
/*output
[fy125145@localhost setA]$ cc digit.c
[fy125145@localhost setA]$ ./a.out
Enter the Charecter:d
d is a not digit
[fy125145@localhost setA]$ ./a.out
Enter the Charecter:6
6 is a digit
*/
Prof Imran Qureshi 43
/* program to accept an integer & check it
is div by 5 & 7 */
/* Exerise 2 set A Assignment no:4 */
#include<stdio.h>
main()
{
int a;
printf("Enter a no:");
scanf("%d",&a);
if(a%5==0 && a%7==0)
printf("%d is divisible by 5 & 7\n",a);
else
printf("%d is not divisible by 5 & 7\n",a);

}
/*output
[fy125145@localhost setA]$ cc div.c
[fy125145@localhost setA]$ ./a.out
Enter a no:35
35 is divisible by 5 & 7
[fy125145@localhost setA]$ ./a.out
Enter a no:45
45 is not divisible by 5 & 7
*/
Prof Imran Qureshi 44
a leap year or not
Exerise 2 set B Assignment no:3 */
#include<stdio.h>
main()
{
int a;
printf("enter any year:");
scanf("%d",&a);
if ((a%4==0 && a%100!=0)|| a%400==0)
printf("%d is leap year\n",a);
else
printf("%d is not leap year\n",a);
}
/*output
[fy125145@localhost setB]$ cc leap.c
[fy125145@localhost setB]$ ./a.out
enter any year:1900
1900 is not leap year[fy125145@localhost
setB]$ cc leap.c
[fy125145@localhost setB]$ ./a.out
enter any year:1984
1984 is leap year
[fy125145@localhost setB]$ ./a.out
enter any year:1999
1999 is not leapProf
year
Imran Qureshi 45
The nesting of If…else Statements
if (test expression1)
{
if (test expression2)
{

statement -1;
}
else
{

statement – 2;
}
Fig. 5.7
}
else
{
statement - 3;
}
statement – x;

46
The else If Ladder
• if (condition - 1)
• statement – 1;
• else if (condition - 2)
• statement – 2;
• else if (condition - 3)
• statement – 3;
• …………………………….
• else if (condition - n)
• statement – n;
• else
• default – statement;

47
The switch Statement
• We use if statements to choose one of the many alternatives. But as the
number of alternatives increases, the complexity of such a program also
increases. Thus, to make it simpler, C has a multi-way decision statement
known as switch.
• A case expression can be repeatedly used in a switch statement. That is it
allows several alternate courses of actions and choose one to be executed at
runtime.
• The use of break statement in every case is used to quit the switch statement
after a particular case is matched. Thus only one case gets executed. If the
break statement is not used, then all the statements following the matched
case will get executed. Thus break statement is compulsory for the proper
execution of the switch statement.
switch (expression)
{
case value – 1: // value -1 is a constant and is known as case label.
Statement1;
break; // end of case
case value – 2: // case labels end with a colon (:).
Statement1;
break;
default: //optional
default – Statement;
break;
}
statement – x;

48
/* Write a program, which accepts two
integers and an operator as a character (+
- * /), performs the
corresponding operation and displays the
result
Exerise 3 set A Assignment no:2 */
#include<stdio.h>
main()
{
int n1,n2,a,m,d1,s,d2;
char ch;
printf("Enter two integers & operator:");
scanf("%d %d %c",&n1,&n2,&ch);
a=n1+n2;
m=n1*n2;
d1=(float)n1/n2;
d2=(float)n2/n1;
s=n1-n2;

Prof Imran Qureshi 49


switch(ch)
{
case '+':printf("The addition of %d & %d is
%d\n",n1,n2,a);
break;
case '*':printf("The multiplication of %d &
%d is %d\n",n1,n2,m);
break;
case '/':printf("The division of %d & %d is
%d\n",n1,n2,d1);
printf("The division of %d & %d is
%d\n",n2,n1,d2);
break;
case '-':printf("The subraction of %d & %d
is %d\n",n1,n2,s);
break;
}
}

Prof Imran Qureshi 50


square,rectangle & triangle
Exerise 3 set B Assignment no:2*/
#include<stdio.h>
main()
{
int l,b2,l2,h3,b3,ch;
printf("\n1.Area of Square\n2.Area of
Rectangle\n3.Area of Triangle\n");
printf("Enter your choise=");
scanf("%d",&ch);
switch (ch)
{
case 1:printf("Enter length=");
scanf("%d",&l);
printf("Area of Square is %d\n",l*l);
break;
case 2:printf("Enter length & breath=");
scanf("%d %d",&l2,&b2);
printf("Area of Rectangle=%d\n",l2*b2);
break;
case 3:printf("Enter base & height=");
scanf("%d %d",&b3,&h3);
printf("Area of
Triangle=%.2f\n",(b3*h3)/2.0);
Prof Imran Qureshi 51
}
Difference between if…else and switch-
case
The if…else The switch-case

Is a two – way branching. Is a multi – way branching.

The nested if…else is Is easier to write.


complicated.
The nested else…if can take No such problem occurs in
many switch-case.
levels and it becomes difficult to
match the else part to its
corresponding if.
Debugging becomes difficult. Tracing of errors and debugging
is
easy.
The test expression can be a Only constant integer
constant value or may involve expressions
any and values are allowed.
type of operators.
52
The while Statement
• C programming language provide us readymade loop
statements like-while ,do..while , for . Without using
these statement we can construct a loop, but we have to
follow these rules of loop mentioned in first chapter, that
is initialisation, increment, check and transfer the loop.
• Syntax :
while (test expression)
{
Body of the loop
}
statement – x;

Prof Imran Qureshi 53


/*program to accept a no & count the no of
digit in the no
Exerise 4 set A Assignment no:5*/
#include<stdio.h>
main()
{
int n,dig=0;
printf("Enter a number:");
scanf("%d",&n);
while (n>0)
{
dig++;
n=n/10;
}

printf("The digits are %d\n",dig);


}
/*output
[fy125145@localhost setA]$ cc digit.c
[fy125145@localhost setA]$ ./a.out
Enter a number:1545464
The digits are 7
*/
Prof Imran Qureshi 54
Exerise 4 set A Assignment no:4*/
#include<stdio.h>
main()
{
int n,flag=1,i=2;
printf("Enter a no:");
scanf("%d",&n);
while (i<n)
{
if (n%i==0)
{
flag=0;
break;
}
i++;
}
if (flag==0)
printf("%d is not a prime no\n",n);
else
printf("%d is a prime no\n",n);
}
/*output
[fy125145@localhost setA]$ cc prime.c
[fy125145@localhost setA]$ ./a.out
Enter a no:9 Prof Imran Qureshi 55
The do_while Statement
• Syntax :
do
{
Body of the loop
}

while (test condition);


statement – x;
• All do loops are executed in following sequence.
• Step 1 : Executes body of loop and go to Step 2
• Step 2 : It checks the test condition if true then go
to Step 1 other wise Step 3

56
#include<stdio.h>
main()
{
int x=1;

do
{
printf("%d\t",x);
x++;
}while(x<=10);
}

Prof Imran Qureshi 57


Difference between while and
do…while
The while Loop The do – while Loop

It is an entry-controlled loop It is an exit-controlled loop

It is top-tested control loop. It is bottom-tested control loop.

Tests the condition before Though the condition is false the


executing any of the body of the Do loop is
statements in its body. executed at least once.

Syntax: while (test exp) { body } Syntax: do { body } while (test


exp);

58
/*program to accept a no & check it is
Fibnacci no or not
Exerise 4 set B Assignment no:1*/
#include<stdio.h>
main()
{
int n,n1=0,n2=1,i=1,n3;
printf("Enter a no:");
scanf("%d",&n);
while(i<=n)
{
n3=n1+n2;
printf("The no's are %d\n“,n3);
n1=n2;
n2=n3;
i++;
}
}

Prof Imran Qureshi 59


/*program to accept a no & display it in
words
Exerise 4 set B Assignment no:5*/
#include<stdio.h>
main()
{
int n,dig=0,rev=0,t;
printf("Enter a number:");
scanf("%d",&n);
while (n>0)
{
rev=rev*10+n%10;
n=n/10;
}

Prof Imran Qureshi 60


t=rev%10;
switch (t)
{
case 1:printf("ONE\t");
break;
case 2:printf("TWO\t");
break;
case 3:printf("THREE\t");
break;
case 4:printf("FOUR\t");
break;
case 5:printf("FIVE\t");
break;
case 6:printf("SIX\t");
break;
case 7:printf("SEVEN\t");
break;
case 8:printf("EIGHT\t");
break;
case 9:printf("NINE\t");
break;
case 0:printf("ZERO\t");
break;
}
Prof Imran Qureshi 61
rev=rev/10;
The for statement
• It is also an entry-controlled loop
• Syntax :
for (initialization ; test condition ; increment)
{
Body of the loop
}

62
Nested loop s
• Rules of the nested loop
1) Inner loop and outer loop should not overlap with each
other.
2) Running variables used in the loops are to be
independent or separate.
3) Direct jump from inner loop to outer loop is allowed but
jump from outer loop to inner loop is not allowed.
4) We can use for loop within while loop or do-while loop
and vice vrsa.
5) If total iteration of outer loop is n (i.e. body of loop of
outer loop is executed n times) and iteration of inner loop
is m then body of inner loop is executed m*n times. This
m may vary according to condition.

63
#include<stdio.h>
main()
{
char ch='A';
int n,i=0,j;
printf("Enter lines you want:");
scanf("%d",&n);
for(i=n;i>=0;i--)
{printf("\n");
for(j=1;j<=i;j++)
printf("%c\t",ch++);
}
}
/*output
[fy125145@localhost setA]$ cc lines.c
[fy125145@localhost setA]$ ./a.out
Enter lines you want:6

A B C D E F
G H I J K
L M N O
P Q R
S T
U
Prof Imran Qureshi 64
*/
The break Statement
• The break statement is used to jump out of
a loop.
• An early exit from a loop can be
accomplished using the break statement.
When a break statement is encountered
inside a loop, the loop is immediately
exited and the program continues with the
statement immediately following the loop.

65
The continue Statement
• Sometimes, in the loop iterations, it may
be necessary to skip some statements in
that loop and start the next iteration of that
same loop. For such situations, C provides
continue statement.
• The continue statement causes the loop
to continue with the next iteration skipping
the remaining statements in that loop.

66
Functions
Functions
• A function is a named, self-contained block of statements
that perform a specific, well defined task and may return a
value to the calling program.

• A function is named i.e. it is referenced by a name and is


invoked (or called) by this name.

• A function is self-contained as it can have its own variables


and constants to be used only within the function.

• A function performs a specific task as it defines a discrete


job to perform as a part of the overall program.

• A function may or may not return a value to the calling


program.

Prof Imran Qureshi 68


Advantages of Functions
1. It facilitates top down modular programming. In this programming style, the high
level logic of the overall problem is solved first while the details of each lower level
functions is addressed later.
2. In many programs, it may happen that a specific function is repeated many times.
Instead of writing the function code as many times as it is required we can write it
as a single function and access the same function again and again as many times
as it is required.
3. Use of functions avoids the repeated programming of the same set of instructions.
For example, if we want to find the area of a circle for different set of values, we
write a function, and we can call this function and supply different values.
4. The length of the source program can be reduced by using functions at
appropriate places.
5. A function may be used by many other programs. Thus a c programmer can build
on what others have already done, instead of starting over from zero.
6. A function can call other functions. It may even call it self which is called
recursion.
7. Due to breaking up of the program into modules, it becomes easy to write and
debug. This also provides logical clarity.
8. Programming teams does a large percentage of programming. If the program is
divided into subprograms, each subprogram can be developed by different team
members rather than the whole team working on the same complex program.

Prof Imran Qureshi 69


Flow of Control in Multi-function
Program

Prof Imran Qureshi 70


• Sequence of execution
• 1 2 6 7 3 8 9 10 12 13 11
• 4 5 12 13

Prof Imran Qureshi 71


Function Declaration :
• Syntax
– return_datatype function_name(type arg1,
type arg2, …);
• Example
– int sum(int a, int b); //Takes two integer
arguments and returns an integer value.
– void sum(float a, float b);

Prof Imran Qureshi 72


Function Definition
• Syntax :
return_datatype function_name(type arg1,
type arg2, …)
{
local variable declarations;
statements;
return (expression);
}

Prof Imran Qureshi 73


The ‘return’ keyword :

return;
return;
return expression; return b;
return(expression);
return(a+b);

Prof Imran Qureshi 74


Types of Function Calls
• Functions can be called in many different
ways :
1.Functions with no arguments and no
return values.
2.Functions with arguments and no return
values.
3.Functions with arguments and return
values.

Prof Imran Qureshi 75


Functions with Arguments and No
Return Values :
• Function call has the actual arguments that are
assigned to the formal arguments in the function
definition.
• Actual parameters are used in the function call.
• Formal parameters are used in function
definition.
• Both the arguments should match in number,
type and order.
• The values of actual arguments are assigned to
the formal arguments on a one to one basis
starting with the first argument as shown above.

Prof Imran Qureshi 76


Functions with Arguments and
Return Values
• The function call transfers the actual arguments
to the particular function where the formal
arguments are created and are assigned the
memory space and are given the values of the
actual arguments.
• The called function is executed until the return
statement is encountered. The return value is
passed back to the function call.
• The return value is thus assigned to the calling
function.

Prof Imran Qureshi 77


Methods of Parameter Passing

• There are two ways to pass arguments (parameters) to a function:


• 1. Pass arguments by value (Call by value).
• 2. Pass arguments by address or by pointers (Call by reference).

Call by Value :
• In this method, the contents of the arguments in the calling functions
are not changed, even if they are changed in the called function.
• The contents of the actual parameters get copied into the
corresponding formal parameters.
• Call by Reference :
• In this method, the contents of the arguments in the calling functions
get changed i.e. the original values are changed.
• Instead of passing the value of a variable, we can pass the memory
address of the variable to the function. This is called as Call by
reference.

Prof Imran Qureshi 78


Scope of Variables
• The part of the program within which a variable can be
accessed is called as its scope.
• Local :
• By default the scope of a variable is local to the function
in which it is defined. Local variables can only be
accessed in the function in which they are defined; they
are unknown to other functions in the same program.
They are also called as Internal variables.
• Global :
• The default scope of variable can be changed by setting
up variables that are available across function
boundaries. If a variable is defined outside any function
definitions is called as External variable. Scope of such
variables will be for the whole program, and hence such
variables are also called as Global variables.

Prof Imran Qureshi 79


Comparison of Global variable and
Local Variable
Local variables Global variables

Exist inside the function Accessible through out


that creates them. the program.
Have allocated memory Have allocated
on the stack. memory on the Data
segment
Are not initialized Are normally
automatically. initialized to 0 by
default.

Prof Imran Qureshi 80


Explanation of life and access of variables
#include <stdio.h> Life Access
int a = 7; // global variable
main( )
{
int b = 3; // local to main( )
………. a/b a/b
abc( );
……….. a/b a/b
xyz( );
………. a/b a/b
}
abc( )
{
int c =4; // local to abc( )
……..
…….. a/b/c a/c
}
xyz( )
{
int d = 9; // local to xyz( )
…….. a/b/d a/d
}

Prof Imran Qureshi 81


#include<stdio.h>
main()
{
int even(int n);
int n,r;
printf("Enter a no:");
scanf("%d",&n);
r=even(n);
if (r==1)
printf("It is even no\n");
else
printf("It is odd no\n");
}
int even(n)
{
int r;
if(n%2==0)
r=1;
else
r=0;
return r;
}
/*output
[fy125145@localhost setA]$ cc even.c
[fy125145@localhost
Prof ImransetA]$
Qureshi ./a.out 82
/* program to write a function for prime no
*/
/* Exerise 7 set B Assignment no:1 */
#include<stdio.h>
main()
{
int prime(int n);
int i=1,cnt=1;
while(cnt<=10)
{
if(prime(i)==1)
{
printf("%d\t",i);
cnt++;
}
i++;
}
}

Prof Imran Qureshi 83


int prime(int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
/*output
[fy125145@localhost setB]$ cc prime.c
[fy125145@localhost setB]$ ./a.out
1 2 3 5 7
11 13 17 19
23
*/

Prof Imran Qureshi 84


Storage Classes
• The storage class determines the scope and lifetime of a
variable.
• There are two types of locations in a computer where
such a value is stored – Memory and CPU registers.
• There are four types of Storage classes :
– Automatic
– Register
– Static
– External
• The storage class of a variable tells-
– Where the variable would be stored?
– What will be the default initial value?
– What is the scope of the variable?
– How long would the variable exist?

Prof Imran Qureshi 85


Auto - Storage Class
• auto is the default storage class for local variables.
• Example :
int num(int n)
{
int count;
auto int student;
}
• The example above defines two variables with the same storage
class. auto can only be used within functions, i.e. local variables.
• The auto variables are created when the function is called and
destroyed automatically when the function is exited, hence the name
automatic.
• Features :
– Storage : Memory
– Scope : Local to the block in which it is defined.
– Life : Till the control remains within the block where it is
defined.
• Default initial value : Garbage value.

Prof Imran Qureshi 86


Register - Storage Class :
• Register is used to define local variables that should be stored in a
CPU register instead of memory. This means that the variable has a
maximum size equal to the register size (usually one word) and cant
have the unary '&' operator applied to it (as it does not have a
memory location).
• Example :
{
register int items;
}
• Register should only be used for variables that require quick access
- such as counters.
• Note : Defining 'register' does not mean that the variable will
be stored in a register. It is entirely up to the compiler to decide
where a variable is to be stored – in the register or memory.
• Features :
– Storage : CPU registers
– Scope : Local to the block in which it is defined.
– Life : : Till the control remains within the
block where it is defined.
– Default initial value : Garbage value.

Prof Imran Qureshi 87


Static - Storage Class :
• static is the default storage class for global variables. The two variables
(count and road) in the below example have a static storage class.
• Example :
static int count;
int road;
main( )
{
printf("%d\n", count);
printf("%d\n", road);
}
• static can also be defined to local variables (within a function) and they
retain their values between calls to the function.
• Example :
void Func(void)
{
static count=1;
}
• Features :
– Storage : Memory
– Scope : Local to the block in which it is defined.
– Life : Persists between different function
calls.
– Default initial value : Zero

Prof Imran Qureshi 88


Difference between Auto and Static storage classes
Auto Static
Auto variables persists till the Static variables persist between
control remains within the different function calls.
block where it is defined.
The auto variables are created The variables persist in the main
when the function is called memory.
and destroyed automatically
when the function is exited.
auto is the default storage class static is the default storage class
for local variables. for global variables
Default initial value: Garbage Default initial value: Zero
value.
Auto declaration is valid only for Static declaration is valid for
variables. variables and functions.
Declaration: auto int x; Declaration: static int x;

Prof Imran Qureshi 89


Extern - Storage Class :
• extern defines a global variable that is accessible by any function in the program. They are declared
outside all functions. Note that the extern declaration does not a allocate storage space for
variables.
• Some times, the same global variable defined in file A is used again in file B. Then how does the
compiler know that the variable used in file B is actually the same variable declared in file A?
• The answer is: Use the extern specifier to the global variable defined elsewhere. In this case, we
declare a global variable in file A, and then declare the variable again using the extern specifier in
file B.
• For example, suppose you have two global int variables, y and z, that are defined in one file, and then, in another
file, you may have the following declarations:
• Example :
int x = 0; /* a global variable */
extern int y; /* an allusion to a global variable y */
int main()
{
extern int z; /* an allusion to a global variable z */
int i; /* a local variable */
.
.
return 0;
}
• When the compiler sees these two declarations, it knows that the declarations are actually allusions
to the global variables y and z that are defined elsewhere.
• Features :
– Storage : Memory
– Scope : Global
– Life : : Active throughout the entire program
– Default initial value : Zero

Prof Imran Qureshi 90


Recursion
• Recursion is the process by which a function calls itself repeatedly,
until some specified condition has been satisfied.
• This process is used in place of iterative computations in which each
action is stated in terms of a previous result; iterative programs are
very big and complex.
• In recursion, functions may directly or indirectly call it self – If the call
to a function occurs inside the function itself, it is called direct
recursion. If the function calls another function, which in turn makes
a call to the first one, it is called indirect recursion.
Syntax :
<type> function_name(<argument list>)
{
…………….
……………
function_name(….);
……………..
…………….
}

Prof Imran Qureshi 91


raise to y */
/* Exerise 8 set A Assignment no:1 */
#include<stdio.h>
main()
{
int powerf(int a,int b);
int x,y,r;
printf("Enter x & y:");
scanf("%d %d",&x,&y);
r=powerf(x,y);
printf("x raise to y is %d",r);
}
int powerf(int a,int b)
{
if(b==0)
return 1;
return a*powerf(a,b-1);
}
/*output
[fy125145@localhost setA]$ cc power.c
[fy125145@localhost setA]$ ./a.out
Enter x & y:2 4
x raise to y is 16
*/
Prof Imran Qureshi 92
Pros and cons of Recursion
• Advantages :
1. Avoids unnecessary calling of functions.
2. Solves problems in easier way than using iterative loops
Ex: tower of Hanoi
You reduce size of the code when you use recursive call.
3. Complex programs can be easily written using recursion.
• Disadvantages :
1. Too many recursive functions may cause confusion in the code.
2. Recursive solution is logical and it is difficult to debug and
understand.
3. In recursion, use of ‘if’ statement is compulsory to force the function
to return without the recursive call being executed. Otherwise the
function will never return i.e. it will execute infinite times.
4. Program execution becomes slower as the function call and return
takes longer time.

Prof Imran Qureshi 93


Passing Arrays to Functions :
• Method 1 : Passing the complete array at a time.
• A complete array can be passed to a called function by just giving
the name of the array as the parameter for that called function -
since just the name of the array specifies the base address of the
array in the memory, we are sending the entire array.

Example :
• int num[5]; // array with 5 elements
• int sum(num); /* passing the starting address of the array ‘n’
i.e. passing the complete array. */
• The name of the array is num and without any subscripts, it refers to
the starting address of the array in the memory. Thus, num is
equivalent to &num[0].
• The above example passes the complete array num to the called
function and the function can perform its task on this array and
modify its values.

Prof Imran Qureshi 94


Passing Arrays to Functions :
• Method 2 : Passing the array elements one-by-one.
• Array elements can also be passed to the called function
one-by-one. Thus the function can access only one
element at a time and has no right to modify this value.
• Example :
• int num[5]; // array with 5 elements
• int sum(int); // function prototype
• for(i=0;i<5,i++)
• sum(num[i]); // passing one-by-one elements of
array num to function sum.

Prof Imran Qureshi 95


Functions and Pointers :
• Pointers to Functions :A pointer to function is defined as the address of
the code executed when the function is called.
• Syntax :
return_type *pointer_name(argument list);
The * along with the pointer_name acts as the function name.
• Example :
float *maxp(float, float);
float *maxp(float *xp, float *yp)
{
return xp>=yp?xp:yp;
}
• In the above example, maxp is a pointer to function accepting two float
values and returning a float value
• Types of declaration of pointers :
– int* pi(void) : declares pi to be a function returning a pointer to integer
with no arguments.
– int *pi(void) : declares pi to be a pointer returning an integer value with
no arguments.

Prof Imran Qureshi 96


Assigning Function Address to a Pointer

• You can also assign the address of any function to a pointer by just
specifying the function_name without parenthesis.
• Example :
int fact(int n) // function to find the factorial of a given no.
{
……..
……..
}
main( )
{
int *pi(int); //pointer to function with prototype of fact
int x = 5; // number whose factorial is required
pi = fact; //assigning address of function fact to pointer pi
pi(x); //call to the function fact using pi
}

Prof Imran Qureshi 97


Functions Returning Pointers :
• To make a function return a pointer, it has to be explicitly mentioned in
the calling function as well as in the function declaration.
• Example :
main( )
{
int a, b, *c;
int* pi(int, int); // pi is a function returning pointer to integer with two
……… // integer arguments.
………
c = pi(a,b);
printf(“%d”, *c);
}
int* pi(int i, int j) // function definition
{
int *p, *q; integers being passed to pi( ) are collected in i and j and
p = &i; then their addresses are assigned to p and q.
q = &j;
return *p >= *q ? p : q; // Test the value of p and q and returns either
} // address stored in p or the address in q.

Prof Imran Qureshi 98


Arrays
Array Concept
• An array is a group of data items of the same data type that
share a common name.
• An array should be of a single type, comprising of integers
or strings and so on.
• An array is a linear and homogeneous data structure.
Linear data structure stores its individual data elements in
a sequential order in the memory. Homogeneous means all
individual data elements are of the same data type.
• An array has the following properties:
1. The type of an array is the data type of its elements.
2. The name of an array
3. The number of dimensions
4. The size of an array is the number of elements in each dimension.

Prof Imran Qureshi 100


Types of Array
• One Dimensional Array
– One-dimensional arrays have one subscripts, three-dimensional arrays
– Syntax : datatype arrayname[size]
– Where,
– datatype : The type of the data stored in the array
– arrayname : Name of the array
– size : Maximum number of elements that an array
can hold.
• Multi Dimensional Array
– Two-dimensional arrays have two subscripts, three-dimensional arrays
have three subscripts. And so on.
– Syntax : datatype arrayname[size1] [size2] [size3]…[sizen]
– Where,
– datatype : The type of the data stored in the array
– arrayname : Name of the array
– size1 : Size of first dimension
– size2 : Size of second dimension

– sizen : Size of nth dimension

Prof Imran Qureshi 101


Array Initialization
• Syntax : arrayname[index] = value ;
• Example : int mark[10];
mark[0] = 35;
mark[1] = 70;
………………..
………………..
mark[9] = 86;

▪ You can also initialize the complete array directly:


▪ Syntax : type arrayname[ ] = {list of values};
▪ Example :
– int mark[10] = {35, 70, 40, 55, 26, 43, 56, 82, 78, 86};

Prof Imran Qureshi 102


Advantages of Arrays
• 1. Random Access - Any element in an
array can be accessed immediately if its
exact position in the array is known.
• Any memory chip is nothing but array
• 2. Easy to use.

Prof Imran Qureshi 103


Limitations of Array
1. Constant size - To get an array of a different size, you must
explicitly deal with memory using realloc, malloc etc.
2. Constant data type.
3. Large free sequential block to accommodate large arrays
4. Arrays do not support copy assignment (you cannot write
arraymarks = arrayscores)
5. Sequential Search – You can search any element in an
unsorted array by sequential search technique. Thus, if the
element is located at 5th position in the array, then we will
have to first go through first 4 elements before locating it
on the 5th position.
6. Elements cannot be inserted into an array - Inserting an
element into an array would mean shifting down by one
place of all the elements after the correct position of the
inserted element.
7. Elements cannot be deleted from an array – Deleting an
element from an array would mean shifting up by one
position of all the elements in the array.
Prof Imran Qureshi 104
Our days are identical suitcases

all of the same sizes,

but some people can pack more into them than others

Please Note..

Sky is the Limit for Programmer

Prof Imran Qureshi 105


Pointers
Need of Pointers
• Definition
• Pointers are the variables that contain the address of another variable
within the memory..

1. It enhances the capability of the language to manipulate


data.
2. Pointers reduce the length and complexity of the program.
3. It is used for creating data structures such as linked lists,
trees, graphs and so on.
4. Use of pointers to access array of strings saves the data
storage space in the memory.
5. Pointer is used to pass information to and for the functions.
6. It allows working with dynamically allocated memory.
7. It increases the execution speed.

Prof Imran Qureshi 107


Concept of Pointers

• Int x=5
• X variable
• 5 value
• 1002 address
• The variable x is associated with the memory address 1002. Since
memory addresses are just numbers, they can also be assigned to
any variables that can be stored in the memory location, like other
simple variables. Such variables that contain the memory address
are called Pointers.
• Thus, pointer is a variable that contains the address which is a
location of another variable in the memory.
• Suppose, we assign the address of x to variable p, then p is called
the pointer as it points to the variable x. This link between x and p is
shown below:

Prof Imran Qureshi 108


• x 5 1002 indicates, x = 5;
• p 1002 3400 p = 1002;
where 1002 is the address of x

Prof Imran Qureshi 109


Address and Dereferencing (& and
*) Operators
• Accessing address of variable through pointer(using & operator):
• Consider, x = 5;
• The memory address is automatically assigned for this data item.
• To access the address of variable x, the operator & is used.
• The & operator is called ‘address of’ operator and it is a unary operator.
• We can assign the address of x to another variable p as:
• p = & x; //Assigns 1002(address of variable x) to variable p. Thus, p is
pointer variable.
• Accessing the value of variable through pointer(using * operator):
• The value represented by x, can be accessed by the expression *p, where *
is called ‘value at the address’ operator and it is a unary operator.
• Therefore,
• x = *p; // *p and x represent the same value (data item).
• x also represents the value 5 and *p also represents 5.
• Accessing to an object through pointer is called Dereferencing and the
asterisk (*) operator is called ‘dereferencing or indirection operator’.

Prof Imran Qureshi 110


Write a program to print the
address of a variable along with its
#include<stdio.h>
value.
void main()
{
char c='Z';
float f=10.2;
int i=987;
printf("\nVariable is the quadraple");
printf("\nWhich has some name, some value");
printf("\nSome location that means address");
printf("\nAnd its value has its type");
printf("\n\nName :c\t\tValue :%c\t\tAddress :%X\tType :char",c,&c);
printf("\nName :f\t\tValue :%f\tAddress :%X\tType :float",f,&f);
printf("\nName :i\t\tValue :%d\t\tAddress :%X\tType :int",i,&i);
}

Prof Imran Qureshi 111


Pointer Arithmetic
Operation Expression Meaning
Increment ptr++; Increments ptr to point to next location of same
type. If ptr is a pointer to integer (int occupies 2
bytes), and if ptr = 2003 then ptr++ gives
ptr = 2005
Decrement ptr--; Decrements ptr to point to previous location of
same type. If ptr is a pointer to integer(int
occupies 2 bytes), and if ptr = 2003 then ptr--
gives ptr = 2001
Adding a ptr = ptr + 8; ptr points to 9 integer locations after current
number location.
If ptr = 2003 then ptr+8 gives ptr = 2011
Subtracting ptr = ptr – 6; ptr points to 6 integer locations before current
a location.
number If ptr = 2003 then ptr-6 gives ptr = 1997
Subtraction ptr=ptr1- We can subtract one pointer from another if and
of ptr2; only if both are pointing two one array.
pointers (in program) Here ptr, ptr1, ptr2 all are pointers to same array.

Prof Imran Qureshi 112


Some invalid Pointer arithmetic
are:
• Addition of two pointers
• Multiplication of a number with pointer
• Division of a pointer with a number

Prof Imran Qureshi 113


Write a program to demonstrate the arithmetical
operation on pointers.
/*Program to show pointer arithmatic*/
#include<stdio.h>
void main()
{ char c='Z',*cp;
float f=10.2,*fp;
int i=987,*ip;
long l=345,*lp;
double d=9.99,*dp;
cp=&c;fp=&f;ip=&i;lp=&l;dp=&d;
printf("\n Char float int long double");
printf("\n%8x%8x%8x%8x%8x",cp,fp,ip,lp,dp);
cp++;fp++;ip++;lp++;dp++;
printf("\n%8x%8x%8x%8x%8x",cp,fp,ip,lp,dp);
cp+=12;fp+=12;ip+=12;lp+=12;dp+=12;
printf("\n%8x%8x%8x%8x%8x",cp,fp,ip,lp,dp);
cp--;fp--;ip--;lp--;dp--;
printf("\n%8x%8x%8x%8x%8x",cp,fp,ip,lp,dp);
cp-=12;fp-=12;ip-=12;lp-=12;dp-=12;
printf("\n%8x%8x%8x%8x%8x",cp,fp,ip,lp,dp);
}

Prof Imran Qureshi 114


Pointer Comparison
• The comparisons >, <, >=, <=, = =, != are
permitted only between pointers of same type.
• Example:
• Consider, int a[5], *aptr;
• Then expression, aptr = = &a[4];
//is true if ‘aptr’ points to the last

element of array ‘a’
• and aptr < &a[5];
//is true as long as aptr is pointing to one of
the elements of ‘a’.

Prof Imran Qureshi 115


Pointer to Pointer
• We know that, a pointer is a variable that contains the address of
another variable of a specific datatype. A pointer to pointer is a
variable that contains the address of a pointer variable of specific
datatype.
• Syntax of declaring pointer to pointer : data_type **ptr_to_ptr
• Example :
• int x = 12;
• int *ptr, // implies ptr is a pointer to an integer
• int **ptr_to_ptr; // implies ptr_to_ptr is a pointer to a
pointer
• ptr = &x; // assigns address of variable x
• ptr_to_ptr = &ptr; // assigns address of pointer variable ptr

Prof Imran Qureshi 116


Allocating Memory
• When we declare a pointer variable, the space is allocated in memory only for storing the address
and not for the data items.
• This space is allocated by the compiler. To solve this problem, we use malloc() function which
allocates the space for the data items also. This function takes the memory needed for allocation
directly from the operating system with out the interference of the compiler.
• How to allocate memory to integer pointer?
• int *p;
• p = (int *) malloc (sizeof (int));
• Here, p conatains the address of 2 bytes memory where that 2 bytes can hold the data.
• How to allocate memory to character pointer?
• char *p;
• p = (char *) malloc (sizeof (char));
• How to allocate memory to float pointer?
• float *p;
• p = (float *) malloc (sizeof (float));
• How to allocate memory to double pointer?
• double *p;
• p = (double *) malloc (sizeof (double));
• In this similar manner, we can allocate memory to other data types also.

Prof Imran Qureshi 117


Write a program to calculate perimeter of the rectangle using

pointers
/*program to handle pointers*/
/*Remember that compiler only allocates memory to pointers
to store location, for data member it is require to use malloc finction*/
#include<stdio.h>
void main()
{ int *l,*b,*p;
l=(int*)malloc(sizeof(int));
b=(int*)malloc(sizeof(int));
p=(int*)malloc(sizeof(int));
printf("\nEnter Length");scanf("%d",l);
printf("\nEnter Breadth");scanf("%d",b);
*p=2*(*l + *b);
printf("\nLength = %d",*l);
printf("\nBreadth = %d",*b);
printf("\nPerimeter of Rectangle = %d",*p);
}

Prof Imran Qureshi 118


Arrays and Pointers
• Arrays are internally stored as pointers. Thus array
elements can be efficiently handled using a pointer.
• Any operation that can be achieved by array subscripting
can also be done with pointers (i.e. an array name
without the subscript is a pointer to the first element of
the array).
• Example :
• int a[5];
• Then, a and &a[0] are similar.
• int a[4][5];
• Then a and &a[0][0] are similar.

Prof Imran Qureshi 119


Functions for DMA
Functio Meaning
n
malloc Allocates requested size of bytes and returns the pointer to
the first byte.

calloc Allocates space for an array of elements, initializes them to


zero and then return the pointer to the memory.

free Frees the previously allocated space.

realloc Changes(modifies) the size of previously allocated space.

Prof Imran Qureshi 120


The malloc
• Syntax : ptr = (cast_type *) malloc (byte_size)
• Where, ptr is a pointer of type cast_type. Type casting
is required because by default malloc( ) returns a void
pointer.
• malloc returns a pointer to an area of memory with
byte_size.

Example : int *x;
• x = (int *) malloc (10 * size of(int));
• This statement reserves a block of memory size of 10
integer quantities.
• Example : x = (char *) malloc (30);
• This statement reserves a block of memory size of 30
character quantities

Prof Imran Qureshi 121


The calloc
• Example : int *x;
• x = (int *) calloc (10 * size of(int));

Prof Imran Qureshi 122


The free
• When we no longer need the data we
stored in the block of memory and also we
don’t want to use that block any more for
storing any other information, we may
release that storage space.
• Syntax : free(ptr); //releases the
memory pointed to by ptr.
• Where, ptr is a pointer to memory which
has already been created by malloc or
calloc.

Prof Imran Qureshi 123


The realloc
• Syntax : ptr = realloc(ptr, newsize);
• It allocates new memory size of newsize to
the pointer variable ptr and returns the
pointer to the first byte of the new memory
block.

Prof Imran Qureshi 124


Advantages of Dynamic memory
allocation over Static allocation
• 1. Allocates memory at run time.
• 2. Neither wastage nor shortage of memory
space.
• 3. It can either grow or shrink during the
execution of the program
• 4. Data can be rearranged efficiently through
DMA.
• 5. Speed of DMA is faster than static allocation.
• 6. Freeing of unnecessary memory is possible
through DMA.

Prof Imran Qureshi 125


Array of Pointers
• Till now, we have seen array of integers, array of
characters. Similarly, there is a concept of array of pointers.
• Since pointers are the variables that store the address, thus,
array of pointers is the collection of addresses.
• Syntax : data_type *array_name[size];
• Example 1 : int *x[6]; // x is an array of 6
integer pointers.
• Example 2 : int arr[] = {2, 1, 8, 10};
• int *ptr[]= {arr, arr+1, arr+2, arr+3};

Prof Imran Qureshi 126


Dynamic Memory Allocation
(DMA)
• The process of allocating memory at run time is
known as Dynamic Memory Allocation.
• Consider an array declaration : int arr[20];
• This reserves 40 bytes(20 elements * 2 bytes
each) for arr in the memory. But we may not use
all the storage space. In such case there is
wastage of the memory space. On the other
hand, if we wan to store 30 elements, then there
is no way to increase the array size during
program execution.
• Such problems can be solved by the use of
dynamic memory allocation technique.

Prof Imran Qureshi 127


Please Note..

Pointer gives the depth in Programming

Prof Imran Qureshi 128


Strings
Concept :
• A string is an array of characters stored in
consecutive memory locations.
• In strings, the ending character is always
the null character ‘\0’. The null character
acts as a string terminator.

Prof Imran Qureshi 130


Declaration of Strings
• Syntax : char string_name[length];
• Example : char name[5];
• This example declares an array name
which can store at the most 5 characters.

Prof Imran Qureshi 131


Initialization :
• Character arrays can be initialized in two ways – as
individual characters or as single sring.
• Example :
• char greet[10] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘!’};
• char greet[10] = “hello!”;
• char greet[ ] = “hello!”; //This declaration
automatically assigns storage
//equivalent to 7 characters including ‘\0’ to the
character //array greet.
• Note : A string of n elements can hold (n-1) characters
as nth character is always ‘\0’.
• The compiler automatically stores the null character at
the end of the string. Memory representation of char
greet[ ] = “hello!”; is as follows:
• hello!\0

Prof Imran Qureshi 132


String Input and Output
• Till now, we have seen how to read (input) different type of numeric
values.
• Now we will see how to read characters and strings from the
terminal.
• We are familiar with two standard functions for reading input and
writing output – scanf( ) and printf( ) respectively.
• These functions with format specifiers %c and %s can be used for
input and output of characters and strings.
• Examples : char color [6];
• scanf(“%c”, &color); // reading character
• scanf(“%s”, color ); //reading string
• printf(“%c”, color); //writing character
• printf(“%s”, color); //writing string
• We have seen other I/O functions for character and string –
getchar, putchar, gets, puts in the Chapter 2.

Prof Imran Qureshi 133


Various Operations on Characters
Example Out Meaning
put
x=a; 97 Ascii value of a in integer form.
printf(“%d”, x);
x=’z‘-1; y Ascii of z is 122, 122-1 = 121= y
printf(“%c”, x);
ch>=’A’&& - Tests whether character ch is in
ch<=’Z’ upper case or not.

Prof Imran Qureshi 134


Character Related Functions
Function Meaning
isalnum(c) Is the character alphanumeric?
isalpha(c) Is the character an alphabet?
isascii(c) Is the character an ascii character?
isdigit(c) Is the character a digit?
islower(c) Is the character a lower case letter?
isupper(c) Is the character a upper case letter?
isspace(c) Is the character a space?
ispunct(c) Is the character a punctuation?
isprint(c) Is the character printable?
tolower(c) It convert the uppercase character into lowercase character
toupper(c) It convert the lowercase character into uppercase character

Prof Imran Qureshi 135


Various Operations Possible on Strings
• There are various operations that can be performed on strings as
follows:
1. To find length of string (for general purpose)
2. To copy content of one string to another (for general purpose)
3. To change the case of letters in the strings (for general purpose)
4. To do encryption and decryption operation with string (for security
purpose)
5. To find out tokens from the string (for compiler purpose)
6. To do some string manipulation and rearranging the strings (for
networking purpose)
7. To search match (for editing as well as searching purpose)
• Above mentioned operation requires following string operations.
string3 = string1 + string2 But these operations are not allowed in C
str3 = str1 + “hello”; either for combining the strings or
comparing
if(str1= =str2) them.
if(str1 = = “hello”)

Prof Imran Qureshi 136


String Handling Functions
Function Meaning

strlen(s1) Returns the length of the string s1 excluding the null character.

strlwr(s1) Converts the string s1 to lower case.

strcat(s1, s2) Appends a copy of string s2 to the end of s1 and terminates s1


with a null and returns s1.

strcmp(s1, s2) Compares s1 and s2 and returns -ve if s1<s2, +ve if s1>s2, 0 if
s1=s2.
strcpy(s1, s2) Copies the string s2 into string s1, modifying the string s1.

strcmpi(s1, s2) Compares s1 and s2 ignoring the case and returns similar result
as strcmp

strncmp(s1, s2, n) Compares the first n characters of string s1 and s2 and returns
similar result as strcmp.

strupr(s1) Converts the string s1 to uppercase

Prof Imran Qureshi 137


String Handling Functions
Function Meaning
strchr(s1, c) Returns a pointer to the first occurrence of the character c in
string s1
strrchr(s1, c) Returns a pointer to the last occurrence of the character c in
string s1
strstr(s1, s2) Returns a pointer to the first occurrence of the string s2 in
string s1
strrev(s1) Returns the reverse string of string s1.
strtok(s1, s2) Searches s1 for tokens that are separated by delimiters
specified in s2. Returns the pointer to first character of first
token in s1.
strset(s1, c) Sets all characters in string s1 to character c and quits when
null character is detected.

strnset(s1, c, n) Sets the first n characters in string s1 to character c and quits


when null character is detected. If n>length of s1, then
length of s1 replaces n.

sscanf(buff,contro Divide lines into tokens.


l
string,paramet
ers) Prof Imran Qureshi 138
Strings and Pointers
• String is an array of characters, thus, the name
of the string is the constant pointer to the string.
• But we can also use pointers to point to the
strings. But that same pointer can be later on
used to point some where else. Thus pointer is
not constant pointer.
• Example :
• char color[] = “red”; //color is the name of the
string
• char *color = “red”; //color is the pointer

Prof Imran Qureshi 139


Array of Strings
• Table of strings is called as Array of strings.
• Example :
• char name[3][10] = {“Sharada”, “Neelima”, “Tech Max”};
• //(Array of strings)Two dimensional
array of strings
• name is an array of 3 strings; each containing 10
characters. The total storage for name requires 30
bytes as below :

A r p i t a \0

S h a r a d a \
0
S I B A R M C A \
0

Prof Imran Qureshi 140


Use of Pointers in handling array
of strings :
• We know that all the strings in the array are of not equal length or say that all
the
• strings do not require the total 10 spaces. Thus instead of assigning fixed length
to each
• string, we can make a pointer to string of varying length. This is the main use of
pointers i.e. handling the array of strings.
Example :
char *name[3] = {“Sharda”, “Neelima”, “Tech Max”};
//Pointer handling the array of strings
• name is the pointer pointing to the array of strings with 3 strings; each
containing varying number of characters. This declaration allocates total of only
24 bytes as below :

M A N I S H \0
N e e l i m a \0
A v a n t i k a \0

Prof Imran Qureshi 141


Please Note..

We make a living by what we get,

but we make a life by what we Give.

Prof Imran Qureshi 142


C PreProcessor
Concept
• What is the need of C preprocessor? The answer is contained in its name
itself. Preprocessor is a program that processes our source program before it
is passed to the compiler.
• The 4 major functions of C preprocessor are:
• Macro substitution
• File inclusion
• Conditional compilation
• Error generation
• C Preprocessor is a collection of special statements called directives. Either it
can be an independent program or its functionality may be embedded in the
compiler. Each of these preprocessor directives begins with a # symbol.They
are as follows:
#include directive
#define directive
#undef directive
#error directive
• Conditional compilation directives :These directives can placed anywhere in
the program but are most often placed at the beginning of the program before
the main( ) function or before the beginning of any particular function.
• The actual purpose of the C preprocessor is to expand the source program.

Prof Imran Qureshi 144


File Inclusion
• If we have a very large program; it is good to keep
different sections in separate files. These files are
included in the beginning of the main program file.
• Many times we use some functions or some macro
definitions almost in all programs. In such a case,
commonly needed functions and macro definitions can
be stored in a file and that file can be included wherever
necessary.

Prof Imran Qureshi 145


Macro Substitution
• This directive replaces every occurrence of a simple macro in the
program. It is obtained using #define directive.
• Syntax: #define macro-name
value
• Macro Macro
Macro
definition template
expansion
• This statement replaces the macro-name with the given value
wherever it appears - from the first blank after the macro-name to
the end of the file.

Prof Imran Qureshi 146


Advantages of Macros :
• Macros are very useful when you use a
value repeatedly in a program and you
want it to be constant through out the
execution.
• Macros are also used for easy
understanding of a program to a new user.
You can use macros instead of user
defined words.

Prof Imran Qureshi 147


Macros with Arguments
#include<stdio.h>
#define AREA(x) 3.14*x*x
main()
{
float r=7.5, a;
a=AREA(r);
printf("\nArea=%f",a);
}

Prof Imran Qureshi 148


Nested Macro
#define SQUARE(X) (X * X)
#define CUBE(X) (SQUARE(X) * X) //
Nested Macro

Prof Imran Qureshi 149


Difference between Macros and
Functions:
1. Macros are small and do not extend beyond one line where as
functions occupy lot of space.
2. When we call a function at program execution time, the control is
passed to the function and after processing the function, a value is
returned back. All this processing takes time. But by using macros,
the C preprocessor first replaces the macro_name with the value
and then compiles it. Thus including the macros in the program
speeds up the execution.
3. As macros are preprocessed first and then compiles but functions
are directly compiled, sodata type checking is performed with the
functions but not with the macros. Hence, function give type-
compatibility and macros don’t.

Prof Imran Qureshi 150


Undefining a Macro
• A defined macro can be undefined.
• Syntax : #undef identifier
• This is used when we want to restrict the
definition only to a particular part of the
program.
• Example : #undef JKL //removes the
macro definition JKL

Prof Imran Qureshi 151


Conditional Compilation
• This directive causes one file to be included in another.
• It allows selective inclusion of lines of source text on the basis of a
computed condition. Conditional compilation is performed using the
preprocessor directives;
• #ifdef
• #ifndef
• #elif
• #else
• #endif
• #ifndef is opposite of the #ifdef directive. #ifdef includes the code if the
identifier is defined before but #ifndef includes the code if the identifier has
not been defined before.
• #elif is similar to else if construct.
• #define jkl 20 is not always correct. Because, if this macro jkl is already
defined, then this statement gives an error. So, first check whether this
macro is already defined and if yes then remove it and define it again as
you wish:

Prof Imran Qureshi 152


Error Generation
• This directive displays the error message
on occurrence of error.
• Syntax : #error sequence-of-token

Prof Imran Qureshi 153


Please Note..

A good plan of today is better than a great plan of tomorrow

Look backward with satisfaction

and look forward with confidence.

Prof Imran Qureshi 154


Our months are dissimilar suitcases

all of the different sizes,

but some special people can pack more into them than others

Structures and Unions


Concept of Structure
• Structure is a collection of logically related data items of
different data types grouped together under a single
name.
• Structure is analogous to records. As the records contain
different fields, the data items that make up a structure
are called its members or fields.
• Syntax of Structure Definition :
struct structure_name
{
data_type member1;
data_type member2;
……………..
};
• Syntax of Structure Variable declaration :
struct structure_name sv1,sv2,sv3;

Prof Imran Qureshi 156


Structure Initialization
struct book struct book
{ {
char title[15]; char title[15];
char author[10]; char author[10];
int pages; int pages;
float price; float price;
}; }b1={“Magnefying C”,”Dr Arpita
struct book b1, b2,b3; Gopal”,476,325.0};
void main() void main()
{ b1.pages=10; { b1.pages=10;
b1.price=23.0; b1.price=23.0;
… …
} }

Prof Imran Qureshi 157


Array of Structure-variables
(Array of structures)
• If we need the details of 100 books, then it
is difficult to declare 100 structure
variables using the above two methods,
but this problem can be solved by array
declaration of structure variables. We can
declare array of structures just like we
declare array of integers or array of
variables of any other data-type.

Prof Imran Qureshi 158


Nested Structures
struct date struct book
{ {
int month, day, year ; char title[15];
}dt1; struct date
struct book {
{ int month, day, year ;
char title[15]; }dt1;
struct date dt1; float price;
float price; }b1;
}b1;

By using this method structure date By using this method any function not
acts as global declaration and it is directly access structure date.
involved by all functions.

Prof Imran Qureshi 159


Prof Imran Qureshi 160
Passing Structures to Functions
• Structures can be passed to a function as a parameter
and also can be returned by functions. This can be done
in two ways:
1. Passing individual structure members
2. Passing structure as a whole
• Passing Individual Structure Members
– In this method, we can pass structure members as arguments to
a function call and in this process, these individual structure
members are treated as separate non-structure values.
• Passing Structure as a Whole
– In this method, we can pass the entire structure to a function by
simply providing the name of the structure variable as the
argument in the function call.

Prof Imran Qureshi 161


Pointers and Structures
• Pointers to Structures
• Till now, we have learnt pointer to variables and pointer to arrays. In
a similar manner, we can also have pointer to structures. This
pointer points to the starting address of the structure. We can
declare a pointer to structure using ‘&’ operator.
struct book
{
char title[15];
char author[10];
int pages;
float price;
}b1, *bptr; //*bptr is a pointer to struct book
bptr = &b1;

Prof Imran Qureshi 162


Access thru Variable or pointers
Member Using structure Using structure pointer
variable

Simple b1.title; (*bptr).title; bptr -> title;


variable

Array stu1.marks[0]; (*sptr).marks[0]; sptr->marks[0]


variable

Embedded b1.dt1.month; (*bptr). dt1.month; bptr ->


structure dt1.month;

Prof Imran Qureshi 163


Pointers within a Structure
• A structure can contain pointers as members.
• Example :
• struct book
• {
• char title[15];
• char *author;
• int *pages;
• float price;
• }b1;
• Such pointer members can be accessed as below:
• b1.pages = 120;
• b1.author = “Arpita”;

Prof Imran Qureshi 164


Array of Pointers to Structure
• This is useful in dynamic memory allocation, which saves a lot of
memory space.
Example :
struct book
{
char title[15];
char author[10];
int pages;
float price;
} *ptr[20];
• Here, ptr is an array of 20 pointers to struct book. We should use
this method when there is large number of books and we don’t know
their actual quantity. In such cases, declaring array of pointers to
structures avoids the memory wastage. Thus, we can dynamically
allocate space for ‘n’ no. of books.

Prof Imran Qureshi 165


Unions
• Unions like structures are the user defined data type and
somewhat similar to structures as they also contain
members of different data types.
• Only difference is that - all members in the Union share
the same storage area in the computer’s memory while,
each member in the Structure is assigned its own unique
storage area.
• Since the members of the union share the same
memory, only one member can be active at a time.
• Thus, Unions are useful as they efficiently use the
computer’s memory. They are useful in cases where you
have to include multiple members provided the values
need not be assigned to all the members at any one
time.

Prof Imran Qureshi 166


union union_name union book union book
{ { {
data_type char title[15]; char title[15];
member1; char *author; char author[10];
data_type int pages; int pages;
member2; float price; float price;
………………. } b1, b2,b3; } b1, *bptr;
}var1, var2, …; Or union book
*bptr;

■ Accessing union members


■ Example : printf(“%s”, b1.title); //union variable accessing
union member.
■ printf(“%s”, bptr -> title); //union pointer variable accessing
union member.

Prof Imran Qureshi 167


Operations on Unions
• A union variable can be assigned to another
union variable.
• Address of the union variable is obtained
using the addressof (&) operator.
• It is possible to pass a union to function and
a function can return a union.
• We can use pointer to unions and pointer
within unions as seen in the above examples.

Prof Imran Qureshi 168


Difference between Unions and Structures
Unions Structures

All members in the Union share the Each member in the Structure is
same storage area in the computer’s assigned its own unique storage area.
Example: Assume struct
Union SS{
UU{int
inta;a;
memory . float b; char c; } then sizeof SS would
UU(Union)
be >7 bytes would be 4dependendent-if
(compiler bytes.
Allocates the memory equal
int,float, char to as
are taken the
2,4,1) Allocates the memory equal to total
maximum memory required by the memory (sum of the memory)required
member. by all the members.
Only one member can be active at a All members can be active at a time.
time.
Only the first member of a union All members of a structure variable can
variable can be initialized. be initialized.

Conservation of memory. Occupies lot of memory space.

Prof Imran Qureshi 169


Please Note..

Our months are dissimilar suitcases

all of the different sizes,

but some special people can pack more into them than others

Prof Imran Qureshi 170


Command Line Arguments
Concept
• Arguments that are passed to the program when the
program is invoked are called command line arguments.
That is, these arguments are passed from the command
line during run time.
• When there is a need to pass information into a program
while you are running it, then the information can be
passed into the main( ) function through the two built in
arguments:
• int argc : Argument count which contains the number of
arguments in the command
• line(number of arguments passed to the program),
including the command name.
• char *argv[ ] : Argument vector is an array which
contains address of each arguments. It is an array of
character pointers that point to the command line
arguments. Size of thisProfarray is equal to the value of 172
Imran Qureshi
argc.
Declaration of main( )
• To declare the main( ) function with
arguments:
• Syntax:
main(int argc, char *argv[ ])
{
………….
.…………
}

Prof Imran Qureshi 173


• #include<stdio.h>
• void main(argc,argv)
• int argc;
• char *argv[];
• {
• if(argc==1)
• {
• printf("\nYou forgot to type your name\n");
• exit();
• }
• printf("\n Hello %s",argv[1]);
• }

Output :
• #cc name.c
• #./a.out
• You forgot to type your name
• #./a.out Raj
• Hello Raj

Prof Imran Qureshi 174


Advantages
1. Since arguments are supplied at run time, you are
allowed to pass different type of arguments at different
times.
2. There is no restriction on number of arguments to be
passed.
3. There is no need to change the code in the program to
work with different command line arguments.
4. You can run the same program through command line
by referring it with different file names(the file names are
supplied at runtime) since the code in the program here,
is actually referred by argv[0] and not by the file name
you are giving.
5. There is no need to recompile the program each time
you run it, because the source code is not changed; only
the arguments passed to the program are changed.
Prof Imran Qureshi 175
Disadvantages
1.You cannot pass the information to the
program without using the keyboard.
2.Every program is not suitable to run
through command line arguments

Prof Imran Qureshi 176


Thanck you!

Please Note..

Achievement always comes to the person

who is looking for it

but not to the person

who is just waiting for it

Prof Imran Qureshi 177


File Handling
Streams
• In C, the stream is an interface between the programmer and the
device. This device is a file. Thus a stream is a logical interface to a
file.
• A file may refer to a disk file or a file on tape, and so on. Even
though the files are different, the buffered file system transforms
each into a logical device called a stream. Thus, although files differ
in form and capabilities, all streams are the same.
• A stream is linked to a file using an open operation. A stream is
disassociated from a file using a close operation.
• There are two types of streams - text (is a sequence of characters
organized in lines. In these streams, certain character translations
may occur as required and thus there may not be one-to-one
correspondence between stream and what's in the file) and binary
(is a sequence of bytes used with any type of data, no character
translation, one-to-one correspondence between stream and file).

Prof Imran Qureshi 179


Files
• Need of Files : Till now we have discussed console I/O functions where we take
input from the user and display output to the screen. This is ok till we work with small
amount of data. But real life situations involve dealing with large amounts of data. In
such cases, it is necessary to store the data permanently so that user can access
and alter that data if required. Thus, there is need of files as it stores large amount of
data permanently.
• File : It is a collection of information stored in the secondary memory, having some
filename, which is stored in the directory. Whatever information is present on the
secondary memory is called as a physical file. One copy of that file is also kept in to
the primary memory is called as a logical file.
• File types : Stream-oriented (High-level) and System-oriented (low-level).
• The functions that deal with or that handle the files are called as disk I/O functions.
There are various file handling functions available in the C library. They are classified
as: High level file I/O functions (do their own buffer management) and Low level
file I/O functions (buffer mgmt. is done by the programmer). A buffer is a block of
memory where the data to be stored in the file is placed temporarily.
• The low level disk I/O functions are more closely related to the computer’s operating
system rather than high level disk I/O functions.

Prof Imran Qureshi 180


Files

Prof Imran Qureshi 181


Difference between Text and
Binary Modes
Text Mode Binary Mode
It is a sequence of characters. It is a sequence of bytes
Data is separated into lines All data is read and written with no
separation.
Character translation occurs. New line is No character translation occurs.
converted to carriage return + line
feed.
Thus, no one to one correspondence. Thus, one to one correspondence.
Special character whose ASCII value is No special character is used to indicate
26 automatically inserted to indicate the end of file. The end of file is
the end of file. detected from the no. of bytes in the
directory entry of the file.
Characters are stored one byte per A character occupies 1 byte, integer
character or one byte per digit. occupies 2 bytes, and float 4 bytes.
E.g. An integer 1234 occupies 4 bytes(1 E.g. An integer 1234 occupies 2 bytes.
byte per character)
Prof Imran Qureshi 182
Operations on Files
1. Naming the file
2. Opening the file: Opening the files in various modes.
3. Reading the content of the file: Reading the data from the file.
4. Writing the content into the file: Writing the data to the file.
5. Re writing the content into the file: Writing the new content on old content of
the files.
6. Updating the file: Changing some content of the records of the file.
7. Searching some element in the file: Searching the location of record or byte
in the file.
8. Rearranging the contents of the file: Sorting the records in
ascending/descending order.
9. Modifying the contents of the file: Changing the data if it is wrong.
10. Appending the file: Writing additional data to the end of the file.
11. Closing the file: Closing the file that is opened to perform any of the above
operations.

Prof Imran Qureshi 183



File Concept
File Name :Generally, a file can be identified by its name. This name is divided into
two parts - file name and extension. File name is any name; normally it consists of
alphabets and digits. Special characters are also allowed. But these rules depend on
the operating system. The extension is given to specify the file’s type. For example
exe will be the extension of executable file or dat is extension of data file.
• Examples : fibo.c employee.dat info.out
• File Pointer
• Before opening the file, we will have to create a file pointer.
• Syntax : FILE *fptr;
• FILE is a structure defined in the header file ”stdio.h”. This header file stores the
complete information about the files i.e. name of the file, the mode it is opened in,
starting buffer address, a character pointer that points to the character being read.
Each file opening has its own file structure area. Before processing any file, it should
be opened.
– Opening a File
• No operation can be performed on the file when it is on the disk. For performing any
operation on that file, you should bring the copy of that file (from disk) on to the
memory and only then you can perform any operation on that file.
• Thus, bringing the copy of the file from disk to memory is called Opening the file. And
the opposite is called the Closing the file i.e. closing the file on the memory.

Prof Imran Qureshi 184


Mode Meaning File Modes
r Open a text file for reading only. If the file doesn’t exist, it returns null.
w Opens a file for writing only. If the file exists, then all the contents of that
file are
destroyed and a new fresh blank file is prepared on the disk with the same
name
and the same blank file is copied on the memory and now it is ready to be
written
any thing. If the file doesn’t exist, a new blank file is created and opened
for
writing. Returns null if it is unable to open the file.
a Appends to the existing text file i.e. adding data at the end of the file If the
file
doesn’t exist then a new file is crated. Returns null if it is unable to open
the file.
rb Open a binary file for reading.
wb Open a binary file for writing.
ab Append to a binary file
r+ Opens a text file for read/write
w+ Opens the existing text file or Creates a text file for read/write.
a+ Append or create a text file for read/write
r+b Open a binary file for read/write
Prof Imran Qureshi 185
Open a file and Closing a File
To open a file and associate it with a stream, use fopen().
Syntax : FILE *fopen(char *fname,char *mode);
The fopen() function, like all the file-system functions, uses the header stdio.h . The name of the file to
open is pointed to by fname (must be a valid name). The string pointed at for mode determines how
the file may be accessed.

Example :
FILE *fp;
if ((fp = fopen("myfile", "r")) = =NULL)
{
printf("Error opening file\n");
exit(1);
}
To close a file and disassociate it with a stream, use fclose().
Syntax : fclose(FILE *fp);
The fclose() function closes the file associated with fp, (which must be a valid file pointer previously
obtained using fopen()) and disassociates the stream from the file. The fclose() function returns 0 if
successful and EOF (end of file) if an error occurs.
The fcloseall() closes all the files opened previously.
Example :
FILE *fptr;
char filename[]= "myfile.dat";
fptr= fopen (filename,"w");
…….
……….
fclose (fptr);

Prof Imran Qureshi 186


• End of File
– A file contains a large amount of data. Thus, we some times cannot
detect the end of file. In text files, a special character EOF denotes
the end-of-file. And it can be detected as:
– Example :
• while ( !feof(fp) )
• fscanf(fp,"%s",line);

• String I/O Functions in Files A file


• The fgets() and fputs() functions can be used for string I/O.
• Syntax : char *fgets(char *str, int n, FILE *fptr);
• This statement reads character from the stream fptr into to the
character array ‘str’ until a new line character is read or end of file is
reached or n-1 characters have been read.
• Syntax : fputs(const char *str, FILE *fptr);
• This statement writes to the stream fptr except the terminating
null character of string ‘str’.

Prof Imran Qureshi 187


• Character I/O Functions in Files
– The getc() and putc() functions can be used to
handle one character at a time.
– Syntax : putc(ch, fptr); // writes character
contained in the character variable ch to the file
associated with FILE pointer fptr.
– Syntax : ch = getc(fptr);
• Numeric I/O Functions in Files
– The getw() and putw() functions can be used to read
and write integer or numeric quantity from the file.
– Syntax :
– int_var=getw(fptr);
– putw(integer, fptr);

Prof Imran Qureshi 188


Formatted High Level Disk I/O
Functions
• The fprintf() and fscanf() functions are
identical to printf() and scanf(), only
difference is that they work on files.
• Syntax :
– fprintf(fptr, char *control-string, ...);
– fscanf(fptr, char *control-string ...);
• where, fptr is a file pointer associated with the file
that has been opened for writing or reading.

Prof Imran Qureshi 189


How to create new file :
• Step 1 : Initialize the variables
• Step 2 : Open file in output mode
• Step 3 : Accept information from user
• Step 4 : Write it into the file
• Step 5 : Repeat steps 3 and 4
according to user’s choice
• Step 6 : Stop procedure.

Prof Imran Qureshi 190


How to read contents from existing
file
• Step 1 : Initialize the file variables
• Step 2 : Open file in read mode
• Step 3 : Accept information from file
• Step 4 : Write it into the output device
• Step 5 : Repeat steps 3 and 4 till file is
not ends
• Step 6 : Stop procedure.

Prof Imran Qureshi 191


Updating the Files

Step 1 : Initialize the file variables


Step 2 : Open master file in read write mode
Step 3 : Open transaction file in to read mode
Step 4 : Adjust file pointers of master file at beginning of the file
(i.e. first record)
Step 5 : Adjust file pointers of transaction file at the first record.
Step 6 : Read information from master file
Step 7 : Search new information in transaction file according to
primary key.
Step 8 : Update the master file
Step 9 : Repeat steps 5 to 9 till file is not ends.
Step 7 : Stop procedure.

Prof Imran Qureshi 192


Modifying the Files
• Step 1 : Initialize the variables
• Step 2 : Open file in read write mode
• Step 3 : Read information from file
• Step 4 : Print it
• Step 5 : Check whether the information is wrong or
not?
• If wrong, accept Correct information from user
• Move the file pointer to the start of
record or information
• Re-write it that means new information
into the file
• If not wrong, go to the Step 6.
• Step 6 : Repeat steps 3 to 6 till file is not ends.
• Step 7 : Stop procedure.

Prof Imran Qureshi 193


Serial access file (Non Random access files
structured file) (Structured file)
It stores data serially no matter if it It stores data randomely , generally
is text or some number.These these files are the collection of
files are some times divided into records , records are again
the lines some times it is divided divided into the fields and field
into the records or some times it can store elementary data items.
is just divided into the bytes.
Size of all lines or records are not Size of all records are same, so we
same or their structure is also not can easily calculate the address
decided so their address could not of any record of the files if we
be calculated even if we knows knows the address of first record.
the address of the first record.
It not waist any memory. It makes size of all records same so
for small information or record
memory is waisted
It supports to serial access of the It supports to randome access of the
record or lines. record or lines.

It is slow because of serial access It is fast because of random access.

Prof Imran Qureshi 194


Serial access file (Non Random access files
structured file) (Structured file)
It supports to contiguous allocation It supports the contiguous allocation
of the files.as well as linked of the file as well as linked
allocation of the file. allocation of the file.
It gives better performace for linked It gives poor performance for the
allocation of the file. linked allocation.\ of the file
It was used by early operating Now all modern operating system
system. uses these techniques.
For accessing these files it will not For accessing these files it will
required any extra software required special software who
overhead, because these files are knows the structure of that file.
not having any special structure.
Examples: text files, machine Examples: text files, picture files
language files or some data base images animation or data base
files. files.
The fgets, fpus, fscanf, fprintf, The fwrite ,fread, fseek functions are
getc,putc fuctions are used in the used in the C languages.
C language

Prof Imran Qureshi 195


The functions that allow random access are –
fseek(), ftell(), rewind().
• void rewind(FILE *fptr); // Positions a file's current location to
the start of the file.
• ftell(FILE *fptr); //Tells where the pointer is positioned
right now.
• fseek(FILE * fptr, long offset, int reference); //Moves the pointer
from one record to another. The first argument is the file pointer.
Second argument is the offset which tells the compiler by how many
bytes the pointer should be moved from a particular position. The
third argument is the reference from which the pointer should be
offset. It can be:
• SEEK_END moves the pointer from end of file.
• SEEK_CUR moves the pointer from the current position.
• SEEK_SET moves the pointer from the beginning of the
file.

Prof Imran Qureshi 196


• fflush() function removes the data from
the buffer temporarily.
• rename() function renames the filename.
• remove() function deletes the specified
file.

Prof Imran Qureshi 197

Potrebbero piacerti anche