Unit 3.2 C Notes by Prof. Shahid Masood
Unit 3.2 C Notes by Prof. Shahid Masood
Structures
and
Functions
CABSMJ-1001 [2024-25]
/* 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]
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().
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().
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.
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
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:
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:
Prob:
/* 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]
/* 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]
Prob:
(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]
/* 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]
Actual
arguments
/* 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:
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
Prob:
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:
Prob:
Prob:
char *str1;
str1 = "Computer";
or char *str1 = "Computer";
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
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]
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]
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;
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:
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]
s[3]
s[0] s[1] s[2]
p p+1 p+2
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]
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
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
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