0% found this document useful (0 votes)
7 views

Unit 3.2 C Notes by Prof. Shahid Masood

Uploaded by

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

Unit 3.2 C Notes by Prof. Shahid Masood

Uploaded by

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

CABSMJ-1001 [2024-25]

Structures
and
Functions
CABSMJ-1001 [2024-25]

Structures can be Passed to and Returned by a Function


Example: Following function accepts two structures and returns
the structure containing larger height:
structures

student largerheight(student s1,student s2)


{ if (s1.height > s2.height)
return s1;
else
return s2;
}

/* Function call */
student s3 = largerheight(s1,s2);
CABSMJ-1001 [2024-25]

Prob:
Write a C program that reads two distances in feet and inch and
adds them using function add().
(Note: 12 inches = 1 foot).
Note: Use the concept of structure.

Example:
Distance1: 4 feet 8 inch
Distance2: 2 feet 6 inch
Sum of these two distances: 7 feet 2 inch
CABSMJ-1001 [2024-25]
/* struct8.c */
#include<stdio.h>
struct distancetype
{ int feet;
int inch;
};
typedef struct distancetype distance;
distance add(distance, distance); /* accepts struct & returns struct */
main()
{ distance d1, d2, d3;
printf("Enter distance-1 (as feet and inches)\n");
scanf("%d %d",&d1.feet,&d1.inch);
printf("Enter distance-2 (as feet and inches)\n");
scanf("%d %d",&d2.feet,&d2.inch);
d3 = add(d1,d2);
printf("Sum of two distances: %d feet %d inch\n",d3.feet,d3.inch);
}
Contd...
CABSMJ-1001 [2024-25]

distance add(distance d1,distance d2)


{ distance d3;
d3.feet = d1.feet + d2.feet;
d3.inch = d1.inch + d2.inch;
if (d3.inch >=12 )
{ d3.feet = d3.feet + d3.inch/12; /* quotient added to feet */
d3.inch = d3.inch%12;
}
return d3; Output
} Enter distance-1 (as feet and inches)
4 8
Enter distance-2 (as feet and inches)
2 6
Sum of two distances: 7 feet 2 inch
CABSMJ-1001 [2024-25]

Prob:
Write a C program that reads two complex numbers in two
structure variables and finds the sum of the complex
numbers using the function sumcomplexnum().

Example:
Complex number-1: 3 + i8
Complex number-2: 5 + i2
Sum of the complex numbers: 8 + i10
/* struct2.c */ CABSMJ-1001 [2024-25]
#include<stdio.h>
struct complexnumtype
{ float real;
float img;
};
typedef struct complexnumtype complexnum;
complexnum sumcomplexnum(complexnum a, complexnum b)
{ complexnum c;
c.real = a.real + b.real;
c.img = a.img + b.img;
return c;
}
main()
{ complexnum a, b;
printf("Complex number-1\n");
printf("Enter its real and imaginary parts: ");
scanf("%f %f",&a.real,&a.img); Contd...
CABSMJ-1001 [2024-25]
printf("Complex number-2\n");
printf("Enter its real and imaginary parts: ");
scanf("%f %f",&b.real,&b.img);
complexnum c = sumcomplexnum(a, b);
printf("Complex number-1: %.2f + i%.2f\n",a.real,a.img);
printf("Complex number-2: %.2f + i%.2f\n",b.real,b.img);
printf("Sum of the complex numbers: %.2f + i%.2f\n",c.real,c.img);
}
Output
Complex number-1
Enter its real and imaginary parts: 3.5 6.5
Complex number-2
Enter its real and imaginary parts: 45.2 69.8
Complex number-1: 3.50 + i6.50
Complex number-2: 45.20 + i69.80
Sum of the complex numbers: 48.70 + i76.30
CABSMJ-1001 [2024-25]

Prob:
Write a C program that reads details (rno, name, marks in 3
papers) of n students in an array of structures and finds the
student securing highest aggregate marks using the function
highest().

s[0] 99CABSA101 Jameel Ahmad 65 72 59


s[1] 99CABSA102 Adil Khan 63 70 62
s[2] 99CABSA103 Rajesh kumar Singh 70 68 65
/* struct3.c */ s[0] 99CABSA101 Jameel Ahmad
CABSMJ-1001 [2024-25]
65 72 59 196
#include<stdio.h> s[1] 99CABSA102 Adil Khan 63 70 62 195
#include<stdlib.h>
s[2] 99CABSA103 Rajesh kumar Singh 70 68 65 203
#define N 3
struct studtype
{ char rno[11];
char name[41];
int m1,m2,m3;
int agg;
};
typedef struct studtype student;
student highest(student [],int);
main()
{ student s[N], high;
int i;
for (i=0; i<N; i++)
{ printf("Student-%d\n",i+1);
printf("Enter Roll-no: ");
gets(s[i].rno); Contd...
printf("Enter Name: "); CABSMJ-1001 [2024-25]

gets(s[i].name);
printf("Enter marks of 3 papers: ");
scanf("%d %d %d",&s[i].m1,&s[i].m2,&s[i].m3);
fflush(stdin);
s[i].agg = s[i].m1 + s[i].m2 + s[i].m3;
}
high = highest(s,N);
printf("Student securing highest aggregate marks is\n");
printf("%s\n%s\n%d\n",high.rno,high.name,high.agg);
}
student highest(student a[],int n)
{ int i; student high = a[0];
for (i=1; i<n; i++)
{ if ( a[i].agg > high.agg )
high = a[i];
}
return high;
}
CABSMJ-1001 [2024-25]
Output
Student-1
Enter Roll-no: 99CABSA101
Enter Name: Jameel Ahmad
Enter marks of 3 papers: 65 72 59
Student-2
Enter Roll-no: 99CABSA102
Enter Name: Adil Khan
Enter marks of 3 papers: 63 70 62
Student-3
Enter Roll-no: 99CABSA103
Enter Name: Rajesh Kumar Singh
Enter marks of 3 papers: 70 68 65
Student securing highest aggregate marks is
99CABSA103
Rajesh Kumar Singh
203
CABSMJ-1001 [2024-25]

Prob:
Write a C program that reads the details (Roll no, Name and
AggMarks) of n students in an array of structures and sorts
the array on Marks in descending order using function sort().

s[0] 99CABSA101 ADIL PARVEZ 460


