0% found this document useful (0 votes)
41 views265 pages

Unit - 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views265 pages

Unit - 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 265

C-PROGRAMMING

1
C-PROGRAMMING

Unit-III: Strings, string handling functions, and


Command line arguments.
Functions, types of functions, Recursion and
argument passing
Unit-IV&V:pointers, storage allocation, pointer
to functions, expressions involving pointers,
Storage classes – auto, register, static, extern,
Structures, Unions,

2
STRINGS
A String is defined as a collection of
characters. In C language, a character
array itself treated as a string.

The general form of declaration of a


string variable is:

Syntax: char StringName [size];

Example: char str[10];


3
 %s format specification is used to read
and write a string.
 The ampersand ‘&’ symbol is not
required before the variable name in
scanf() function while reading strings.
 Each string is terminated by the null
character (‘\0’), which indicates the end of
the string.

4
/* PROGRAM TO READ AND PRINT A STRING */

#include<stdio.h>
void main()
{
char city[10];
printf("\nEnter A String =");
scanf("%s",city);
printf("\nRESULT = %s",city);
}

5
Result:

Input: Enter A String = Kavali

Output: RESULT = Kavali

Result:

Input: Enter A String = New Delhi

Output: RESULT = New

6
STRING INPUT/OUTPUT FUNCTIONS

gets() and puts() library functions are


known as string input/output functions.

These library functions information is


available in stdio.h header file.

7
gets() function:

gets() is a library function used for


reading an entire line as a string including
blank spaces.

The general format of a gets() function is:

Syntax: gets(string);

Example: gets(str);
8
puts() function:

puts() is a library function used for


displaying an entire line as a string including
blank spaces.

The general format of a puts() function is:

Syntax: puts(string);

Example: puts(str);
9
/* PROGRAM TO READ AND PRINT A STRING */

#include<stdio.h>
void main()
{
char city[10];
printf("\nEnter A String =");
gets(city);
printf("\nRESULT = “);
puts(city);
}

10
Result:

Input: Enter A String = Kavali

Output: RESULT = Kavali

Result:

Input: Enter A String = New Delhi

Output: RESULT = New Delhi

11
STRING HANDLING FUNCTIONS

string.h header file provides various


library function that are used for
manipulating the given strings in different
ways.

12
1. strlen() function:

It refers to string length function.

Syntax: int strlen(string);

Function accepts a single argument as


string and return length of the passed string.
Here, function counts number of
characters as length includes blank spaces
and excluding the NULL character (‘\0’).
13
/* PROGRAM TO FIND LENGTH OF THE GIVEN STRING */

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s[50];
int n;
printf("\nEnter a string =“);
gets(s);
n=strlen(s);
printf("\nSTRING LENGTH IS = %d",n);
} 14
2. strcat() function:

It refers to string concatenation function.

Syntax:
strcat(TargetString,SourceString);

Function is used to add the given two


strings. Here, the contents of the source
string are added at the end of the target
string.
15
/* String Concatenation Function*/

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);
strcat(str1,str2);
printf("\n Result String = %s”,str1);
} 16
3. strcpy() function:

It refers to string copy function.

Syntax:
strcpy(TargetString,SourceString);

Function is used to copy the contents


of one string into another string. Here, the
contents of source string are copied into the
target string.
17
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("\nEnter string 1:");
gets(str1);
strcpy(str2,str1);
printf("\n Result String = %s”,str2);
}
18
4. strcmp() function:

It refers to string comparison function.

Syntax: int strcmp(String1,String2);

Function is used to compare the given two strings.

If the two strings are identical, function returns 0


value. If they are not identical, function returns
numerical difference between the ASCII values of the
first non-matching characters.

19
/* String Comparison*/

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
int k;
clrscr();
printf("\nEnter string 1:");
gets(str1);
printf("\nEnter string 2:");
gets(str2);

20
k=strcmp(str1,str2);
if(k = = 0)
printf("\n BOTH STRINGS ARE SAME");
else
printf("\nBOTH STRIGNS ARE DIFFERENT");
}

21
5. strcmpi() function:

It refers to string comparison ignore case


function.

Syntax: int strcmpi(String1,String2);

Function is used to compare the given two


strings without case consideration.

22
6. strrev() function:

It refers to string reverse function.

Syntax: strrev(String);

Function is used to reverse the contents of


the given string.

23
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String:");
gets(str);
strrev(str);
printf("\n Reverse String =");
puts(str);
}
24
7. strlwr() function:

It refers to string lower function.

Syntax: strlwr(String);

Function is used to convert all characters in


the given string from upper case to lower case
characters.

25
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String in Upper Case:");
gets(str);
strlwr(str);
printf("\nResult String in Lower Case =");
puts(str);
} 26
8. strupr() function:

It refers to string upper function.

Syntax: strupr(String);

Function is used to convert all characters in


the given string from lower case to upper case
characters.

27
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[10];
clrscr();
printf("\nEnter a String in Lower Case:");
gets(str);
strupr(str);
printf("\nResult String in Upper Case =");
puts(str);
} 28
TWO DIMENSIONAL ARRAY OF CHARACTERS /
ARRAY OF STRINGS
Collection of strings is treated as two
dimensional array of characters (or) array of
strings.

Syntax: char stringname[size1][size2];


Where,
Size1 represents maximum number of strings and
size2 represents maximum number of characters in
each string.

Example: char str[10][50];


29
Initialization of Array of Strings

The general format of initializing array of


strings is:

Syntax :

char arrayname[size1][size2] = {“string1” ,


“string2” , ……… };

Example: char x[3][10]={ “India” ,


“Pakistan”};
30
Array of strings can also be initialized in the
form of array of characters.

Syntax: char arrayname[size1][size2] =


{ {‘char1’ , ‘char2’ , …… , ‘\0’} ,
{‘char1’ , ‘char2’ , …… , ‘\0’} ,
---
---
{‘char1’ , ‘char2’ , …… , ‘\0’}
};

31
Example :

char x[3][10]=

{ {‘I’ , ‘n’ , ‘d’ , ‘i’ , ‘a’ , ‘\0’} ,


{‘P’ , ‘a’ , ‘k’ , ‘i’ , ‘s’ , ‘t’ , ‘a’ , ‘n’ , ‘\0’} ,
{‘S’ , ‘r’ , ‘i’ , ‘l’ , ‘a’ , ‘n’ , ‘k’ , ‘a’ ,’\0’}
};

32
While initializing array of strings, size1 can
be omitted. In such cases, compiler allocates
sufficient memory by counting number of
initialized strings.

Example: char x[][10]=

{ {‘I’ , ‘n’ , ‘d’ , ‘i’ , ‘a’ , ‘\0’} ,


{‘P’ , ‘a’ , ‘k’ , ‘i’ , ‘s’ , ‘t’ , ‘a’ , ‘n’ , ‘\0’} ,
{‘S’ , ‘r’ , ‘i’ , ‘l’ , ‘a’ , ‘n’ , ‘k’ , ‘a’ ,’\0’}
};

33
STRING / DATA CONVERSION FUNCTIONS

stdlib.h (standard library header file)


header file supports various library functions
that are used to convert the given strings
into other forms and vice-versa.

34
atoi() function:

atoi() function converts a string of


digits into an integer value.

Syntax: int atoi(string);

Function accepts a string as an


argument and returns the result value as an
integer.

35
/* EXAMPLE PROGRAM FOR atoi() FUNCTION*/

