Unit 3.1 C Notes by Prof. Shahid Masood
Unit 3.1 C Notes by Prof. Shahid Masood
CABSMJ-1001
Problem Solving Using C
Unit - III
CABSMJ-1001 [2024-25]
Arrays
CABSMJ-1001 [2024-25]
Integer 5 10 15 20 25
Array array a[5] 0 1 2 3 4
One-Dimensional Array
1D array is a sequential collection of finite number of related
data elements of the same type such that:
Individual elements are referenced by subscripted variable
consisting of array name and an index enclosed in square
brackets, e.g. a[i] refers to the ith element of the array a.
The array elements are stored in successive memory
locations.
CABSMJ-1001 [2024-25]
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
Declaring
1D Arrays 5201 5205 5209 5213 5217 5221 5225 5229 5233 5237
Base address int a[10]
Array Initialization
While declaring arrays, initial values can also be assigned:
int m[5] = {5, 10, 15, 20, 25};
Array size may be omitted. In this case, size is auto set equal to
the no. of elements in the initialization list, e.g.:
float percent[ ] = { 60.5, 72.3, 65.8, 70.0 }; /* array size = 4 */
If no. of elements in the initialization list < the array size, then
remaining elements are assigned zero values:
int a[5] = { 10, 15, 20 }; /* stored as { 10, 15, 20, 0, 0 } */
If no. of elements in the initialization list > the array size, then
this is treated as an ERROR:
int b[2] = { 10, 15, 20 }; /* error */
CABSMJ-1001 [2024-25]
Note:
It is programmer’s responsibility to ensure:
that the program refers to the array elements which are
within the declared limits.
Prob
Prob
Rows…
1 a10 a11
a12
is a collection of finite number, say
mxn, of homogenous elements such 2 a20 a21 a22
that: 3 a30 a31 a32
individual elements are referenced 2D array a of size 4x3
by array name followed by two indices and
the elements are stored in consecutive memory locations.
Declaring 2D arrays:
int a[4][3]; /* total elements = 4x3 = 12 */
float b[m][n]; /* total elements = mxn */
2D Arrays
Initial values can be assigned to elements while declaring:
int a[3][2] = {25,30,15,20,10,12}; /*values assigned row-wise */
or int a[][] = {{25,30},{15,20},{10,12}}; /* size is auto set = 3x2 */
0 1
0 25 30
1 15 20
2 10 12
Prob
Contd...
CABSMJ-1001 [2024-25]
printf("Matrix is\n");
Output
for ( i=0; i<M; i++)
Matrix size is: 3x4
{ for ( j=0; j<N; j++)
Enter 4 elements of row-0
{ printf("%d\t",a[i][j]);
10 11 12 13
}
Enter 4 elements of row-1
printf("\n"); /*print next row in next line*/
14 15 16 17
} Enter 4 elements of row-2
/* finding maximum value */
18 19 20 21
max = a[0][0];
Matrix is
for ( i=0; i<M; i++) 10 11 12 13
{ for ( j=0; j<N; j++) 14 15 16 17
{ if ( a[i][j] > max ) 18 19 20 21
max = a[i][j]; Maximum value in the matrix= 21
} Sum of all the elements= 186
}
printf("Maximum value in the matrix= %d\n",max);
printf("Sum of all the elements= %d",sum);
}
CABSMJ-1001 [2024-25]
Prob
0 1 2 3
0 Main diagonal elements
1
2
3
CABSMJ-1001
0 1 [2024-25]
2 3
0 11 12 13 14
/* sumdiagonal.c */
1 15 16 17 18
#include<stdio.h>
#define N 4 2 19 20 21 22
main() 3 23 24 25 26
{ int m[N][N], i, j, sum=0;
printf("integer matrix size is %d x %d\n",N,N);
for ( i=0; i<N; i++)
{ printf("Enter %d values for row-%d\n",N,i);
for (j=0; j<N; j++)
{ scanf("%d",&m[i][j]);
if ( i==j )
sum = sum + m[i][j];
}
}
Contd...
CABSMJ-1001 [2024-25]
printf("Matrix is\n");
for ( i=0; i<N; i++)
{ for ( j=0; j<N; j++)
{ printf("%d\t",m[i][j]);
}
printf("\n"); /* print next row in next line */
}
printf("Sum of main diagonal elements= %d",sum);
}
CABSMJ-1001 [2024-25]
Output
Integer matrix size is 4 x 4
Enter 4 values for row-0
11 12 13 14
Enter 4 values for row-1
15 16 17 18
Enter 4 values for row-2
19 20 21 22
Enter 4 values for row-3
23 24 25 26
Matrix is
11 12 13 14
15 16 17 18
19 20 21 22
23 24 25 26
Sum of main diagonal elements= 74
CABSMJ-1001 [2024-25]
Prob
/* matadd.c */
#include<stdio.h>
main()
{ int a[10][10], b[10][10], c[10][10], i, j, m, n;
printf("Enter no. of rows & cols in matrix a and b (Range: 1-10)\n");
scanf("%d %d",&m,&n);
printf("Enter elements of %dx%d matrix-a row-wise\n",m,n);
for (i=0; i<m; i++)
{ for (j=0; j<n; j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements of %dx%d matrix-b row-wise\n",m,n);
for (i=0; i<m; i++)
{ for (j=0; j<n; j++)
scanf("%d",&b[i][j]);
}
Contd...
CABSMJ-1001 [2024-25]
/* find matrix c */
Output
for (i=0; i<m; i++)
Enter no. of rows & cols in matrix a and
{ for (j=0; j<n; j++)
c[i][j] = a[i][j] + b[i][j]; b (Range: 1-10)
} 3 4
printf("\nMatrix-c\n"); Enter elements of 3x4 matrix-a row-wise
for (i=0; i<m; i++) 1 2 3 4
{ for (j=0; j<n; j++) 5 6 7 8
{ printf("%d\t",c[i][j]); 9 1 2 3
} Enter elements of 3x4 matrix-b row-wise
printf("\n"); 4 5 6 7
} 8 9 1 2
} 3 4 5 6
Matrix-c
5 7 9 11
13 15 8 10
12 5 7 9
CABSMJ-1001 [2024-25]
Prob
Write a C program that reads a mxn integer matrix a and finds
its transpose matrix.
Character Arrays
and
Strings
CABSMJ-1001 [2024-25]
name[31] N E W D E L H I \0 …
String 0 1 2 3 4 5 6 7 8 9 ………. 30
char s[31];
gets(s); Input
ARIF KHAN
char s[31];
fgets(s,31,stdin); /* n = 31 */ Input
ARIF KHAN
It stops reading:
when either (n-1) characters are read or
newline character is read, or the EOF is encountered,
whichever comes first.
CABSMJ-1001 [2024-25]
gets()/fgets() Function
char s[31];
scanf("%s",s); /* input: C IS EASY */
printf("%s",s); /* output: C */
Note: scanf() will read only first word of the inputted string
because scanf() treats whitespace character as delimiter.
s[31] C I S E A S Y \0 …
0 1 2 3 4 5 6 7 8 9 .… 30
CABSMJ-1001 [2024-25]
s[31] C I S E A S Y \0 …
0 1 2 3 4 5 6 7 8 9 .… 30
Prob
ASCII codes of
Uppercase and
Lowercase Alphabets
CABSMJ-1001 [2024-25]
Prob
Prob
Prob
Write a C program that reads a string s and reverses its
characters without using strrev() library function.
Prob
Write a program that tests whether a given string s is a
Palindrome or not.
Note: A string is called a palindrome if it reads the
same forward and backward (or the reverse of that string
is the same as the original string).
For example, "radar", "level", "1234321" etc.
CABSMJ-1001 [2024-25]
/* palindrome1.c */
#include<stdio.h>
#include<string.h>
main()
{ char s[81], rev[81];
printf("Enter a string (max 80 chars)\n");
gets(s);
strcpy(rev,s);
strrev(rev);
if ( strcmp(s,rev)==0 ) /* if given string and its reverse string are same */
printf("Palindrome");
else Output
printf("Not a Palindrome"); Enter a string (max 80 chars)
} ABCBA
Palindrome
CABSMJ-1001 [2024-25]
Prob
#include<string.h> A B C B A
0 1 2 3 4
main()
{ char s[81];
int len, i, ispalindrome = 1; comparisons
printf("Enter a string (max 80 chars)\n");
gets(s);
len = strlen(s);
for ( i=0; i<len/2; i++)
{ if ( s[i] != s[len-i-1] )
{ ispalindrome = 0;
break;
}
} Output
if ( ispalindrome==1 ) Enter a string (max 80 chars)
printf("Palindrome"); ABCDCBA
else Palindrome
printf("Not a Palindrome");
}
CABSMJ-1001 [2024-25]
Prob
Prob
A F T A B A H MA D K H A N \0 R A H U L \0 …
MOH D J AHANGI R AL I K H A N \0
First name
Middle name
Last name
CABSMJ-1001 [2024-25]
A F T A B A HMA D K H A N \0
/* namebreak.c */
#include<stdio.h> T A R I Q M E H M O O D \0 …
main() R A H U L \0 …
{ char name[41],fn[21],mn[21],ln[21];
int i, j;
fn[0] = mn[0] = ln[0] = '\0'; /* Empty strings */
printf("Enter a name\n");
gets(name);
i = j = 0;
while ( !(name[i]==' ' || name[i]=='\0' ) )
{ fn[j++] = name[i++];
}
fn[j] = '\0';
j = 0;
Contd...
A F T A B CABSMJ-1001
A H M A D K H A[2024-25]
N \0
if ( name[i]!='\0' )
{ i++; T A R I Q M E H M O O D \0 …
while ( !(name[i]==' ' || name[i]=='\0' ) ) R A H U L \0 …
{ mn[j++] = name[i++];
}
Output
mn[j] = '\0';
Enter name (consisting of first,
} middle and last name)
j = 0; AFTAB AHMAD KHAN
if ( name[i]!='\0' ) First name: AFTAB
{ i++; Middle name: AHMAD
while ( name[i] != '\0' ) Last name: KHAN
{ ln[j++] = name[i++];
Output
}
Enter name (consisting of first,
ln[j] = '\0'; middle and last name)
} MOHD JAHANGIR ALI KHAN
printf("First name: %s\n",fn); First name: MOHD
printf("Middle name: %s\n",mn); Middle name: JAHANGIR
printf("Last name: %s",ln); Last name: ALI KHAN
}
CABSMJ-1001 [2024-25]
0 1 2 3
2D char Arrays 0 M O N \0
1 T U E \0
Used to store a collection of strings. 2 W E D \0
After a 2D char array is declared, it is 3 T H U \0
4 F R I \0
used as 1D array for performing string I/O
5 S A T \0
operations and other manipulations. 6 S U N \0
Declaration
char name[10][31]; /* can be used to store 10 names (max length 30) */
char days[7][4] = {"MON","TUE","WED","THU","FRI","SAT","SUN"};
days[i] refers to the string in ith row.
gets( days[i] ); /* to read a string in ith row */
puts( days[i] ); /* to output the string of ith row */
putchar( days[i][j] ); /* to output jth character of ith row */
CABSMJ-1001 [2024-25]
Prob
Prob
Write a C program that reads rollnos and marks obtained by n
students in their 3 sessionals of C programming and prints:
1. rollno and average marks of each student.
2. details of the student securing highest average marks.
Output Contd…
Average sessional marks
21CABSA101 65 67 87 73.000000
21CABSA102 55 62 67 61.333332
21CABSA103 45 56 78 59.666668
21CABSA104 76 75 74 75.000000
21CABSA105 43 61 54 52.666668
21CABSA106 45 55 76 58.666668
21CABSA107 45 67 76 62.666668
21CABSA108 54 56 68 59.333332
21CABSA109 65 69 54 62.666668
21CABSA110 56 34 78 56.000000
Details of student securing highest average marks
21CABSA104 76 75 74 75.000000
CABSMJ-1001 [2024-25]
Structure
and
Union
Structure structCABSMJ-1001
MyStructure[2024-25]
template { int i;
Structure structure
char c;
members
Structure is a way to group different float f;
types of related variables together };
into a single unit. struct MyStructure x;
Syntax:
StructName.MemberName
e.g. s1.rno /* to access rno member of structure s1 */
Prob:
Output
Student-1
Enter RollNo: 99CABSA101
Enter Name: Jameel Ahmad
Enter Age and Height: 21 167
Student-2
Enter RollNo: 99CABSA102
Enter Name: Fareed Khan
Enter Age and Height: 20 162.5
Prob:
Write a C program that reads two distances in feet and
inches and adds them (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
/* struct8b.c */ CABSMJ-1001 [2024-25]
#include<stdio.h>
struct distancetype
{ int feet;
int inch;
};
typedef struct distancetype distance;
main()
{ distance d1, d2, res;
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);
res.feet = d1.feet + d2.feet; Output
res.inch = d1.inch + d2.inch; Enter distance-1 (as feet and inches)
if ( res.inch>=12 ) 4 8
{ res.feet += res.inch/12; Enter distance-2 (as feet and inches)
res.inch = res.inch%12; 2 6
} Sum of two distances: 7 feet 2 inch
printf("Sum of two distances: %d feet %d inch\n",res.feet,res.inch);
}
rno name height CABSMJ-1001 [2024-25]
age
Array of
Structures s[0] s[1] s[2]
Array of structures
Prob:
Prob:
else if (s1.dob.yr>s2.dob.yr ||
(s1.dob.yr==s2.dob.yr && s1.dob.mon>s2.dob.mon) ||
(s1.dob.yr==s2.dob.yr && s1.dob.mon==s2.dob.mon &&
s1.dob.day>s2.dob.day))
{ printf("Older student is s2\n");
printf("%-10s %-30s %.1f %02d/%02d/%4d\n",s2.rno,s2.name,
s2.height,s2.dob.day,s2.dob.mon,s2.dob.yr);
}
else
{ printf("\nOlder student is s1\n");
printf("%-10s %-30s %.1f %02d/%02d/%4d\n",s1.rno,s1.name,
s1.height,s1.dob.day,s1.dob.mon,s1.dob.yr);
}
}
CABSMJ-1001 [2024-25]
Output
Student-1
Enter RollNo: 1001
Enter Name: Sarfaraz Ali
Enter Height: 165
Enter dob (dd/mm/yyyy): 11/01/2002
Student-2
Enter RollNo: 1002
Enter Name: Navin Kumar
Enter Height: 167
Enter dob (dd/mm/yyyy): 05/03/2002
Details of Students are:
1001 Sarfaraz Ali 165.0 11/01/2002
1002 Navin Kumar 167.0 05/03/2002
Older student is s1
1001 Sarfaraz Ali 165.0 11/01/2002
CABSMJ-1001 [2024-25]
Union
CABSMJ-1001 [2024-25]
struct cid union cid
{ char c; Storage { char c;
Union int i; allocated=13 bytes int i;
double d; 1 4 8 double d; 8
} s1; byte bytes bytes } u1; bytes
printf("%lf",u1.d); 545.568400
Prob:
Write a C program that displays following menu:
Menu
1. Add two integer type numbers
2. Add two float type numbers
3. Add two double type numbers
4. Exit
Choice: -
Then depending upon user’s choice, the program performs
following actions:
If choice is 1, it reads two int type numbers and displays their sum.
If choice is 2, it reads two float type numbers and displays their sum.
If choice is 3, it reads two double type numbers and displays their sum.
Note: Make use of union data type.
CABSMJ-1001 [2024-25]
/* union2.c */
#include<stdio.h>
main()
{ union ifd
{ int i;
float f;
double d;
};
union ifd u1, u2, u3;
int choice;
do
{ printf("\nMenu\n");
printf("1. Add two integer type numbers\n");
printf("2. Add two float type numbers\n");
printf("3. Add two double type numbers\n");
printf("4. Exit\n");
printf("Choice: ");
scanf("%d",&choice); Contd...
CABSMJ-1001 [2024-25]
switch (choice)
{ case 1: printf("Enter two integers: ");
scanf("%d %d",&u1.i,&u2.i);
u3.i = u1.i + u2.i;
printf("Result= %d\n",u3.i);
break;
case 2: printf("Enter two floats: ");
scanf("%f %f",&u1.f,&u2.f);
u3.f = u1.f + u2.f;
printf("Result= %f\n",u3.f);
break;
case 3: printf("Enter two double type numbers: ");
scanf("%lf %lf",&u1.d,&u2.d);
u3.d = u1.d + u2.d;
printf("Result= %lf\n",u3.d);
}
} while (choice !=4 );
}
Output CABSMJ-1001 [2024-25]
Menu
1. Add two integer type numbers
2. Add two float type numbers
3. Add two double type numbers
4. Exit
Choice: 1
Enter two integers: 10 20
Result= 30
Menu
1. Add two integer type numbers
2. Add two float type numbers
3. Add two double type numbers
4. Exit
Choice: 2
Enter two floats: 15.50 12.10
Result= 27.600000 Note: Union provides
Menu an efficient way of
1. Add two integer type numbers using the same memory
2. Add two float type numbers
3. Add two double type numbers
location for multiple
4. Exit purposes.
Choice: 4
CABSMJ-1001 [2024-25]
User-Defined
Functions
CABSMJ-1001 [2024-25]
User-defined
Functions Large and
complex Problem
Function
A function is a block of code that performs a specific task.
It is a complete & independently defined program segment
that works under the control of main() function (can’t run on
its own).
C allows us to define functions in our programs according to
our need.
As these functions are defined by the users, they are called
user-defined functions.
For example, to find the biggest and to find the average of all
the array elements, we can create two functions:
1. biggest() function and
2. average() function
CABSMJ-1001 [2024-25]
Function
Programmers need to write their own functions to perform
tasks for which library functions are not available, e.g.
1. to find factorial of a +ve integer,
Function Definition
Function definition consists of the function header and
function body (block of code to perform a specific task).
Syntax of function definition: Function receives input
through argument list
returnType functionName(type1 argument1, type2 argument2, ...)
{ /* body of the function */
Function header
..........
}
#include<stdio.h>
void printline(int len, char c) /* accepts values */
{ int i;
for ( i=1; i<=len; i++ )
printf("%c",c);
printf("\n"); /* returns no value */
} /* so there is no return statement */
main()
{ printline(80,'-');
printline(60,'*');
}
CABSMJ-1001 [2024-25]
#include<stdio.h>
void printline() /* accepts no value */
{ int i;
for ( i=1; i<=80; i++ )
printf("%c",'-');
printf("\n"); /* returns no value */
}
main()
{ printline();
}
CABSMJ-1001 [2024-25]
Prob
/* factusingfn.c */
#include<stdio.h>
Variables declared inside a block are called
int factorial(int n) local variables. A local variable exists only
{ int i, fact=1; inside the block in which it is declared.
for ( i=2; i<=n; i++ )
{ fact = fact * i;
} Output
return fact; Enter non-negative int value
} 5
main() Factorial of 5 = 120
{ int n, fact;
printf("Enter non-negative int value\n");
scanf("%d",&n); We can use same variable name
fact = factorial(n); in different functions.
printf("Factorial of %d = %d\n",n,fact);
}
CABSMJ-1001 [2024-25]
Prob
Prob:
Prob
Prob:
Write a C program that reads two positive integers and finds
their GCD (greatest common divisor) and LCM (lowest common
mean) using functions.
#include<stdio.h>
int gcd(int x,int y)
{ int r = x % y;
while ( r !=0 )
{ x = y;
y = r;
r = x % y;
}
return y;
}
int lcm(int x,int y)
{ int max = x>y ? x : y;
while ( 1 )
{ if ( max%x==0 && max%y==0 )
break;
max++;
}
return max;
} Contd...
CABSMJ-1001 [2024-25]
main()
{ int x, y;
printf("Enter two +ve integers: ");
scanf("%d %d",&x,&y);
if ( x<=0 || y<=0 )
printf("x and y should be positive integers");
else
{ printf("GCD = %d\n",gcd(x,y)); Output
printf("LCM = %d\n",lcm(x,y)); Enter two +ve integers: 25 40
} GCD = 5
} LCM = 200
Output
Enter two +ve integers: 14 35
GCD = 7
LCM = 70
CABSMJ-1001 [2024-25]
Prob
Prob
In this way all the elements (except the last) are compared
with their next element and are interchanged if required.
This is called a pass.
After 1st pass, the largest value gets placed at the last (i.e. n-
1th) position in the array which is its final position. Now, only
first n-1 elements are left for sorting.
CABSMJ-1001 [2024-25]
Bubble Sort
Thus, after making n-1 such passes, the data gets sorted.
CABSMJ-1001 [2024-25]
0. 46 20 20 20 20 20 20 20
1. 20 46 46 46 46 46 25 25
2. 65 65 25 25 25 25 46 46
3. 25 25 65 58 58 58 58 15
4. 58 58 58 65 15 15 15 58
5. 15 15 15 15 65 65 65 65
Prob
c[p]: 10 15 18 27 35 50 65 90
p=m+n
c[p]: 10 15 18 27 35 50 65 90 k=0/ 1/ 2/ 3/ 4/ 5
p=m+n 0 1 2 3 4 5 6 7
Prob
#include<stdio.h>
#define N 10
void readmat(int x[][N],int m,int n);
void printmat(int x[][N],int m,int n);
void addmat(int a[][N],int b[][N],int c[][N],int m,int n);
main()
{ int a[N][N], b[N][N], c[N][N], i, j, m, n;
printf("Enter Size (no. of rows & cols) of matrices (Range: 1-%d)\n",N);
scanf("%d %d",&m,&n);
printf("Matrix-a (size %dx%d) - enter elements row-wise\n",m,n);
readmat(a,m,n);
printf("Matrix-b (size %dx%d) - enter elements row-wise\n",m,n);
readmat(b,m,n);
addmat(a,b,c,m,n);
printf("Matrix-c\n");
printmat(c,m,n);
} Contd...
CABSMJ-1001 [2024-25]