s[1] 99CABSA102 MOHD AKMAL 450
s[2] 99CABSA103 NAVEEN KUMAR 465
s[3] 99CABSA104 JAMSHED ALI 475
s[4] 99CABSA105 JAMAL AHMAD 458
#include<stdio.h> /* structsort.c */ CABSMJ-1001 [2024-25]
#define N 5
struct studtype
{ char rno[11];
char name[31];
int aggmarks;
};
typedef struct studtype student;
void sort(student [ ],int);
main()
{ student s[N]; int i;
for (i=0; i<N; i++)
{ printf("Student-%d\n",i+1);
printf("Enter Roll-no: ");
gets(s[i].rno);
printf("Enter Name: ");
gets(s[i].name);
printf("Enter AggMarks: ");
scanf("%d",&s[i].aggmarks);
fflush(stdin); Contd...
}
sort(s,N); CABSMJ-1001 [2024-25]

printf("Student details in descending order:\n");


for (i=0; i<N; i++)
printf("%-10s %-30s %d\n",s[i].rno,s[i].name,s[i].aggmarks);
}
void sort(student s[],int n) /* uses bubble sort method */
{ int pass, i;
student temp;
for (pass=1; pass<=(N-1); pass++)
{ for(i=0; i<=(N-1-pass); i++)
{ if ( s[i].aggmarks < s[i+1].aggmarks ) /* sorts in descending order */
{ temp = s[i];
s[i] = s[i+1]; s[0] 99CABSA101 ADIL PARVEZ 460
s[i+1] = temp; s[1] 99CABSA102 MOHD AKMAL 450
} s[2] 99CABSA103 NAVEEN KUMAR 465
} s[3] 99CABSA104 JAMSHED ALI 475
} s[4] 99CABSA105 JAMAL AHMAD 458
}
Student-1 CABSMJ-1001 [2024-25]
Enter Roll-no: 99CABSA101
Enter Name: ADIL PARVEZ
Enter AggMarks: 460
Student-2
Enter Roll-no: 99CABSA102
Enter Name: MOHD AKMAL
Enter AggMarks: 450
Student-3
Enter Roll-no: 99CABSA103
Enter Name: NAVEEN KUMAR
Enter AggMarks: 465
Student-4
Enter Roll-no: 99CABSA104
Enter Name: JAMSHED ALI
Enter AggMarks: 475
Student-5
Enter Roll-no: 99CABSA105
Enter Name: JAMAL AHMAD
Enter AggMarks: 458
Student details in descending order:
99CABSA104 JAMSHED ALI 475
99CABSA103 NAVEEN KUMAR 465
99CABSA101 ADIL PARVEZ 460
99CABSA105 JAMAL AHMAD 458
99CABSA102 MOHD AKMAL 450
CABSMJ-1001 [2024-25]

Pointers
CABSMJ-1001 [2024-25]
i 25
Pointer 62fe14
memory
address
 Pointer is a variable that stores the memory p 62fe14
address of another variable as its value.

 Data type of the pointer and the variable (whose address is to


be stored) must be same.
 It is called pointer because its value points to the location of
another value.
 Since addresses are whole numbers, hence a pointer always
contains a whole number.
 In general, memory size of pointer for a 32-bit computer is 4
bytes and for a 64-bit is 8 bytes.
CABSMJ-1001 [2024-25]
i 25
Declaring a Pointer 62fe14

 Pointer is declared using * (asterisk symbol),


e.g. p 62fe14
int *a; /* a is a pointer to int */
char *c; /* c is a pointer to char */

 C provides two pointer operators, (i) Address of Operator (&)


and (ii) Indirection Operator (*).
(i). Address Of operator (&)
 It is a unary operator that returns the address of the variable
specified as its operand, e.g.
int i = 25; We can perform all the
int *p; /* pointer to int */ operations on 25 through p
p = &i; /* pointer p contains address of i */
CABSMJ-1001 [2024-25]
i 25 30
(ii). Indirection Operator 62fe14
(or Value at Address) operator (*)
 It is a unary operator that returns the value p 62fe14
stored at the address contained in its
argument, e.g.
 , e.g.
int i = 25;
int *p; /* pointer to int */
p = &i; /* pointer p contains address of i */
printf("%x\n",p); /* 62fe14 (value of p) */
printf("%d\n",*p); /* 25 (value stored at address contained in p) */
*p = 30; /* store 30 at the address contained in p */
printf("%d\n",i); /* 30 */
CABSMJ-1001 [2024-25]
i 25 30
Pointer to Pointer 62fe1c

 It is a pointer variable that contains the p 62fe1c


address of another pointer variable, e.g. 62fe10
int i = 25;
pp 62fe10
int *p; /* pointer to an int */ 62fe08
p = &i; /* p contains address of i */
int **pp; /* pp is a pointer to pointer to an int */
pp = &p; /* pp is a pointer to pointer p */
printf("%x\n",pp); /* 62fe10 (value of pp) */
printf("%x\n",*pp); /* 62fe1c (value at address contained in pp) */
printf("%d\n",**pp); /* 25 (value at address (value at address contained in pp))*/
**pp = 30;
printf("%d\n",i); /* 30 */
CABSMJ-1001 [2024-25]

Operations on Pointers
 Like ordinary variables, some operations can be performed on
pointers also.
 We can perform following FOUR operations on pointers:
Addition of a Adding 1 to a pointer will increment its value
whole (memory address) by the size of its underlying data
type.
number
int *a,*b; /* suppose both contain address 1001 */
(int value) a=a+1; /* a = 1005 ( 1*sizeof(int) = 4 will be added ) */
b=b+2; /* b = 1009 ( 2*sizeof(int) = 8 will be added ) */
Subtraction Subtracting 1 from a pointer will decrement its value
of a whole (memory address) by the size of its underlying data
type.
number
double *d; /* suppose it contains address 1020 */
(int value) d=d-2; /* d=1004 (2*sizeof(double)=16 will be subtracted) */
CABSMJ-1001 [2024-25]
int a[6]
10 15 20 25 30 35
Operations on Pointers
1002 1006 1010 1014 1018 1022

j k

Subtraction of • Both pointers must have the same data type.


one pointer • It gives the difference in terms of how many
from another elements they are apart.
sizeof(int)
int *j=&a[0], *k=&a[2];
int d= k - j; /* 2 elements apart (1010-1002)/4 = 8/4 = 2 */

Comparison of • We can compare pointers if they are pointing


pointers to the elements of the same array.
• All relational operators can be used to
compare two pointers, e.g. if (j==k), if (j<k) etc.

Note: Pointers can’t be multiplied or divided.


CABSMJ-1001 [2024-25]
int a[6]
10 15 20 25 30 35
Operations on Pointers
1002 1006 1010 1014 1018 1022
#include<stdio.h> j k
main()
{ int a[6] = {10,15,20,25,30,35}, i,*j,*k;
j = &a[0]; /* or j=a; array name gives address to the 0th element */
k = j + 1;
printf("%d %d\n",*j,*(j+2)); /* 10 20 */
i = 4;
printf("%d %d\n",*a,*(a+i)); /* 10 30 (a is name of the array) */
printf("%d\n",*(k-1)); /* 10 */
i = (k+4) - j; /* (1022 - 1002)/4 = (20/4 ) = 5 int apart */
printf("%d\n",i); /* 5 (difference in terms of no. of elements) */
if ( j != k )
printf("Pointers do not point to the same location\n");
}
CABSMJ-1001 [2024-25]
int a[6]
Accessing 1D Array Elements 10 15 20 25 30 35
1002 1006 1010 1014 1018 1022
Using Pointer
p