#include<stdio.h>
#include<stdlib.h>
void main()
{
char x[10]="2009";
int k;
k=atoi(x)+6;
printf("\nRESULT VALUE:%d",k);
}

36
atol() function:

atoi() function converts a string of


digits into a long integer value.

Syntax: long int atol(string);

Function accepts a string as an


argument and returns the result value as a
long integer.

37
/* EXAMPLE PROGRAM FOR atol() FUNCTION*/

#include<stdio.h>
#include<stdlib.h>
void main()
{
char x[10]="2009";
long int k;
k=atol(x)+6;
printf("\nRESULT VALUE:%ld",k);
}

38
atof() function:

atoi() function converts a string of


digits into a real value.

Syntax: float atof(string);

Function accepts a string as an


argument and returns the result value as a
real value.

39
/* EXAMPLE PROGRAM FOR atof() FUNCTION*/

#include<stdio.h>
#include<stdlib.h>
void main()
{
char x[10]="2009";
float k;
k=atof(x)+6;
printf("\nRESULT VALUE:%f",k);
}

40
itoa() function:
itoa() function converts an integer
value into a string.

Syntax: char * itoa(int , char[] , int);

Where,
First argument is an integer value used for
conversion.
Second argument is a string used to store the
conversion value.
Third argument is an integer value that represents
format of conversion such as decimal, octal and hexa-
decimal format.
41
/* EXAMPLE PROGRAM FOR itoa() FUNCTION*/

#include<stdio.h>
#include<stdlib.h>
void main()
{
char x[10];
int k=49;
itoa(k,x,10);
printf("\nDecimal Format:");
puts(x);
}

42
ltoa() function:
ltoa() function converts a long integer
value into a string.

Syntax: char * ltoa(long int , char[] , int);

Where,
First argument is a long integer value used for
conversion.
Second argument is a string used to store the
conversion value.
Third argument is an integer value that represents
format of conversion such as decimal, octal and hexa-
decimal format. 43
/* EXAMPLE PROGRAM FOR ltoa() FUNCTION*/

#include<stdio.h>
#include<stdlib.h>
void main()
{
char x[10];
long int k=49;
ltoa(k,x,10);
printf("\nDecimal Format:");
puts(x);
}

44
FUNCTIONS

A function is a self-contained program


segment that carries out some specific,
well-defined task.

C program consists of one or more


functions. One of these functions must be
called by main() function.

45
Advantages:

 Avoid repetition of codes.


Increases program readability.
Divide a complex problem into simpler ones.
Reduces chances of error.
Create, Modify and debugging a program
becomes easier by using function.
It can be executed any number of times.

46
FUNCTION TYPES:

Functions

Library User-defined
Functions Functions

47
A) LIBRARY FUNCTIONS

Functions those are predefined by the


system compiler are known as library
functions.

Examples: scanf()
printf()
getch()
getche() etc.,

48
Some of the important header files are:

stdio.h : Standard Input and Output header file

conio.h : Console Input and Output header file

stdlib.h : Standard library header file

ctype.h : Character type header file

math.h : Mathematical header file etc,


49
ctype.h : Character type header file

ctype.h header file provides several


library functions used for character testing
and conversions.

50
i) isalnum():

Syntax: isalnum(ch)

Where, ch is a character type variable.

Function determines whether the given


argument is alpha numeric or not.

If the character is alpha numeric, it returns a


non-zero value that represents TRUE; otherwise,
it returns ‘0’ that represents FALSE.
51
ii) isalpha():

Syntax: isalpha(ch)

Where, ch is a character type variable.

Function determines whether the given


argument is alphabet or not.

If the character is alphabet, it returns a non-


zero value that represents TRUE; otherwise, it
returns ‘0’ that represents FALSE.
52
iii) isdigit():

Syntax: isdigit(ch)

Where, ch is a character type variable.

Function determines whether the given


argument is digit or not.

If the character is digit, it returns a non-zero


value that represents TRUE; otherwise, it returns
‘0’ that represents FALSE.
53
iv) isspace():

Syntax: isspace(ch)

Where, ch is a character type variable.

Function determines whether the given


argument is space or not.

If the character is space, it returns a non-


zero value that represents TRUE; otherwise, it
returns ‘0’ that represents FALSE.
54
v) islower():

Syntax: islower(ch)

Where, ch is a character type variable.

Function determines whether the given


argument is in lower case or not.

If the character is in lower case, it returns a


non-zero value that represents TRUE; otherwise,
it returns ‘0’ that represents FALSE.
55
vi) isupper():

Syntax: isupper(ch)

Where, ch is a character type variable.

Function determines whether the given


argument is in upper case or not.

If the character is in upper case, it returns a


non-zero value that represents TRUE; otherwise,
it returns ‘0’ that represents FALSE.
56
vii) tolower():

Syntax: tolower(ch)

Where, ch is a character type variable.

Function converts the given argument


from upper case to lower case character.

57
vii) toupper():

Syntax: toupper(ch)

Where, ch is a character type variable.

Function converts the given argument


from lower case to upper case character.

58
/* Program to count number of alphabets, digits
and special symbols of a given line */

#include<stdio.h>
#include<conio.h>
#include<ctype.h>

main()
{
char ch[50];
int na,nd,ns,i;
clrscr();
printf(“\n Enter A Line = “);
gets(ch);
59
na=0;
nd=0;
ns=0;
for(i=0;ch[i]!=‘\0’;i++)
{
if(isalpha(ch[i]))
na=na+1;
else if(isdigit(ch[i]))
nd=nd+1;
else
ns=ns+1;
}
printf(“\n Number of Alphabets = %d”,na);
printf(“\n Number of Digits = %d”,nd);
printf(“\n Number of Special Symbols = %d”,ns);
} 60
Result:
Enter A Line =
PBR VITS @ 1998.

Number of Alphabets =7
Number of Digits =4
Number of Special Symbols = 5

61
math.h : Mathematical header file

math.h header file provides several


library functions used for mathematical
operations.

62
i) sin():

Syntax: sin(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the sine value as
double.

Example: printf(“Value = %lf”, sin(45));


63
ii) cos():

Syntax: cos(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the cosine value as
double.

Example: printf(“Value = %lf”, cos(45));


64
iii) tan():

Syntax: tan(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the tangent value as
double.

Example: printf(“Value = %lf”, tan(45));


65
iv) log():

Syntax: log(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the natural logarithm
(base e) value as double.

Example: printf(“Value = %lf”, log(10));


66
v) log10():

Syntax: log10(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the logarithm (base
10) value as double.

Example: printf(“Value = %lf”, log10(10));


67
vi) sqrt():

Syntax: sqrt(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the square root value
as double.

Example: printf(“Value = %lf”, sqrt(16));


68
vii) exp():

Syntax: exp(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the e to the power d
value as double.

Example: printf(“Value = %lf”, exp(6));


69
viii) ceil():

Syntax: ceil(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the value rounded up
to the next lowest integer as double.

Example: printf(“Value = %lf”, ceil(3.1));


70
ix) floor():

Syntax: floor(d)

Where, d is a double data type argument.

Function receives a double type


argument and returns the value rounded
down to the previous highest integer as
double.

Example: printf(“Value = %lf”, floor(3.1));


71
x) pow():

Syntax: pow(d1,d2)

Where, d1,d2 are double data type arguments.

Function receives two double type


arguments and returns the d1 raised to the
d2 power value as double.

Example: printf(“Value = %lf”, pow(3,4));


72
/* Write a program to evaluate the expression
1 + X + X2 + X3 + - - - - - */

#include<stdio.h>
#include<conio.h>
#include<math.h>

