Unit - 2
Unit - 2
1
C-PROGRAMMING
2
STRINGS
A String is defined as a collection of
characters. In C language, a character
array itself treated as a 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:
Result:
6
STRING INPUT/OUTPUT FUNCTIONS
7
gets() function:
Syntax: gets(string);
Example: gets(str);
8
puts() function:
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:
Result:
11
STRING HANDLING FUNCTIONS
12
1. strlen() function:
#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:
Syntax:
strcat(TargetString,SourceString);
#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:
Syntax:
strcpy(TargetString,SourceString);
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:
22
6. strrev() function:
Syntax: strrev(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:
Syntax: strlwr(String);
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:
Syntax: strupr(String);
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 :
31
Example :
char x[3][10]=
32
While initializing array of strings, size1 can
be omitted. In such cases, compiler allocates
sufficient memory by counting number of
initialized strings.
33
STRING / DATA CONVERSION FUNCTIONS
34
atoi() function:
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:
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:
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.
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.
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
45
Advantages:
46
FUNCTION TYPES:
Functions
Library User-defined
Functions Functions
47
A) LIBRARY FUNCTIONS
Examples: scanf()
printf()
getch()
getche() etc.,
48
Some of the important header files are:
50
i) isalnum():
Syntax: isalnum(ch)
Syntax: isalpha(ch)
Syntax: isdigit(ch)
Syntax: isspace(ch)
Syntax: islower(ch)
Syntax: isupper(ch)
Syntax: tolower(ch)
57
vii) toupper():
Syntax: toupper(ch)
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
62
i) sin():
Syntax: sin(d)
Syntax: cos(d)
Syntax: tan(d)
Syntax: log(d)
Syntax: log10(d)
Syntax: sqrt(d)
Syntax: exp(d)
Syntax: ceil(d)
Syntax: floor(d)
Syntax: pow(d1,d2)
#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:
75
B) USER DEFINED FUNCTIONS
1. Function prototype
2. Function call
3. Function definition
76
1. Function Prototype
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:
(or)
int Fact(int);
79
2. Function Call
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,
83
Example:
int Fact(int k)
{
int i,f=1;
for(i=1;i<=k;i++)
f=f*i;
return f;
}
84
Note:
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
92
Note:
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.
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.
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.
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
Syntax:
#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
Example:
main()
{
---
---
main();
---
}
105
Recursion can be classified into two
types as:
1. Direct recursion
2. Indirect recursion
106
1. Direct recursion
109
Disadvantages:
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
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
118
Storage class deals with scope and life
time of variables with four access specifiers
namely auto, extern, static and register.
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.
122
Note:
#include<stdio.h>
#include<conio.h>
main()
{
auto int x=100;
clrscr();
printf(“\nValue = %d”,x);
}
124
2. External Storage class
126
Note:
127
/* EXAMPLE PROGRAM FOR EXTERNAL VARIABLES */
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“\nValue = %d”,x);
}
128
3. Static Storage class
130
Note:
131
a) Internal Static Variables:
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:
134
/* EXAMPLE PROGRAM FOR
EXTERNAL STATIC VARIABLES */
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“\nValue = %d”,x);
} 135
4. Register Storage class
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
139
Syntax:
Example:
#define PI 3.14159
140
Note:
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
143
Constant variable
Syntax:
const datatype variablename = Value;
#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;
#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
Example: int x;
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:
150
POINTER
151
Pointer Declaration
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;
154
Initializing a Pointer
Syntax:
ptrvariable = &ordinaryvariable;
155
156
Accessing variable value through pointer:
Example:
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:
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.
162
3. Pointer variable comparisons with relational
operators are valid.
163
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;
#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
167
PASSING PARAMETERS TO FUNCTIONS
168
1. Call 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.
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:
172
2. Call 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.
174
#include<stdio.h>
#include<conio.h>
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:
176
POINTERS AND ARRAYS
178
Array subscripts can also be defined in terms of
pointer arithmetic operations which are known as
indexing 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
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
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
186
1. Passing individual element of the array as
an argument:
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:
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
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
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.
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:
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
206
Dynamic memory allocation functions are
defined in stdlib.h and alloc.h header files.
1. malloc()
2. calloc()
3. realloc()
4. free()
207
1. malloc() function:
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));
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));
Syntax:
ptrvariable = (casttype*)realloc(ptrvariable,newsize);
Where,
The newsize may be larger or smaller than the
previous size.
214
Note:
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:
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
219
Structure Declaration and Definition
221
Example:
struct Book
{
char BName[10];
int Pages;
float Price;
};
222
The general format of defining a structure variable is:
Syntax:
223
Now, the compiler allocates memory for the
structure variable B1 as:
224
Accessing members of the structure
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:
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
Example:
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
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
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.
Example : P → Acno;
242
The same representation can also be placed
with dot operator is as:
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);
246
TYPEDEF (TYPE DEFINITION)
Syntax:
Where,
ExistingDataType may be either a primitive
data type of user-defined data type.
247
Example: 1. typedef int Integer;
Integer x,y,z;
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.
Complex k;
249
SELF-REFERENTIAL STRUCTURE
251
Syntax: struct Tag
{
Datatype Member1;
- -
struct Tag *Member;
};
253
Union Declaration and Definition
255
Example:
union Book
{
char BName[10];
int Pages;
float Price;
};
256
The general format of defining a union variable is:
Syntax:
257
Now, the compiler allocates memory for the union
variable B1 as:
258
Accessing members of the union
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();
#include<stdio.h>
#include<conio.h>
#include<string.h>
266