In a 1D array a[n], both array name a and the expression &a[0]


give the address of the element a[0].

int *p = &a[0];
Expression to get the address of ith element:
(p+i) or (a+i)
Expression to get the value of ith element:
*(p+i) or *(a+i)
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads n integers in an integer array a


and finds their sum.

Note: Array elements must be accessed through a pointer.


CABSMJ-1001
int a[10] [2024-25]

10 11 12 13 … 19
Accessing 1D Array Elements
1001 1005 1009 1013 … 1037
Using Pointer
p
/* arraysumusingptr.c */
#include<stdio.h> Output
#define N 10 Enter 10 int values
main() 10 11 12 13 14 15 16 17 18 19
{ int a[N], sum=0, i, *p; sum of all elements= 145
p = &a[0];
printf("Enter %d int values\n",N); for (i=0; i<N; i++)
for (i=0; i<N; i++) Loop can also be
{ scanf("%d",p);
{ scanf("%d",(p+i)); written as sum = sum + *p;
sum = sum + *(p+i); p = p+1;
} }
printf("Sum of all elements= %d",sum);
}
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads n integers in an integer array a


and checks whether the array elements are in ascending
order or not.

Note: Array elements must be accessed through a pointer.


/* arraycheckusingptr.c */ CABSMJ-1001
int a[10] [2024-25]
#include<stdio.h> 0 1 2 3 8 9
#define N 10 10 11 12 13 … 17 50
main() 1001 1005 1009 1013 … 1033 1037
{ int a[N], i, *p, isascending = 1; p
p = &a[0];
printf("Enter %d int values\n",N);
for (i=0; i<N; i++)
scanf("%d",(p+i));
for (i=0; i<=N-2; i++)
{ if ( *(p+i) > *(p+i+1) ) Output
{ isascending = 0; Enter 10 int values
break; 10 11 12 13 13 14 15 16 17 50
} Array elements are in ascending order
}
if (isascending == 0)
printf("Array elements are not in ascending order");
else
printf("Array elements are in ascending order");
}
1CABSMJ-1001
2 3 [2024-25]
4
Accessing 2D Array Elements 5 6 7 8
Using Pointer
9 10 11 12
 A 2D array is actually a 1D array in which
int a[3][4]
each element is itself a 1D array.

 So, 2D array a[3][4] is actually a 1D array of 3 elements,


where each element is a 1D array of 4 integers.
 2D array elements can be accessed using pointer in 3 ways:
(i). Using Array Name as Pointer
#columns in 2D array
(ii). Using Pointer to an Array of C Elements

(iii). Using Pointer to Element a[0][0]


a 1CABSMJ-1001
2 3 [2024-25]
4
1000
Accessing 2D Array Elements a+1 5 6 7 8
Using Pointer 1016
a+2 9 10 11 12
1032
int a[3][4]
(i). Using Array Name as Pointer: In a 2D array a[m][n]:

a Pointer to 0th row Entire row is treated


a+i Pointer to the ith row as an element

*(a+i) Pointer to 0th element in the ith row


*(a+i)+j Pointer to the element in ith row and jth column i.e. &a[i][j]
*(*(a+ i)+j) Value stored in ith row and jth column i.e. a[i][j]
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads an integer 2D array of size mxn


and finds the biggest value.

Note: Array elements must be accessed using pointer.


CABSMJ-1001 [2024-25]

Accessing 2D array elements using array name as pointer

/* biggestin2dusingptr1.c */
1 2 3 4
#include<stdio.h>
#define R 3 5 6 7 8
#define C 4 9 10 11 12
main() int a[3][4]
{ int a[R][C], i, j, biggest;
printf("Enter elements of %dx%d 2D int array row-wise\n",R,C);
for (i=0; i<R; i++)
{ for (j=0; j<C; j++)
scanf("%d",*(a+i)+j ); /* eqv to &a[i][j] */
}

Contd...
CABSMJ-1001 [2024-25]

biggest = *(*(a+0)+0); /* eqv to a[0][0] */


printf("2D array is\n");
for (i=0; i<R; i++)
{ for (j=0; j<C; j++)
{ printf("%d\t",*(*(a+i)+j) ); /* eqv to a[i][j] */
if ( *(*(a+i)+j) > biggest )
Output
biggest = *(*(a+i)+j);
Enter elements of 3x4 2D int
}
array row-wise
printf("\n");
1 2 3 4
} 5 6 7 8
printf("Biggest = %d",biggest); 1 2 3 4
} 2D array is
1 2 3 4
5 6 7 8
1 2 3 4
Biggest = 8
CABSMJ-1001 [2024-25]
p 1 2 3 4
1000
Accessing 2D Array Elements p+1 5 6 7 8
1016
Using Pointer
#columns in 2D array p+21032 9 10 11 12
(ii). Using Pointer to an Array of C Elements: int a[3][4]

 First declare a pointer to an array of C integers, then assign


the 2D array name to this pointer:
int (*p)[4]; /* p is a pointer to an array of 4 integers */
p = a;

p Pointer to 0th row


p+i Pointer to the ith row
*(p+i) Pointer to 0th element in the ith row
*(p+i)+j Pointer to the element in ith row and jth column i.e. &a[i][j]
*(*(p+ i)+j) Value stored in ith row and jth column i.e. a[i][j] i.e. a[i][j]
CABSMJ-1001 [2024-25]

Accessing 2D array elements using pointer

/* biggestin2dusingptr2.c */
1 2 3 4
#include<stdio.h>
#define R 3 5 6 7 8
#define C 4 9 10 11 12
main() int a[3][4]
{ int a[R][C], i, j, biggest;
int (*p)[C] = a; /* p is a ptr to an array of C ints */
printf("Enter elements of %dx%d 2D int array row-wise\n",R,C);
for (i=0; i<R; i++)
{ for (j=0; j<C; j++)
scanf("%d",*(p+i)+j); /* eqv to &a[i][j] */
}
Contd...
CABSMJ-1001 [2024-25]

biggest = *(*(p+0)+0); /* eqv to a[0][0] */


printf("2D array is\n");
for (i=0; i<R; i++)
{ for (j=0; j<C; j++)
{ printf("%d\t",*(*(p+i)+j) ); /* eqv to a[i][j] */
if ( *(*(p+i)+j) > biggest )
Output
biggest = *(*(p+i)+j);
Enter elements of 3x4 2D int
}
array row-wise
printf("\n");
1 2 3 4
} 5 6 7 8
printf("Biggest = %d",biggest); 1 2 3 4
} 2D array is
1 2 3 4
5 6 7 8
1 2 3 4
Biggest = 8
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads an integer 2D array of size mxn


and prints its row-wise sum.

Note: Array elements must be accessed through a pointer.