main()
{
int x,n,i;
double sum,term;
clrscr();
printf("\nEnter How Many Terms = ");
scanf("%d",&n);
printf("\nEnter X Value = ");
scanf("%d",&x); 73
sum=1.0;
for(i=1;i<n;i++)
{
term=pow(x,i);
sum=sum+term;
}
printf("Expression Result = %.2lf",sum);
}

74
Result:

Enter How Many Terms =


3
Enter X Value =
2

Expression Result = 7.00

75
B) USER DEFINED FUNCTIONS

User-defined functions are defined by


the user according to their requirements.

While defining functions, function


places are classified into three parts as:

1. Function prototype
2. Function call
3. Function definition
76
1. Function Prototype

Function prototype specifies the


declaration statement of the function that
intimates to the compiler about function
information before executed it.

Function prototype includes function


name, list of arguments and type of the data
returned.

77
Syntax:
ReturnType FunctionName(datatype arg1, - - , datatype argn);

Where,
 FunctionName is the name given to the
function, which allows the same rules as valid
identifier.
 ReturnType specifies the type of the data
returned from the function to calling function.
 datatype arg1, - - - - are the arguments used
to perform the function implementation.
Argument names arg1, -- , argn are optional.
78
Example:

int Fact(int X);

(or)

int Fact(int);

79
2. Function Call

The function call statement invokes the


function by passing arguments.

The arguments which passed at the


function call are called “actual arguments”.

80
Syntax:
VariableName = FunctionName(value1, value2, - - - , valuen);

Where,
 value1,value2, - - -, valuen are actual values passed
to the function definition.

Example: p = Fact(5);

(or)

p = Fact(N);

81
3. Function Definition
Function definition contains actual
implementation code of the function.
Syntax:
ReturnType FunctionName (datatype arg1, - - - , datatype argn)
{
Local Variable Declarations
----
- - - - (Implementation Code)
----
return value;
}
82
Where,

 arg1, arg2, --- , argn arguments are known


as “formal / temporary arguments”. List of
values passed from the function call are
temporarily stored in these formal parameters.
 Variables declared in the function definitions
are called local variables.
 After completing implementation of the
function, it should return a value to the calling
function with a return statement.

83
Example:

int Fact(int k)
{
int i,f=1;
for(i=1;i<=k;i++)
f=f*i;
return f;
}

84
Note:

Function call is treated as the calling


function and function definition is treated as the
called function.

85
/* Write a program to calculate factorial of a given value
using functions */

#include<stdio.h>
#include<conio.h>

int Fact(int);

main()
{
int p,n;
clrscr();
printf("\nEnter a Value = ");
scanf("%d",&n);
p=Fact(n);
printf("\nFactorial Value = %d",p);
} 86
int Fact(int k)
{
int i,f=1;
for(i=1;i<=k;i++)
f=f*i;
return f;
}

87
Result:

Enter A Value =
4

Factorial Value = 24

88
/* Write a program to calculate NcR value */

#include<stdio.h>
#include<conio.h>

int Fact(int);

main()
{
int p,n,r;
clrscr();
printf("\nEnter N & R Values = ");
scanf("%d%d",&n,&r);
p=Fact(n)/((Fact(r) * Fact(n-r));
printf("\nResult Value = %d",p);
}
89
int Fact(int k)
{
int i,f=1;
for(i=1;i<=k;i++)
f=f*i;
return f;
}

90
FUNCTION CATEGORIES

Depending on whether arguments are passed


or not and function returns any value or not,
functions are classified into different categories as:

1) Functions without arguments and without return


value
2) Functions with arguments and without return
value
3) Functions without arguments and with return
value
4) Functions with arguments and with return value
91
Case 1: Functions without arguments and
without return value.

In this case, calling function does not


send any data to the called function.
Similarly after implementation of the
function, called function does not return any
value to the calling function.

92
Note:

i) If the function does not return any


value, return type must be void.

ii) Default return type of a function is int.

93
#include<stdio.h>
#include<conio.h>

void sum();

main()
{
clrscr();
sum();
}
void sum()
{
int x,y,z;
printf("\nEnter Two Values =");
scanf("%d%d",&x,&y);
z=x+y;
printf("\nResult = %d",z);
} 94
Case 2: Functions with arguments and
without return value.

In this case, calling function send data


to the called function. After implementation
of the function, called function does not
return any value to the calling function.

This type of communication is referred


as downward flow communication.

95
#include<stdio.h>
#include<conio.h>

void sum(int,int);

main()
{
int x,y;
clrscr();
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
sum(x,y);
}
void sum(int p,int q)
{
int z;
z=p+q;
printf("\nResult = %d",z);
96
}
Case 3: Functions without arguments and
with return value.

In this case, calling function does not


send data to the called function. After
implementation of the function, called
function returns value to the calling function.

This type of communication is referred


as upward flow communication.

97
#include<stdio.h>
#include<conio.h>

int sum();

main()
{
int p;
p=sum();
printf("\nResult = %d",p);
}
int sum()
{
int x,y,z;
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
z=x+y;
return z;
98
}
Case 4: Functions with arguments and
with return value.

In this case, calling function send data


to the called function and called function
also returns a value to the function call after
completing the function implementation.

This type of communication is referred


as bi-directional flow communication.

99
#include<stdio.h>
#include<conio.h>

int sum(int,int);