/* rowsumusingptr.c */ CABSMJ-1001 [2024-25]
#include<stdio.h> 1 2 3 4
#define R 3 5 6 7 8
#define C 4
main() 3 4 5 6
{ int a[R][C], i, j, sum; int a[3][4]
int (*p)[C] = a;
printf("Enter elements of %dx%d 2D int array row-wise\n",R,C);
for (i=0; i<R; i++)
{ for (j=0; j<C; j++)
scanf("%d",*(p+i)+j ); /* eqv to &a[i][j] */ Output
} Enter elements of 3x4 2D
for (i=0; i<R; i++) int array row-wise
{ sum = 0; 1 2 3 4
for (j=0; j<C; j++) 5 6 7 8
{ sum += *(*(p+i)+j); 3 4 5 6
} Sum of row - 0 = 10
printf("Sum of row -%2d = %d\n",i,sum); Sum of row - 1 = 26
} Sum of row - 2 = 18
}
CABSMJ-1001 [2024-25]
1 2 3 4
Accessing 2D Array Elements 5 6 7 8
Using Pointer
3 4 5 6
(iii). Using Pointer to Element a[0][0] int a[3][4]
 First we declare a pointer to the array type, then assign the
address of element a[0][0] to this pointer:
0th row 1st row 2nd row
int *p; 1 2 3 4 5 6 7 8 3 4 5 6
p
p = &a[0][0]; 1001 1005 1009 1013 1017 1021 1025 1029 1033 1037 1041 1045
p+1 p+2

(p + i*C + j) Pointer to element in ith row and jth column i.e. &a[i][j]
*(p + i*C + j) Value stored in ith row and jth column i.e. a[i][j]

Address of a[1][2] = ( p + i*C + j ) = ( 1001 + 1*4 + 2 )


= ( 1001 + 6 ) i.e. 1025
CABSMJ-1001 [2024-25]

Accessing 2D array elements using pointer to element a[0][0]

/* biggestin2dusingptr3.c */
#include<stdio.h> 0th row 1st row 2nd row
#define R 3
p 1 2 3 4 5 6 7 8 3 4 5 6
#define C 4 1001 1005 1009 1013 1017 1021 1025 1029 1033 1037 1041 1045
main() p+1 p+2
{ int a[R][C], i, j, biggest;
int *p = &a[0][0];
printf("Enter elements of %dx%d 2D int array row-wise\n",R,C);
for (i=0; i<R; i++)
{ for (j=0; j<C; j++)
scanf("%d",(p+i*C+j) ); /* eqv to &a[i][j] */
}
Contd...
CABSMJ-1001 [2024-25]

biggest = *(p+0*C+0); /* eqv to a[0][0] */


printf("2D array is\n");
for (i=0; i<R; i++)
{ for (j=0; j<C; j++)
{ printf("%d\t",*(p+i*C+j) );
Output
if ( *(p+i*C+j) > biggest )
Enter elements of 3x4 2D int
biggest = *(p+i*C+j);
array row-wise
} 1 2 3 4
printf("\n"); 5 6 7 8
} 3 4 5 6
printf("Biggest = %d",biggest); 2D array is
} 1 2 3 4
5 6 7 8
3 4 5 6
Biggest = 8
main()CABSMJ-1001 [2024-25]
somefun()
(ii). Pass By Reference x 10.5
ptrx addr1
addr1
y 20.5
 Memory addresses of the actual ptry addr2
addr2
arguments are passed in the formal
z 30.5
arguments of the called function. ptrz addr3
addr3

 Called function directly works on the actual arguments.


 Called function can access & modify actual arguments
through their addresses.
 "Pass by reference" method is used:
1. When we want called function to modify actual arguments.
2. When we need multiple values to be returned by the called
function.
Note: Arrays and strings are always auto passed by reference.
CABSMJ-1001 [2024-25]

Difference between Pass By Value and Pass By Reference

Actual
arguments

Function works on Function works on


the copy of Actual the Actual arguments
arguments through their
addresses
CABSMJ-1001 [2024-25]

C program to illustrate how a function can modify Actual


Arguments through pointers.
Prob:

Write a C program that reads two integers a and b and swaps


their values using swap() function.
CABSMJ-1001 [2024-25]
/* swapusingfn.c */
main() swap()
#include<stdio.h> a 25
x 1001
1001
void swap(int*, int*);
main() b 50
y 1005
1005
{ int a, b;
printf("Enter integer values for a and b\n");
scanf("%d %d",&a,&b);
printf("Before swapping: a = %d and b = %d\n",a,b);
swap(&a, &b);
printf("After swapping : a = %d and b = %d\n",a,b);
}
void swap(int *x, int *y)
Output
{ int temp;
Enter integer values for a and b
temp = *x;
25 50
*x = *y;
Before swapping: a = 25 and b = 50
*y = temp;
After swapping : a = 50 and b = 25
}
CABSMJ-1001 [2024-25]

C program to illustrate how a function can return two or


more values through pointers.
Prob:
Write a C program that reads two integers namely dividend and
divisor and finds the quotient and remainder when dividend is
divided by divisor using a function qr().
CABSMJ-1001 [2024-25]
quotient remainder
Garbage Garbage
/* quotientrem.c */
1001 1005
#include<stdio.h>
void qr(int dividend,int divisor,int *q,int *r)
{ *q = dividend / divisor; quotient remainder
*r = dividend % divisor; 3 4
} 1001 1005
main()
{ int dividend, divisor, quotient, rem;
Output
printf("Enter dividend: ");
Enter dividend: 25
scanf("%d",&dividend);
Enter divisor: 7
printf("Enter divisor: ");
Quotient = 3
scanf("%d",&divisor); Pass by value
Remainder = 4
qr(dividend,divisor,&quotient,&rem);
printf("Quotient = %d\n",quotient); Pass by reference
printf("Remainder = %d",rem);
}
CABSMJ-1001 [2024-25]

C program to illustrate how a function can return a


pointer.
Prob:
Write a program that reads two integer values a and b and
finds the address of the bigger value using function bigger().
CABSMJ-1001 [2024-25]

/* biggerusingfn.c */
#include<stdio.h>
int* bigger(int*, int*); /* returns a pointer to an int */
main()
{ int a, b, *ptobig; a b
printf("Enter integer values for a and b\n"); 25 50
scanf("%d %d",&a,&b); 1001 1005
ptobig = bigger(&a,&b); ptobig
printf("Bigger value = %d\n",*ptobig);
}
int* bigger(int *x, int *y)
{ if ( *x > *y ) Output
return x; Enter integer values for a and b
else 25 50
return y; Bigger value = 50
}
CABSMJ-1001 [2024-25]

Prob: Pointer to 1D int array

Write a C program that reads 1D integer array of size n and


finds the number of even integers in the array using function
count_even(int*, int) which receives the integer 1D array as a
pointer and size of the array.
The function returns the number of even integers in the array.
/* eveninarrayusingptr.c */ 0 1 2 CABSMJ-1001
3 8 [2024-25]
9
#include<stdio.h> 10 11 12 13 … 18 19
contains base 1001 1005 1009 1013 … 1033 1037
#define N 10 address of a
a a+1
int count_even(int *a, int n)
{ int i, counteven=0;
for (i=0; i<n; i++) /* int a[] is internally eqv to int *a */
{ if ( *(a+i) % 2 == 0) /* we can write a[i] in place of *(a+i) */
counteven++;
} Output
return counteven; Enter 10 int values
} 12 45 67 98 52 59 88 33 55 21
main() No. of even numbers in the array=4
{ int a[N], i;
printf("Enter %d int values\n",N);
for (i=0; i<N; i++)
{ scanf("%d",&a[i]);
}
printf("No. of even numbers in the array=%d",count_even(a,N));
}
CABSMJ-1001 [2024-25]

Prob:
Write a C program that reads a NxN integer matrix and finds
sum of non-diagonal elements using the function
sum_nondiag_ele(int (*p)[N]), where p is a pointer to an array
of N elements and each element is an array of N integers.

p 1 2 3 4
p+1 2 3 4 5
p+2 3 4 5 6
4 5 6 7
int a[4][4]
#include<stdio.h> /* matusingfnandptr.c */ CABSMJ-1001 [2024-25]
p 1 2 3 4
#define N 4
int sum_nondiag_ele(int (*p)[N]) p+1 2 3 4 5
{ int i, j, sum=0;
eqv to int p[][N] p+2 3 4 5 6
for (i=0; i<N; i++)
{ for (j=0; j<N; j++) 4 5 6 7
{ if ( i != j )
sum = sum + *(*(p+i)+j); /* or p[i][j] */ int a[4][4]
} p is a pointer to
} an array of N elements,
return sum; where each element is
} an array of N ints.
main()
{ int a[N][N], i, j;
printf("Matrix size = %dx%d - enter elements row-wise\n",N,N);
for (i=0; i<N; i++)
{ for (j=0; j<N; j++)
scanf("%d",&a[i][j]);
}
printf ("Sum of non-diagonal elements = %d\n",sum_nondiag_ele(a));
}
CABSMJ-1001 [2024-25]

Output
Matrix size = 4x4 - enter elements row-wise
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Sum of non-diagonal elements = 48
CABSMJ-1001 [2024-25]
str[9] C o m p u t e r \0
Accesing Strings 0 1 2 3 .4. . 5 6 7 8
Through Pointers p

 As you know, strings are represented using char arrays:


char str[9]="Computer";
 Name of the string (str) holds the address of the 0th element
of the array.
 To access a string through pointer, we can declare a char
pointer p and store the address of 0th element of the string in it:
char *p = str;
/* now we can manipulate the string elements using pointer p */
while ( *p != '\0' )
{ printf("%c", *p);
p++; /* now p points to the next string element */
} /* or printf("%s",p); or puts(p); to print entire string */
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads a string (consisting of alphabets


and spaces) and counts no. of vowels, consonants and spaces
in the string using pointer to the string.
/* stringvowels.c */ CABSMJ-1001 [2024-25]
str W r i t e a C p r o g r a m \0
#include<stdio.h>
main() ....
p
{ char str[81], *p;
int vowelscount=0, consonantscount=0, spacecount=0;
printf("Enter a string consisting of alphabets and spaces only\n");
printf("Max length: upto 80 chars\n");
gets(str);
p = str; /* str gives address of 0th char */
while ( *p != '\0' )
{ if (*p=='a'||*p=='e'||*p=='i'||*p=='o'||*p=='u')
vowelscount++;
else if (*p==' ')
spacecount++;
else consonantscount++;
p++;
}
printf("Number of vowels = %d\n",vowelscount);
printf("Number of consonants = %d\n",consonantscount);
printf("Number of spaces = %d\n",spacecount);
}
CABSMJ-1001 [2024-25]

Output
Enter a string consisting of alphabets and spaces only
Max length: upto 80 chars
Write a C program
Number of vowels = 5
Number of consonants = 9
Number of spaces = 3
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads a string and prints it in reverse


order using pointer.
/*strreverse2.c */ CABSMJ-1001 [2024-25]
1001 1011
#include<stdio.h> str P r o g r a m m i n g \0
#include<string.h> ....
#define N 81 p
main()
{ char str[N], *p;
int i=0, len;
printf("Enter a string (Max length %d chars)\n",N-1); str=1001
len=11
gets(str); p= 1001+ 11-1
len = strlen(str); = 1011
p = str + len-1; /* p points to the last char of the string */
printf("String in reverse order\n");
for( i=0; i<=len-1; i++) Output
{ printf("%c",*p);
Enter a string (Max length 80 chars)
p--; Programming
} String in reverse order
} gnimmargorP
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads a string and converts it in reverse


order using pointers.
/*strreverse3.c */ CABSMJ-1001 [2024-25]
1001 1011
#include<stdio.h> str P r o g r a m m i n g \0
#include<string.h>
#define N 81 pf pl
main()
{ char str[N], temp, *pf, *pl;
int i=0, len;
printf("Enter a string (Max length %d chars)\n",N-1);
gets(str); str=1001
pf = str; /* pf points to first char of the string */ len=11
len = strlen(str); pl= 1001+ 11-1
pl = str + len-1; /* pl points to last char of the string */ = 1011
for( i=0; i<len/2; i++)
{ temp = *pf;
*pf = *pl;
Output
*pl = temp;
pf++; pl--; Enter a string (Max length 80 chars)
} Programming
printf("String in reverse order\n"); String in reverse order
puts(str); gnimmargorP
}
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads a string and converts all


lowercase letters in it into uppercase using pointer without
using toupper() library function.
CABSMJ-1001 [2024-25]
/*strupper.c */ str C
#include<stdio.h> P r o g r a m m i n g \0
....
#define N 81 p
main()
{ char str[N], *p;
printf("Enter a string (Max length %d chars)\n",N-1); ASCII values
gets(str); A (65) a (97)
p = str; B (66) b (98)
while ( *p != '\0' ) C (67) c (99)
{ if ( *p >='a' && *p <= 'z' )
: :
*p = *p - 32;
p++; Output
}
Enter a string (Max length 80
printf("String in uppercase:\n"); chars)
puts(str); C Programming
} String in uppercase:
C PROGRAMMING
str1 CABSMJ-1001 [2024-25]
C o m p u t e r \0
Using char Pointer
to represent & store Strings
 When a string is directly assigned to a char pointer:
 the string is stored in a read-only block in the memory and
 its starting address is stored in the pointer, e.g.

char *str1;
str1 = "Computer";
or char *str1 = "Computer";

 The char pointer (str1) is stored in read-write memory.

Note: The string represented through char pointer can’t be