main()
{
int x,y,z;
printf("\nEnter Two Values:");
scanf("%d%d",&x,&y);
z=sum(x,y);
printf("\nResult = %d“,z);
}
int sum(int p,int q)
{
int r;
r=p+q;
return r;
100
}
NESTED FUNCTIONS

Functions can also be included within


another function. Such a representation is known
as nested functions.

Syntax:

main() Fun1() Fun2()


{ { {
-- - --- ---
-- - Fun2(); ---
Fun1(); --- }
-- - }
} 101
/* EXAMPLE PROGRAM FOR NESTED FUNCTIONS */

#include<stdio.h>
#include<conio.h>

void fun1();
void fun2();

main()
{
clrscr();
printf("\nMAIN STARTS");
fun1();
printf("\nMAIN ENDS");
} 102
void fun1()
{
printf("\nFUNCTION 1 STARTS");
fun2();
printf("\nFUNCTION 1 ENDS");
}

void fun2()
{
printf("\nFUNCTION 2 STARTS");
printf("\nFUNCTION 2 ENDS");
}

103
Result:

MAIN STARTS
FUNCTION 1 STARTS
FUNCTION 2 STARTS
FUNCTION 2 ENDS
FUNCTION 1 ENDS
MAIN ENDS

104
RECURSION

A function calls itself is known as recursion


and the function is called as recursive function.

Example:
main()
{
---
---
main();
---
}
105
Recursion can be classified into two
types as:

1. Direct recursion
2. Indirect recursion

106
1. Direct recursion

A function calls itself directly is known


as direct recursion.

Example: void sum()


{
----
sum();
----
----
} 107
2. Indirect recursion

A function calls another function, which


initiates to call of the initial function is known
as indirect recursion.

Example: void sum() void Fun()


{ {
---- ----
Fun(); sum();
---- ----
---- }
} 108
Advantages:

The main advantage of recursion is to


reduce the length of the code.

109
Disadvantages:

1. Recursion uses more memory


space compare to non-recursive functions.

2. While using recursion, control may


falls into infinite loop. This disadvantage
can be avoided by placing a return
statement associated with if-else statement
somewhere to force the control without
calling recursive call.
110
In recursion concept, two types of
conditions must be placed as: base
condition and recursive condition.

Base condition avoids the recursive


call and recursive condition calls the
recursive procedure.

111
/* PROGRAM TO PRINT FACTORIAL OF A GIVEN NUMBER
USING RECURSION */

#include<stdio.h>
#include<conio.h>

int Fact(int);

main()
{
int p,k;
clrscr();
printf(“\nEnter a Value =”);
scanf(“%d”,&k);
p=Fact(k);
printf(“\nFactorial Value =%d”,p);
} 112
int Fact(int n)
{
if(n= =1)
return 1;
else
return n*Fact(n-1);
}

113
Result:

Enter a Value =
4

Factorial Value = 24

114
Local Variable Vs Global Variable

Local Variable: Variables declared inside the


function definition or block is called local
variables. Local variables can be used by only
that particular function or block where it was
defined.

Global Variable: Variables declared outside


the function definition are called global variables.
Global variables can be used by any function at
any time.
115
#include<stdio.h>
#include<conio.h>

void change();

main()
{
int x=10;
clrscr();
printf(“\nValue 1 = %d”,x);
change();
printf(“\nValue 2 = %d”,x);
}
void change()
{
x = 20;
printf(“\nValue 3 = %d”,x);
} 116
#include<stdio.h>
#include<conio.h>

void change();
int x=10;

main()
{
clrscr();
printf(“\nValue 1 = %d”,x);
change();
printf(“\nValue 2 = %d”,x);
}
void change()
{
x = 20;
printf(“\nValue 3 = %d”,x);
} 117
STORAGE CLASSES

Scope of a variable defines in which


parts of the program a variable is actually
available for use.

Life-time of a variable defines at what


extent the variable can be alive without
destroying.

118
Storage class deals with scope and life
time of variables with four access specifiers
namely auto, extern, static and register.

Storage class access specifiers provide


access permission of the variables.

119
C language supports four access
specifiers as: auto, extern, static and
registers those are used with data type in
the declaration statement of a variable.

Hence, the storage classes are termed as:

1. Automatic Storage class


2. External Storage class
3. Static Storage class
4. Register Storage class 120
1. Automatic Storage class

Variables declared inside the function


or block starts with the keyword ‘auto’ are
termed as automatic variables.

The general format of an automatic


variable is:

Syntax : auto datatype identifier;

Example : auto int x;


121
 Place of declaration: Inside the function / block

 Memory Allocation: Memory unit

 Default value: Garbage value

 Scope : Only within the function / block

 Life time: Until end of the function / block

122
Note:

1. Automatic variables are created when the


function is called and destroyed automatically
when the function is exited. Therefore, automatic
variables are local to the function in which they
are declared. So that automatic variables are
also known as local or internal variables.

2. Variables declared inside the function or


block without a storage class specification, by
default compiler assigns ‘auto’ keyword and
treated as automatic variables.
123
/* EXAMPLE PROGRAM FOR AUTOMATIC VARIABLES */

#include<stdio.h>
#include<conio.h>

main()
{
auto int x=100;
clrscr();
printf(“\nValue = %d”,x);
}
124
2. External Storage class

Variables declared outside the function


with the keyword ‘extern’ are termed as
external variables.

The general format of an external


variable is:

Syntax : extern datatype identifier;

Example : extern int x;


125
 Place of declaration: Outside of the function

 Memory Allocation: Memory unit

 Default value: Zero

 Scope : Entire file and other files also

 Life time: Until the program execution


comes to end (global)

126
Note:

1. External variables are declared outside of


all functions. Hence, an external variable is also
known as a global variable.

2. Variables declared outside the function


without a storage class specification, by default
compiler assigns ‘extern’ keyword and treated as
external variables.

127
/* EXAMPLE PROGRAM FOR EXTERNAL VARIABLES */

#include<stdio.h>
#include<conio.h>

extern int x = 100;

main()
{
clrscr();
printf(“\nValue = %d”,x);
}
128
3. Static Storage class

Variables declared inside the function


or outside the function with the keyword
‘static’ are termed as static variables.

The general format of a static variable


is:

Syntax : static datatype identifier;

Example : static int x;


129
 Place of declaration:

Inside / Outside the function

 Memory Allocation: Memory unit

 Default value: Zero

130
Note:

1. The main advantage of static variable is for


retaining updated values between the function
calls.

2. Depending on the place of declaration,


static variables are classified into two types as:

a) Internal static variables


b) External static variables

131
a) Internal Static Variables:

Variables declared inside the function with


‘static’ access specifier are known as internal
static variables.

The scope of internal static variable is up to


the end of the function in which they are defined
and life time is throughout the remainder of the
program.

132
/* EXAMPLE PROGRAM FOR
INTERNAL STATIC VARIABLES */

#include<stdio.h>
#include<conio.h>

main()
{
static int x=100;
clrscr();
printf(“\nValue = %d”,x);
}
133
b) External Static Variables:

Variables declared outside the function with


‘static’ access specifier are known as external
static variables.

The scope of external static variable is only


in that file and the life time is global.

134
/* EXAMPLE PROGRAM FOR
EXTERNAL STATIC VARIABLES */

#include<stdio.h>
#include<conio.h>

static int x=100;

main()
{
clrscr();
printf(“\nValue = %d”,x);
} 135
4. Register Storage class

Variables declared inside the function


or block starts with the keyword ‘register’
are termed as register variables.

The general format of a register


variable is:

Syntax : register datatype identifier;

Example : register int x;


136
 Place of declaration: Inside the function / block

 Memory Allocation: Register unit

 Default value: Garbage value

 Scope : Only within the function / block

 Life time: Until end of the function / block

137
/* EXAMPLE PROGRAM FOR REGISTER VARIABES */

#include<stdio.h>
#include<conio.h>

main()
{
register int x=100;
clrscr();
printf(“\nValue = %d”,x);
}
138
SYMBOLIC CONSTANTS

Symbolic constant is a constant


representation that does not change during
program execution.

#define statement is used for defining


symbolic constants.

139
Syntax:

#define symbolicname constantvalue

Example:

#define PI 3.14159

140
Note:

 Symbolic names have the same form as a


valid identifier.

 No blank space between # and define.

 #define statements must not end with a


semicolon.

 Symbolic names are not declared with data


types.

141
/* EXAMPLE PROGRAM FOR SYMBOLIC CONSTANTS */

#include<stdio.h>
#include<conio.h>

#define PI 3.14159

main()
{
double R,Area;
clrscr();
printf(“\nEnter Radius of the Circle =”);
scanf(“%lf”,&R);
Area=PI*R*R;
printf(“\n Area of the Circle =%.2lf”,Area);
} 142
TYPE QUALIFIERS

C provides three type qualifiers const,


volatile and restrict that describes nature
of the identifiers to the compiler.

Here, const and volatile qualifiers can


be applied to any variables, but restrict
qualifier can be applied only on pointer
variables.

143
Constant variable

A variable value can be made unchanged


during program execution by declaring it as a
constant. For this the keyword const is
placed before the variable declaration.

Syntax:
const datatype variablename = Value;

Example: const int x = 10;


144
/* EXAMPLE PROGRAM FOR CONSTANT VARIABLE */

#include<stdio.h>
#include<conio.h>

main()
{
const int x=10;
clrscr();
printf(“\nResult = %d”,x);
}
145
Volatile variable
Variables that can be changed at any
time by external programs or the same
program are called as volatile variables.
For this the keyword volatile is placed
before the variable declaration.

Syntax:
volatile datatype variablename;

Example: volatile int x; 146


/* EXAMPLE PROGRAM FOR VOLATILE VARIABLE */

#include<stdio.h>
#include<conio.h>

main()
{
volatile int x=10;
clrscr();
printf(“\nResult 1= %d”,x);
x=20;
printf(“\nResult 2= %d”,x);
}
147
POINTERS

Accessing Address of a Variable:

Example: int x;

The address of a variable is accessed with


address operator &, which is a unary operator
preceded by the variable. Address of the variable
is always unsigned integer.

Example: &x;
148
/* EXAMPLE PROGRAM FOR ADDRESS OPERATOR */

#include<stdio.h>
#include<conio.h>

main()
{
int x;
clrscr();
printf("\nAddress of x =%u",&x);
x=10;
printf("\nValue of x = %d",x);
}

149
Note:

1. The address operator & can be used only


with a simple variable (or) an array element.

2. Address operator cannot act upon


constants, and arithmetic expression.

Example: &125 → INVALID


&(x+y) → INVALID

150
POINTER

A pointer is a variable which holds the


memory address of another variable.

151
Pointer Declaration

A pointer variable is declared by


preceding its name with an asterisk *
symbol.

The symbol indicates that the variable


is a pointer variable.

152
Syntax: datatype *ptrvariable;

Where,
ptrvariable is name of the pointer variable
that follows same rules as a valid identifier.
‘*’ tells the compiler that ptrvariable is a
pointer variable.
datatype is the type of the data that the
pointer is allowed to hold the address.

153
Example: int *ptr1;
float *ptr2;
char *ptr3;

Note: Any type of pointer occupies only 2


bytes of memory. Since, pointer holds address of
the variable which is always an unsigned integer.

154
Initializing a Pointer

Syntax:

ptrvariable = &ordinaryvariable;

Example: int *ptr, x;


ptr = &x;

155
156
Accessing variable value through pointer:

The value of a variable can be


accessed through pointer variable using a
unary operator ‘*’, usually known as
indirection operator. The operator refers
to “value at the address in”.

Example:

*ptr refers to value at the address in ptr.


157
/* PROGRAM TO DEMONSTRATE POINTERS CONCEPT */

main()
{
int x,*ptr;
clrscr();
printf("\nAddress of x is:%u",&x);
printf("\nAddress of ptr is:%u",&ptr);
x=10;
printf("\nx value using x:%d",x);
ptr=&x;
printf("\nValue in p:%u",ptr);
printf("\nx value using ptr:%d",*ptr);
} 158
/* Program to demonstrates every pointer variable occupies
same (2 bytes) amount of memory space */

#include<stdio.h>
#include<conio.h>
main()
{
char *p;
int *q;
float *r;
double *s;
clrscr();
printf(“\n Size of Char Pointer Variable = %d Bytes”,sizeof(p));
printf(“\n Size of Int Pointer Variable = %d Bytes”,sizeof(q));
printf(“\n Size of Float Pointer Variable = %d Bytes”,sizeof(r));
printf(“\n Size of Double Pointer Variable = %d Bytes”,sizeof(s));
}
159
POINTER ARITHMETIC OPERATIONS

Valid Operations:

1. Addition or Subtraction of an integer value


from a pointer variable is valid. In these cases,
one operand is a pointer variable and other
operand is an integer value.
When the value is added / subtracted from a
pointer variable, the value is in terms of the length
of the data type pointed by the pointer variable.
The final value is termed as a “Scale Factor”.
160
Example: int *p, x;
p = &x;
p = p+2;
p = p-1;

Assume p = 65242

p = 65242 + 2 * 2
= 65246

p = 65242 – 1 * 2
= 65240

161
2. A pointer variable can be subtracted from
another pointer variable.

Example: int *p1,*p2, x, y, z;


p1 = &x;
p2 = &y;
z = p1 – p2;

162
3. Pointer variable comparisons with relational
operators are valid.

Example: int *p1,*p2, x, y;


p1 = &x;
p2 = &y;
p1 < p2
p1 > p2
p1 <= p2
p1 >= p2
p1 == p2
p1 != p2 are valid operations.

163
Invalid Operations:

1. Multiplication of a pointer variable with an


integer value is invalid operation.

2. Division of a pointer variable with an integer


value is invalid operation.

3. Addition, Multiplication and division of two


pointer variables are invalid operations.

164
VOID POINTER
A void pointer is a special type of pointer
that can points to any data type variables.
Syntax: void *ptrvariable;

Example: void *ptr;


int X;
float Y;
ptr = &X;
ptr = &Y;

For accessing value of the variable with the


pointer variable, type casting must be placed to
refer the specific data item. 165
/* EXAMPLE PROGRAM FOR VOID POINTER */

#include<stdio.h>
#include<conio.h>

main()
{
int x=10;
double y=3.45678;
void *ptr;
clrscr();
ptr=&x;
printf("\nValue 1 =%d",*(int *)ptr);
ptr=&y;
printf("\nValue 2 =%lf",*(double *)ptr);
} 166
NULL POINTER

A pointer variable can also be initialized in


such a way that it does not point to any data type.
Such a pointer is known as a NULL pointer.

Null pointer is assigned by using the


predefined constant NULL; which is defined by
several header files including stdio.h, stdlib.h and
alloc.h.

Example: int *p=NULL;

167
PASSING PARAMETERS TO FUNCTIONS

Arguments can be passed to a function in


two ways. Those are,

1. Call by value (or) Pass by value


2. Call by address (or) Pass by address

168
1. Call by value:

The process of passing actual value of


the variable as an argument to a function is
known as call by value (or) pass by value.

169
In this mechanism, a copy of the value is
passed from calling function to the called
function. Now, this value is stored temporarily in
the formal argument of the called function.

At this stage, if we made any changes inside


the function definition with the received value,
those changes are not effect on the original
variable. Entire changes effected only on the
formal arguments of the called function.

170
#include<stdio.h>
#include<conio.h>

void change(int,int);