modified because we have not created a buffer for the
string.
str1 CABSMJ-1001 [2024-25]
C o m p u t e r \0
...
p

 We can process/output the string char-by-char using a


pointer p to the string as below:

char *str1 = "Computer";


char *p = str1;
while( *p != '\0' )
{ printf("%c", *p);
p++;
}

 Or we can output the entire string as below:

printf("%s",str1); or puts(str1);
str2 CABSMJ-1001 [2024-25]
N e w D e l h i \0
Note (regarding strings str3
represented using char
pointers):
1. While declaring a char pointer an initial string (or another
existing string ) can be assigned, e.g.
char *str2 = "New Delhi";
char *str3 = str2; because the pointer does not
point to a storage block where
string read can be stored.
2. We can’t read a string properly using scanf()/gets():

char *str;
gets(str); /* invalid */
scanf("%s",str); /* invalid */
CABSMJ-1001 [2024-25]

Prob:
Write a C program that represents a string using a character
pointer and prints the length of the string without using library
function.
Assume that the string is represented as: char *str = "MUMBAI";
688 694
CABSMJ-1001 [2024-25]

/* stringlength.c */ M U M B A I \0
str ...
#include<stdio.h> p
main()
{ char *str = "MUMBAI"; Output
char *p = str; String is: MUMBAI
int length=0; M is stored at 4210688
printf("String is: %s\n",str); U is stored at 4210689
/* compute length of string using pointer p */ M is stored at 4210690
while ( *p != '\0' ) B is stored at 4210691
{ printf("%c is stored at %u\n",*p,p); A is stored at 4210692
length++; I is stored at 4210693
p++; Length of string = 6
} Length of string = 6
printf("Length of string = %d\n",length);
printf("Length of string = %d\n",(p-str)); /* 4210694 – 4210688 */
} /* = 6 */
name[3][15]
CABSMJ-1001 [2024-25]

Array of Pointers N e w Z e a l a n d \0
To Strings A u s t r a l i a \0
I n d i a \0
 When we use 2D char array to store strings of varying length,
then a lot of storage is wasted, e.g.:
char name[3][15] = { "New Zealand", "Australia", "India" };
 To avoid wastage of storage, we need to use a jagged array: A
2D array whose rows can be of different length.
 C doesn't provide jagged arrays but we can simulate them
using an array of pointers to strings, e.g. Read-only strings

char *name[3] name[0] N e w Z e a l a n d \0


name[1] A u s t r a l i a \0
Array of pointers name[2] I n d i a \0
to strings
Array of pointers CABSMJ-1001 [2024-25]
name[0] N e w Z e a l a n d \0
Array of Pointers name[1] A u s t r a l i a \0
To Strings name[2] I n d i a \0

 So, to store strings of varying length, we can use an array of


pointers to strings (each pointer points to the 0th character of the
string), e.g.:
char *name[3] = { "New Zealand", "Australia", "India" };
 It declares name to be an array of 3 pointers to strings and
allocates only 28 bytes (12+10+6 sufficient to hold all the 3 strings).
 Individual strings can be accessed using name[i]:
for (i=0; i<=2; i++)
printf("%s\n",name[i]); /* prints all the 3 country names */
 To access jth character in ith name:
printf("%c",*(name[i]+j)); /* prints jth character of ith name */
CABSMJ-1001 [2024-25]

Prob:
Store following string literals using an array of pointers to
strings:
"Golf", "Hockey", "Football", "Cricket", "Shooting"
Then
1. Replace the string "Shooting" by "Tennis".
2. Print these string literals and their base addresses using
a loop.
Array of pointers CABSMJ-1001 [2024-25]
sports[0] G o l f \0
/* arrayofptrs1.c */ sports[1] H o c k e y \0
#include<stdio.h> sports[2] F o o t b a l l \0
sports[3] C r i c k e t \0
main()
sports[4] S h o o t i n g \0
{ int i;
char *sports[] = {"Golf","Hockey","Football","Cricket","Shooting" };
sports[4] = "Tennis";
for (i = 0; i<5; i++)
{ printf("String = %-10s",sports[i]);
printf("\tBase address = %u\n",sports[i]);
} Output
} String = Golf Base address = 4210688
String = Hockey Base address = 4210693
String = Football Base address = 4210700
String = Cricket Base address = 4210709
String = Tennis Base address = 4210726
CABSMJ-1001 [2024-25]
name[0]
Invalid Operations on name[1]
name[2]
Array of Pointers To Strings name[3]
name[4]

char *name[5]; /* array of pointers to strings */

 For the above array of pointers, following operations will be


invalid. If we perform them, we will get an undefined result.

scanf("%s",name[i]); // invalid If we want to


perform these
gets( name[i] ); // invalid operations, we will
strcpy(name[i],"Rashid Ali"); // invalid have to allocate
storage for storing
strcat(name[i],"Parvez Alam"); // invalid each string.
CABSMJ-1001 [2024-25]

Prob:
Read n names using an array of pointers to strings and
1. print the names
2. find and print the longest name.
CABSMJ-1001 [2024-25]
/* arrayofptrs2.c */ name[0] J a m a l A h m a d \0
#include<stdio.h> name[1] F a r o o q A h m a d K h a n \0

#include<stdlib.h> name[2] :
name[3] :
#include<string.h> name[4] :
#define N 5
main()
{ char *name[5], str[41];
int i, longestnameindex;
for (i=0; i<N; i++)
{ printf("Enter name-%d\n",i+1);
gets(str); /* gets(name[i]); invalid */
name[i]=(char *)malloc(sizeof(strlen(str)+1)); /* allocate storage */
strcpy(name[i],str);
}
printf("Names are:\n");
for (i=0; i<N; i++)
printf("%s\n",name[i]); /* Contd… */
longestnameindex = 0; CABSMJ-1001 [2024-25]

for (i = 1; i<N; i++)


{ if ( strlen(name[i]) > strlen(name[longestnameindex]) )
longestnameindex = i;
}
printf("Longest name is:\n");
printf("%s",name[longestnameindex]);
}
Output
Enter name-1
Jamal Ahmad Names are:
Enter name-2 Jamal Ahmad
Farooq Ahmad Khan Farooq Ahmad Khan
Enter name-3
Shamshad Alam Khan
Shamshad Alam Khan
Enter name-4 Parvez Akhter
Parvez Akhter Nayeem Ali Khan
Enter name-5 Longest name is:
Nayeem Ali Khan Shamshad Alam Khan
CABSMJ-1001 [2024-25]

Structures
and
Pointers
CABSMJ-1001 [2024-25]
s1
Declaring Pointer to rno name age height
p
Structure
struct student /* structure template */
{ char rno[11];
char name[41];
int age;
float height;
};
struct student s1;

Pointer to structure s1 can be declared as below:

struct student *p;


p = &s1; /* structure s1 can be thought of an ordinary variable */
/* address of struct variable s1 is assigned to pointer p */
CABSMJ-1001 [2024-25]
s1
Accessing Structure rno name age height
Members Through p
Pointer