main()
{
int x,y;
clrscr();
printf(“\nEnter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\nBefore Passing to the Function = ");
printf("\nx value:%d\ny value:%d",x,y);
change(x,y);
printf("\nAfter Passing to the Function = ");
printf("\nx value:%d\ny value:%d",x,y);
}
void change(int p,int q)
{
p=p+5;
q=q+5;
} 171
Result:

Input: Enter Two Values = 15 20

Output: Before Passing to the Function =


x value: 15
y value: 20

After Passing to the Function =


x value: 15
y value: 20

172
2. Call by address:

The processing of passing address of


the variable as an argument to a function is
known as call by address (or) pass by
address.

173
In this mechanism, when we pass address
of the variable as an argument to a function, the
receiving argument at the called function must be
a pointer variable. When the pointer variable
received the address, it points to the actual
variable.

At this stage, if made any changes inside


the function definition; those changes are effected
on the original variable. Since, pointer variable
points the original argument.

174
#include<stdio.h>
#include<conio.h>

void change(int *,int *);

main()
{
int x,y;
clrscr();
printf(“\nEnter Two Values =”);
scanf(“%d%d’,&x,&y);
printf("\nBefore Passing to the Function = ");
printf("\nx value:%d\ny value:%d",x,y);
change(&x,&y);
printf("\nAfter Passing to the Function = ");
printf("\nx value:%d\ny value:%d",x,y);
}
void change(int *p,int *q)
{
*p=*p+5;
*q=*q+5;
} 175
Result:

Input: Enter Two Values = 15 20

Output: Before Passing to the Function =


x value: 15
y value: 20

After Passing to the Function =


x value: 20
y value: 25

176
POINTERS AND ARRAYS

An array name in C language is very much


like a pointer variable.

When an array is declared, the compiler


allocates a base address and sufficient amount of
storage space for storing all the elements of the
array in successive memory locations. The name
of the array is the beginning address (first
element index 0) of the array, called the base
address. So, that the array name is referred to
as an address constant.
177
Here,
x = &x[0] = &x all are referred to the
address location 1000. Hence, in C language
array name itself acts a pointer (Address
constant).

178
Array subscripts can also be defined in terms of
pointer arithmetic operations which are known as
indexing pointers.

For single dimensional arrays, int x[3], i=0;

&x[0] = x+0 x[0] = *(x+0)


&x[1] = x+1 x[1] = *(x+1)
&x[2] = x+2 x[2] = *(x+2)

i.e., &x[i] = x+i x[i] = *(x+i)

Similarly, for double dimensional arrays,

&x[i][j] = (*(x+i)+j) x[i][j] = *(*(x+i)+j) 179


/* PROGRAM TO READ A ONE DIMENSIONAL ARRAY AND PRINT
IT USING POINTERS */

#include<stdio.h>
#include<conio.h>
main()
{
int x[10],i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",x+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf("%5d",*(x+i));
} 180
#include<stdio.h>
#include<conio.h>
main()
{
int x[10],i,n,*p;
clrscr();
p=x;
printf("\nEnter how many numbers:");
scanf("%d",&n);
printf("\nEnter %d Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf("%5d",*(p+i));

} 181
ARRAY OF POINTERS

Array of pointers are used to define more than


one pointer variable that can points to same data type
variables.

Syntax: datatype *ptrvariable[size];


Where,
Datatype specifies type of the data that can be pointed by
each pointer variable.
Ptrvariable is name of the pointer variable that follows
same rules as a valid identifier.
Size represents maximum number of elements.

Example: int *ptr[10]; 182


/* EXAMPLE PROGAM FOR ARRAY OF POINTERS */

main()
{
int i,*p[5],x,y,z;
clrscr();
x=10;
y=20;
z=30;
p[0]=&x;
p[1]=&y;
p[2]=&z;
printf("\nElements Are:");
for(i=0;i<3;i++)
printf("%5d",*p[i]);
} 183
POINTER AND STRINGS

A string is an array of characters that


terminated with a null character ‘\0’. String
means a character array itself; name of the string
refers to base address of the array.

Hence, string address can be stored in


pointer variable so that string contents can also
be accessed with the pointer variable.

184
/* EXAMPLE PROGRAM FOR PONTER TO STRING */

#include<stdio.h>
#include<conio.h>

main()
{
char str[50]="KAVALI",*p;
int i;
clrscr();
p=str;
printf("\nResult string with STR = %s”,str);
printf(“\nResult string with P =%s”,p);
}

185
FUNCTION WITH ARRAYS

Arrays can be passed as an argument in


two ways. Those are:

1. Passing individual element of the array


as an argument
2. Passing entire array as an argument

186
1. Passing individual element of the array as
an argument:

When an individual element of the array is


passed as an argument to a function, it just likes
an ordinary value. In such case, an ordinary
variable is enough to receive at called function.
Then if we made any changes inside the function
with the received value, those changes are not
effected on the original array.

187
/* Example program for passing individual element of
the array as an argument to a function */

#include<stdio.h>
#include<conio.h>

void change(int);

main()
{
int x[10],i,n;
clrscr();
printf("\nEnter How Many Values=");
scanf("%d",&n);
printf("\nEnter %d Elements=",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
188
printf("\nBefore Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
change(x[3]);
printf("\nAfter Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}

void change(int p)
{
p=p+5;
}

189
2. Passing entire array as an argument:

For passing entire array as an argument to


a function, list name of the array and size of the
array at the calling function. In such cases, an
array or pointer is required to receive the array at
the called function. Then if we made changes
inside the function with the received argument,
those changes are effected on the original array.

190
/* Example program for passing entire array as an
argument to a function */

#include<stdio.h>
#include<conio.h>

void sort(int[],int);

main()
{
int x[10],i,n;
clrscr();
printf("\nEnter How Many Values=");
scanf("%d",&n);
printf("\nEnter %d Elements=",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
191
printf("\nBefore Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
sort(x,n);
printf("\nAfter Passing To Function Array Values Are=\n");
for(i=0;i<n;i++)
printf(" %d",x[i]);
}

192
void sort(int p[10],int k)
{
int i,j,temp;
for(i=0;i<=k-2;i++)
{
for(j=i+1;j<=k-1;j++)
{
if(p[i]>p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
}
193
RETURNING MORE THAN ONE VALUE FROM A
FUNCTION

Pointers allow the user to return more than


one value by allowing the arguments to be
passed by address, which allows the function to
alter the values that pointed to and thus return
more than one value from the function.

194
#include<stdio.h>
#include<conio.h>

int* sort(int*,int);

main()
{
int x[5]={77,11,33,88,55},*k,i;
clrscr();
printf("\nBefore Sorting Elements Are:");
for(i=0;i<5;i++)
printf(" %d",x[i]);
k=sort(x,5);
printf("\nAfter Sorting Elements Are:");
for(i=0;i<5;i++)
printf(" %d",*(k+i));
}
195
int* sort(int *p,int n)
{
int i,j,temp;
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if(*(p+i)>*(p+j))
{
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
}
}
}
return p;
}
196
POINTER TO POINTER / MULTIPLE INDIRECTION

A pointer variable that holds address of an ordinary


variable is known as pointer-to-variable.

A pointer variable that holds address of another


pointer variable is known as pointer-to-pointer. For
this, add an asterisk symbol for each level of reference.

197
Example: int x, *p, **q;
x = 10;
p=&x;
q=&p;

198
/* EXAMPLE PROGRAM FOR POINTER TO POINTER VARIABLE */

#include<stdio.h>
#include<conio.h>

main()
{
int a=10,*p,**q;
clrscr();
p=&a;
q=&p;
printf("\nValue with p is:%d",*p);
printf("\nValue with q is:%d",**q);
}

199
POINTER TO FUNCTION
In C language every variable has an address
except register variables.

Similarly, C functions also have an address. This


address is the entry point of the function and used when
the function is called. So, that function can also invoked
by using its address.

200
/* PROGRAM TO DISPLAY THE ADDRESS OF LIBRARY FUNCTIONS */

#include<stdio.h>
#include<conio.h>

main()
{
clrscr();
printf("\nAddress of printf function is:%u",printf);
printf("\nAddress of scanf function is:%u",scanf);
printf("\nAddress of clrscr function is:%u",clrscr);
}

201
/* PROGRAM TO DISPLAY THE ADDRESS OF USER-DEFINED
FUNCTIONS */

#include<stdio.h>
#include<conio.h>

void show();

main()
{
clrscr();
show();
printf("\nAddress of the Function:%u",show);
}
void show()
{
printf("\nFunction Called");
}
202
The address of the function can also be
assigned to a pointer variable. For this, the
general form of declaring the pointer
variable as pointer-to-function is:

Syntax: datatype (*ptrvariable)( );

Here,
ptrvariable is name of the pointer variable
and the parenthesis indicates that it is a pointer
variable to function.

203
#include<stdio.h>
#include<conio.h>

int show(int,int);

main()
{
int x,y,z,(*p)();
clrscr();
x=10;
y=20;
p=show;
z=(*p)(x,y);
printf("\nResult=%d",z);
}
int show(int a,int b)
{
return a+b;
204
}
MEMORY ALLOCATION PROCESS

The program instructions, global and static variables are


stored in a region known as permanent storage area.

Local variables are stored in another region called stack.

The memory spaced located between stack and permanent


storage area is available for dynamic memory allocation during
execution of the program. This free memory region is called as
heap. 205
The memory allocation may be classified as
static memory allocation and dynamic memory
allocation.

Static memory allocation: Memory for the


variables is created at the time of compilation is
known as static memory.

Dynamic memory allocation: Memory for


the variables is allocated at the time of execution
of the program is called dynamic memory.

206
Dynamic memory allocation functions are
defined in stdlib.h and alloc.h header files.

1. malloc()
2. calloc()
3. realloc()
4. free()

malloc(), calloc() and realloc() are memory


allocation functions and free() is a memory
releasing function.

207
1. malloc() function:

malloc() function is used to allocate memory for


the variables at run time.

Syntax: prtvariable = (casttype*)malloc(size);

Where,
ptrvariable is a pointer variable of type casttype.
size represents number of bytes of memory to be
allocated.

208
Example: int *X;

X = (int*)malloc(5*2); (or)
X = (int*)malloc(5*sizeof(int));

Here, malloc() function reserves a single block of


memory with the specified size and returns a pointer of
type void. With this, we can assign it to any type of
pointer variable. By default memory location is filled with
garbage values.
209
/* PROGRAM FOR MALLOC() FUCNTION */
#include<alloc.h>
main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
}
210
2. calloc() function:

calloc() function is used to allocate memory for the


variables at run time.

Syntax: prtvariable = (casttype*)calloc(n , elesize);

Where,
ptrvariable is a pointer variable of type casttype.
n represents number of blocks and elesize
represents block size.

211
Example: int *X;

X = (int*)calloc(5,2); (or)
X = (int*)calloc(5 , sizeof(int));

Here, calloc() function allocates multiple blocks of


storage space with each of same size and by default all
locations are initialized with ‘0’s. If there is not enough
space to allocate, then it returns a NULL pointer.
212
/* PROGRAM FOR CALLOC() FUCNTION */
#include<alloc.h>
main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
} 213
3. realloc() function:

realloc() function provides the altering the size of


the memory allocation and the process is called
reallocation of memory.

Syntax:

ptrvariable = (casttype*)realloc(ptrvariable,newsize);

Where,
The newsize may be larger or smaller than the
previous size.

214
Note:

1. The new memory block may or may not be


begin at the same place as the old one. In case, it is not
able to find additional space in the same region, it will
create the same in an entirely new region and moves the
contents of the old block into the new block.

2. If the function is unsuccessful to allocate the


memory space, it returns a NULL pointer and the original
block is lost.

215
/* PROGRAM FOR REALLOC() FUCNTION */
#include<alloc.h>
main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many numbers:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("\nEnter %d Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
p=(int*)realloc(p,(n+2)*sizeof(int));
printf("\nEnter %d Elements:",n+2);
for(i=0;i<n+2;i++)
scanf("%d",p+i);
printf("\nArray Elements Are:");
for(i=0;i<n+2;i++)
printf(" %d",*(p+i));
} 216
4. free() function:

The memory allocation done by malloc(), calloc()


and realloc() functions at run time are released by
invoking the function free() by the user explicitly.

Syntax: free(ptrvariable);

Example: free(ptr);

217
USES OF POINTERS
 Pointer variable holds address of another variable.
 Pointer enables us to access a variable that is
defined outside the function.
 Pointers support dynamic memory allocation for
saving lot of memory space.
 Pointers allow returning more than one value from a
function.
 Pointers reduce length and complexity of the
program.
 Pointers increase execution speed of the program
etc.

218
STRUCTURE

Structure is a user defined data type


and can be defined as:

“It is a collection of non-homogeneous /


heterogeneous / different data elements
that can be grouped together under a
common name”.

219
Structure Declaration and Definition

General format of a structure declaration is:

Syntax: struct Tag


{
Datatype Member1;
Datatype Member2;
---
---
Datatype Membern;
}; 220
 struct is a keyword used to define structure
declaration.
 Tag is name of the structure that follows
same rules as a valid identifier.
 Members declared inside the structure
declaration are called structure elements (or)
structure members.
 Structure declaration must be ended with a
semicolon.
 Structure is a user-defined data type.

221
Example:

struct Book
{
char BName[10];
int Pages;
float Price;
};

222
The general format of defining a structure variable is:

Syntax:

struct Tag varname1, varname2, - - - - - , varnamep;

Example: struct Book B1;

223
Now, the compiler allocates memory for the
structure variable B1 as:

i.e., Memory is allocated individually for each


member of the structure.

224
Accessing members of the structure

‘.’ Dot operator is used to access members of the


structure with its structure variable. Here dot operator is
also known as member operator (or) period operator.

The general format of accessing a structure


member with structure variable is:

Syntax: structurevariable.member;

Example: B1.Pages;

225
/* EXAMPLE PROGRAM FOR PRINTING BOOK DETAILS
USING STRUCTURE */

#include<stdio.h>
#include<conio.h>

struct Book
{
char BName[50];
int Pages;
float Price;
};

226
main()
{
struct Book B1;
clrscr();
printf("\nEnter Titile of the Book:");
gets(B1.BName);
printf("\nEnter Number of Pages:");
scanf("%d",&B1.Pages);
printf("\nEnter Cost of the Book:");
scanf("%f",&B1.Price);
printf("\nBOOK TITLE:%s",B1.BName);
printf("\nNUMBER OF PAGES:%d",B1.Pages);
printf("\nBOOK COST:%.2f RS",B1.Price);
}
227
Note:

Structure declaration and definition can also be


combined into a single statement. For this, use the
syntax as:

Syntax: struct Tag


{
Datatype Member1;
Datatype Member2;
---
---
Datatype Membern;
}
varname1, varname2, - - - - - , varnamep;
228
#include<stdio.h>
#include<conio.h>

struct Date
{
int Day,Month,Year;
}x;

main()
{
clrscr();
printf("\nEnter Current Day:");
scanf("%d",&x.Day);
printf("\nEnter Current Month:");
scanf("%d",&x.Month);
printf("\nEnter Current Year:");
scanf("%d",&x.Year);
printf("\nTODAY DATE = %d/%d/%d",x.Day,x.Month,x.Year);
}
229
INITIALIZING A STRUCTURE

A structure can be initialized with a list of values at


the time of defining the structure variable.

The general format of initializing a structure is:

Syntax: struct Tag varname = { List of Values };

Example:

struct Book b = {“Let Us C”,350,125.75};

230
/* EXAMPLE PROGRAM FOR INITIALIZING A STRUCTURE */

#include<stdio.h>
#include<conio.h>

struct product
{
int pid;
char pname[10];
float price;
};

main()
{
struct product s1={111,"soap",25.00};
clrscr();
printf("\nProduct Code=%d\n”,s1.pid);
printf(“\nProduct Name=%s\n”,s1.pname);
printf(“\nProduct Cost=%.2f Rs",s1.price);
}
231
NESTED STRUCTURES /
STRUCTURE WITHIN STRUCTURE

When a structure is declared as the member


of another structure, such representation is
known as nested structures (or) structure within
structure.

232
Syntax: struct Outer
{
---
---
struct Inner
{
---
---
}InnerVariable;
---
---
}OuterVariable;
233
Example:

struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st;

234
Dot operator is used to access the members
of the innermost as well as the outermost
structures.

Syntax:

OuterVariable.InnerVariable.InnerMember;

Example: st.Join.d;

235
/*PROGRAM FOR NESTED STRUCTURES */

#include<stdio.h>
#include<conio.h>

struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st;
236
main()
{
clrscr();
printf("\nEnter Name of the Employee:");
gets(st.name);
printf("\nEnter Date of Joining:");
scanf("%d%d%d",&st.Join.d,&st.Join.m,&st.Join.y);
printf("\nEnter Salary of the Employee:");
scanf(“%f”,&st.salary);
printf("\nEMPLOYEE NAME:%s",st.name);
printf("\nSALARY :%.2f RS",st.salary);
printf("\nJOIN DATE :%d / %d / %d",st.Join.d,st.Join.m,st.Join.y);
}

237
/* PROGRAM FOR INITIALIZING NESTED STRUCTURES */

#include<stdio.h>
#include<conio.h>

struct Employee
{
char name[25];
struct Date
{
int d,m,y;
}Join;
float salary;
}st = {“Ravi Kumar”,10,6,2014,23456.25};
238
main()
{
clrscr();
printf("\nEMPLOYEE NAME:%s",st.name);
printf("\nSALARY :%.2f RS",st.salary);
printf("\nJOIN DATE :%d /%d/%d",st.Join.d,st.Join.m,st.Join.y);

239
STRUCTURES AND POINTERS

A structure pointer variable is created as similar


to the creation of a structure variable. A pointer to a
structure is not itself a structure, but it’s a variable
that holds the address of the structure variable.

Syntax: struct Tag *PtrVariable;

Here, PtrVariable can be assigned to any other


structure of the same type, and can be used to
access the members of the structure.

240
Example:

struct Account
{
int Acno;
float AcBalance;
}S, *P;

P = &S;

241
‘→’ Arrow operator is used to access
members of the structure with its pointer variable.
‘→’ operator is formed with the combination of a
minus (-) sign and a greater than(>) symbol.

The general format of accessing structure


member with the structure pointer variable is:

Syntax : PtrVariable → Member;

Example : P → Acno;

242
The same representation can also be placed
with dot operator is as:

Syntax: (*PtrVariable) . Member;

Example: (*P).Acno;

243
/* PROGRAM FOR STRUCTURE POINTER VARIABLE */

#include<stdio.h>
#include<conio.h>
struct Account
{
int Acno;
float AcBalance;
}S={111,35000.75}, *P;

main()
{
clrscr();
P=&S;
printf("\nACCOUNT INFORMATION IS:");
printf("\n%d\t%.2f",P→Acno,P→AcBalance);
} 244
/* PROGRAM FOR ACCESSING STRUCTURE MEMBERS
IN DIFFERENT WAYS */

#include<stdio.h>
#include<conio.h>

struct demo
{
int x;
float y;
char z;
};

245
main()
{
struct demo s={10,345.72,'K'},*p;
clrscr();
printf("\nWith Variable and Dot Operator:");
printf("\n%d\t%.2f\t%c",s.x,s.y,s.z);

p=&s;
printf("\nWith Pointer Variable and Arrow Opeator:");
printf("\n%d\t%.2f\t%c",p→x,p→y,p→z);

printf("\nWith Pointer Variable and Dot Opeator:");


printf("\n%d\t%.2f\t%c",(*p).x,(*p).y,(*p).z);
}

246
TYPEDEF (TYPE DEFINITION)

The typedef keyword allows the user to


specify a new name for the existing data types.

Syntax:

typedef ExistingDataType NewName;

Where,
ExistingDataType may be either a primitive
data type of user-defined data type.
247
Example: 1. typedef int Integer;
Integer x,y,z;

2. typedef char Gender;


Gender x=’F’, y=’M’;

248
Note: typedef keyword is very useful in the case of
user-defined data types like structure. While using
typedef keyword with the structure creation, tag of the
structure is optional.

Example: typedef struct


{
float real, imag;
}Complex;

Complex k;

249
SELF-REFERENTIAL STRUCTURE

A structure in which, at least one


member that points to same structure type
is referred to as a self-referential structure.

251
Syntax: struct Tag
{
Datatype Member1;
- -
struct Tag *Member;
};

Example: struct List


{
int info;
struct List *link;
};
252
UNION

Union is a user defined data type and


can be defined as:

“It is a collection of non-homogeneous /


heterogeneous / different data elements
that can be grouped together under a
common name”.

253
Union Declaration and Definition

General format of a union declaration is:

Syntax: union Tag


{
Datatype Member1;
Datatype Member2;
---
---
Datatype Membern;
}; 254
 union is a keyword used to define union
declaration.
 Tag is name of the union that follows same
rules as a valid identifier.
 Members declared inside the union
declaration are called union elements (or)
union members.
 union declaration must be ended with a
semicolon.
 union is a user-defined data type.

255
Example:

union Book
{
char BName[10];
int Pages;
float Price;
};

256
The general format of defining a union variable is:

Syntax:

union Tag varname1, varname2, - - - - - , varnamep;

Example: union Book B1;

257
Now, the compiler allocates memory for the union
variable B1 as:

In union, compiler selects the member which


occupies highest memory, and that memory is reserved
only. So that, all the members of the union are shared
that common memory.

258
Accessing members of the union

‘.’ Dot operator is used to access members of the


union with its union variable.

The general format of accessing a union member


with union variable is:

Syntax: unionvariable.member;

Example: B1.Pages;

259
/* EXAMPLE PROGRAM FOR PRINTING BOOK DETAILS
USING STRUCTURE */

#include<stdio.h>
#include<conio.h>

union Book
{
char BName[50];
int Pages;
float Price;
};

260
main()
{
union Book B1;
clrscr();

printf("\nEnter Titile of the Book:");


gets(B1.BName);
printf("\nBOOK TITLE:%s",B1.BName);

printf("\nEnter Number of Pages:");


scanf("%d",&B1.Pages);
printf("\nNUMBER OF PAGES:%d",B1.Pages);

printf("\nEnter Cost of the Book:");


scanf("%f",&B1.Price);
printf("\nBOOK COST:%.2f RS",B1.Price);
}
261
Note:

1. The main difference between a structure and


union is in terms of their storage space. In structure,
each member has its own storage location. Whereas. In
union all members shared a common memory.

2. The main advantage of union is to save


memory compared to the structure with same members.

3. A union may be a member of a structure and


structure may by a member of union. These concepts
are referred as union of structures and structure of
unions.
262
COMMAND LINE ARGUMENTS

The arguments that pass to main() function


at the command prompt of the operating system
are called command line arguments.

Syntax: int main(int argc, char *argv[])


{
- - -
- - -
- - -
}
263
 The first argument of main() function argc is
an integer argument called argument counter,
that counts number of arguments passed at the
command prompt.
 The second argument argv is called
argument vector; which is an array of pointer to
strings. Arguments are stored in terms of
strings.
 The arguments passed at the command
prompt are stored in argv[0], argv[1] and so on.
Here, argv[0] is reserved for to store name of
the executing program.
 main() function returns an integer value on
successful completion. 264
/* ADDITION OF GIVEN NUMBERS USING COMMAND LINE ARGUMENTS */

#include<stdio.h>
#include<conio.h>
#include<string.h>

int main(int argc,char *argv[ ])


{
int x,y;
clrscr();
x=atoi(argv[1]);
y=atoi(argv[2]);
printf("\nNumber of arguments:%d",argc);
printf("\nAddition Result:%d",x+y);
return 1;
} 265
THE END

266

You might also like