Structure members can be accessed using pointer in 2 ways:

Using member selection operator Using indirection operator

gets(p->rno); /* char array */ gets((*p).rno);

gets(p->name); /* char array */ gets((*p).name);

scanf("%d", &p->age); scanf("%d", &(*p).age);

scanf("%f", &p->height); scanf("%f", &(*p).height);


printf("%s %s %d %f",p->rno, printf("%s %s %d %f",(*p).rno,
p->name, p->age, p->height); (*p).name, (*p).age, (*p).height;
CABSMJ-1001 [2024-25]

Example: illustrates Reading and Outputting Structure


Members Using Pointer
/* structpointer1.c */
#include<stdio.h> s1
main() rno name age height
{ struct student p
{ char rno[11];
char name[41];
int age;
float height;
};
struct student s1, *p;
p = &s1;
printf("Enter rollno, name, age and height (each on separate line)\n");

Contd...
CABSMJ-1001 [2024-25]
s1
rno name age height
p

gets(p->rno); /* or (*p).rno */
gets(p->name); /* or (*p).name */
scanf("%d", &p->age); /* or &(*p).age */
scanf("%f", &p->height); /* or &(*p).height */
printf("%s %s %d %.2f",p->rno, p->name, p->age, p->height);
}
Output
Enter rollno, name, age and height (each on separate line)
1001
Jamal Ahmad Khan
18
165
1001 Jamal Ahmad Khan 18 165.00
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads details (Title, Author, #Pages,


Price) of two books in structure variables and prints the details
of the book having lower price.

Note: Use pointer to read and access structure members.


/* struct10.c */ CABSMJ-1001 [2024-25]
#include<stdio.h> b1
title author pages price
main() p1
{ struct book
{ char title[31];
b2
char author[31]; title author pages price
int pages; p2
float price;
};
struct book b1, b2, *p1=&b1, *p2=&b2;
printf("Enter Book-1 details\n");
printf("Enter Title: ");
gets(p1->title);
printf("Enter Author: ");
gets(p1->author);
printf("Enter #Pages and Price: ");
scanf("%d %f",&p1->pages,&p1->price);
fflush(stdin); Contd...
CABSMJ-1001 [2024-25]

printf("Enter Book-2 details\n");


printf("Enter Title: ");
gets(p2->title);
printf("Enter Author: ");
gets(p2->author);
printf("Enter #Pages and Price: ");
scanf("%d %f",&p2->pages,&p2->price);
printf("Book having lower price is\n");
if ( p1->price < p2->price )
printf("%s\n%s\n%d pages\nRs.%.2f\n",p1->title,p1->author,
p1->pages,p1->price);
else
printf("%s\n%s\n%d pages\nRs.%.2f\n",p2->title,p2->author,
p2->pages,p2->price);
}
CABSMJ-1001 [2024-25]

Output
Enter Book-1 details
Enter Title: C Programming Language
Enter Author: Kernighan & Ritchie
Enter #Pages and Price: 288 355
Enter Book-2 details
Enter Title: Programming in ANSI C
Enter Author: E Balagurusamy
Enter #Pages and Price: 581 500
Book having lower price is
C Programming Language
Kernighan & Ritchie
288 pages
Rs.355.00
CABSMJ-1001 [2024-25]

Array of Structures and Pointers

s[3]
s[0] s[1] s[2]
p p+1 p+2

Declaring pointer to an array of structures


struct student s[3], *p;
p = &s[0]; /* p = s; */
Members of ith structure can be accessed: (p+i)->membername
gets( (p+i)->rno ); /* (*(p+i)).rno */
gets( (p+i)->name ); /* (*(p+i)).name */
scanf("%d",&(p+i)->age); / * &(*(p+i)).age */
scanf("%f",&(p+i)->height); /* &(*(p+i)).height */
printf("%s %s %d %f",(p+i)->rno, (p+i)->name, (p+i)->age, (p+i)->height);
CABSMJ-1001 [2024-25]

Prob:
Write a C program that reads sales data (cityname, monthly
sales) of a product in n cities in an array of structures and
finds the city having maximum sales and city having
minimum sales.
Make use of pointer to structure and pointer to array of
structures.
/* struct4.c */ CABSMJ-1001 [2024-25]

#include<stdio.h>
#define N 3 sd[3] Delhi 500000 Agra 450000 Aligarh 460000
struct data sd[0] sd[1] sd[2]
{ char city[31]; p p+1 p+2
float sales; maxp
}; minp Array of structures
typedef struct data salesdata;
main()
{ salesdata sd[N], *p = &sd[0], *maxp, *minp;
int i;
for (i=0; i<N; i++)
{ printf("Enter salesdata for city-%d:\n",i+1);
printf("Enter city Name: ");
gets((p+i)->city); / * or (*(p+i)).city */
printf("Enter sales: ");
scanf("%f",&(p+i)->sales); / * or &(*(p+i)).sales */
fflush(stdin);
Contd...
}
CABSMJ-1001 [2024-25]
sd[3] Delhi 500000 Agra 450000 Aligarh 460000
sd[0] sd[1] sd[2]
p p+1 p+2
maxp
minp Array of structures

maxp = minp = p;
for (i=1; i<N; i++)
{ if ( (p+i)->sales > maxp->sales )
maxp = (p+i);
else if ( (p+i)->sales < minp->sales )
minp = (p+i);
}
printf("City Having Maximum sales\n");
printf("%s\n%.2f\n",maxp->city, maxp->sales); / * or (*maxp).city */
printf("City having Minimum sales\n");
printf("%s\n%.2f\n",minp->city, minp->sales); / * or (*minp).city */
}
CABSMJ-1001 [2024-25]
Output
Enter salesdata for city-1:
Enter city Name: Delhi
Enter sales: 500000
Enter salesdata for city-2:
Enter city Name: Agra
Enter sales: 450000
Enter salesdata for city-3:
Enter city Name: Aligarh
Enter sales: 460000
City having Maximum sales
Delhi
500000.00
City having Minimum sales
Agra
450000.00
CABSMJ-1001 [2024-25]

Nested Structures ha.district


and Pointers ha.addr ha.pin
e1
struct employee empid name basicpay ha
p
{ int empid;
char name[31];
float basicpay;
struct home_address /* nested structure */
{ char addr[41];
char district[21];
int pin;
} ha;
};
struct employee e1,*p;
p = &e1;
ha.addr ha.pin
CABSMJ-1001 [2024-25]
e1
Nested Structures empid name basicpay ha
p

Reading data in nested structure members through struct name


gets(e1.ha.addr); gets(e1.ha.district);
scanf("%d", &e1.ha.pin);
Reading data in nested structure members through pointer
gets(p->ha.addr); /* or (*p).ha.addr */
gets(p->ha.district); /* or (*p).ha.district */
scanf("%d",&p->ha.pin); /* or &(*p).ha.pin */
Outputting nested structure members through struct name
printf("%s",e1.ha.addr); printf("%s",e1.ha.district);
printf("%d",e1.ha.pin);
Outputting nested structure members through pointer
printf("%s",p->ha.addr); /* or (*p).ha.addr */
printf("%s",p->ha.district); /* or (*p).ha.district */
printf("%d",p->ha.pin); /* or (*p).ha.pin */
CABSMJ-1001 [2024-25]

Prob:
Write a C program that:
 reads data (empid, name, basicpay, home_addr (addr,
district, pin)) of n employees in an array of structures and
 prints all the employees’ details that belong to a given
district.
You have to use the nested structure and a pointer to access
the members of the array of structures.

ha.district
ha.addr ha.pin

e[3] empid name basicpay ha


[0] [1] [2]
p p+1 p+2
Array of structures
CABSMJ-1001 [2024-25]

/* struct7.c illustrates how to access members of nested


structure using pointer */
#define N 3 ha.district
ha.addr ha.pin
#include<stdio.h>
#include<string.h>
empid name basicpay ha
struct employee
{ int empid;
char name[31];
float basicpay;
struct home_address /* nested structure */
{ char addr[41];
char district[21];
int pin;
} ha;
};
Contd...
main() CABSMJ-1001 [2024-25]

{ struct employee e[N],*p;


char distr[21];
int i, found=0;
p = &e[0];
for( i=0; i<N; i++)
{ printf("Employee[%d]\n",i);
printf("Enter Empid: ");
scanf("%d",&(p+i)->empid); /* or &(*(p+i)).empid */
fflush(stdin);
printf("Enter Name: ");
gets((p+i)->name); /* or (*(p+i)).name */
printf("Enter Basic pay: ");
scanf("%f",&(p+i)->basicpay); /* or &(*(p+i)).basicpay */
fflush(stdin);
printf("Enter Home address (excluding District) (Max 40 char)\n");
gets((p+i)->ha.addr); /* or (*(p+i)).ha.addr */
Contd...
printf("Enter Home district (Max 20 char): "); CABSMJ-1001 [2024-25]
gets((p+i)->ha.district); /* or (*(p+i)).ha.district */
printf("Enter Home district pincode: ");
scanf("%d",&(p+i)->ha.pin); /* or &(*(p+i)).ha.pin */
fflush(stdin);
}
printf("\nEnter District name (Max 20 char) whose employees to be printed: ");
gets(distr);
printf("\nEmployees that belong to %s:\n",distr);
for( i=0; i<N; i++)
{ if ( strncmp( (p+i)->ha.district,distr,strlen(distr) ) == 0 )
{ printf("%d %-30s %9.2f %-40s %-20s %d\n",(p+i)->empid,(p+i)-
>name,(p+i)->basicpay,(p+i)->ha.addr,(p+i)->ha.district,(p+i)->ha.pin);
found = 1;
}
}
if ( found == 0 )
printf("No such employee found ");
}
CABSMJ-1001 [2024-25]

Output
Employee[0]
Enter Empid: 1001
Enter Name: Rashid Ali Khan
Enter Basic pay: 50000
Enter Home address (excluding District) (Max 40 char)
141 Sector D1, Near Zonal Park
Enter Home district (Max 20 char): Lucknow
Enter Home district pincode: 226012
Employee[1]
Enter Empid: 1002
Enter Name: Arif Hameed
Enter Basic pay: 50000
Enter Home address (excluding District) (Max 40 char)
48, Rajendra Nagar Overbridge
Enter Home district (Max 20 char): Patna
Enter Home district pincode: 800020 Contd...
CABSMJ-1001 [2024-25]

Output
Employee[2]
Enter Empid: 1003
Enter Name: Pankaj Kumar
Enter Basic pay: 50000
Enter Home address (excluding District) (Max 40 char)
19 Vijayant Khand-04, Gomti Nagar
Enter Home district (Max 20 char): Lucknow
Enter Home district pincode: 226010
Enter District name (Max 20 char) whose employees to be printed:
Lucknow

Employees that belong to Lucknow:


1001 Rashid Ali Khan 50000.00 141 Sector D1, Near Zonal
Park Lucknow 226012
1003 Pankaj Kumar 50000.00 19 Vijayant Khand-04,
Gomti Nagar Lucknow 226010
CABSMJ-1001 [2024-25]

Exercise #1.
Write a C program that reads n integers in a 1D array and then
stores odd and even integers into separate arrays.
Exercise #2.
Write a C program that reads n integers in a 1D array and sorts its
elements in descending order using bubble sort method.
Exercise #3.
Write a C program that reads 10 numbers in ascending order in a
1D int array a[20]. Then the program reads a new number and
inserts it in the sorted array.
Exercise #4.
Write a C program that reads a string and counts the total number
of characters and total no. of words in the string.
Exercise #5.
Write a C program that reads a string and extracts a substring from
it. To extract the substring, it reads starting position and ending
position of the substring in the string.
CABSMJ-1001 [2024-25]

Exercise #6.
Write a program in C to check whether a given number is a prime
number or not using function.

Exercise #7.
Write a C program that reads a given string and checks whether it
is a palindrome or not using function.

Exercise #8.
Write a C program that reads two matrices a and b of size mxn and
nxp respectively and finds their product matrix c = a*b using
function.

Exercise #9.
Write a C program to find the sum of the series 1!/1 + 2!/2 + 3!/3 +
4!/4 + 5!/5 upto n terms using the fact() function.
CABSMJ-1001 [2024-25]

Exercise #10.
Write a C program that reads a positive integer and checks
whether it is an Armstrong number or not using function.
Note: Armstrong number is a number that is equal to the sum of cubes of
its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong
numbers. 153 is Armstrong no. because: 13 + 53 + 33 = 153.

Exercise #11.
Write a C Program that reads a positive integer number and checks
whether the number is prime or not using function.
Note: A prime number is a positive integer that is divisible only by 1 and
itself. For example: 2, 3, 5, 7, 11, 13, 17 etc.

Exercise #12.
Write a C program that reads radius of a circle and finds the
circumference and area of the circle using a single function. Make
use of pointers.
CABSMJ-1001 [2024-25]

Exercise #13.
Write a C program that reads n integers in a 1D array and finds
number of odd and number of even integers using function and
pointer.
Exercise #14.
Write a C program that reads n integers in a 1D array and finds
maximum and minimum using a single function. Make use of pointers.
Exercise #15.
Write a C program that reads n integers in an array using a pointer
and replaces a given value stored in the array by another given value
using a pointer.
Exercise #16.
Write a C program to add and subtract two complex numbers using
structure and functions.
Exercise #17.
Write a C program to store information (Institute name, Total fees of
BCA course) of n private institutes using array of structures and find
the institute with highest fees using pointer to array of structures.
CABSMJ-1001 [2024-25]

End of
Unit-III

You might also like