0% found this document useful (0 votes)
46 views146 pages

Unit 3.1 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)
46 views146 pages

Unit 3.1 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/ 146

CABSMJ-1001 [2024-25]

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

 Array is a sequential collection of finite number of:


 related data elements of the same type
 that are referred to by a common name.

 Arrays can be 1D, 2D and multi-dimensional.

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]

Gen.form: data-type arrayname[size];


e.g. int a[10]; /* if initial values are not assigned then */
float weight[5]; /* array elements contain garbage value */

 Array name a stores the address of a[0], called base address of a.


 Computer doesn’t keep track of the address of each element of
the array, instead it only stores the base address of the array.
 Address of the ith element of the array is computed using:
Address of a[i] = Base + ( i – LB )*w (w=size of each element)
 If Base(a) is 5201 and w is 4 bytes, then:
address of a[3] = 5201 + ( 3 – 0 ) *4 = 5213
CABSMJ-1001 [2024-25]

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]

How to read data in array elements?


int a[5] 5 10 15 20 25
int a[5]; 0 1 2 3 4
for ( i=0; i<5; i++) Enter element a[0]: 5
{ printf("Enter element a[",%d,"]:",i);
Enter element a[1]: 10
scanf("%d",&a[i]);
Enter element a[2]: 15
}
Enter element a[3]: 20
Enter element a[4]: 25

How to access and output array elements?


for ( i=0; i<5; i++) int a[5] 10 20 30 40 50
{ a[i] = a[i] * 2; 0 1 2 3 4
printf("%d ",a[i]);
} Output
10 20 30 40 50
CABSMJ-1001 [2024-25]
int a[5] 10 20 30 40 50
Predict Output? 0 1 2 3 4

/* accessing an element which is beyond the declared limits */


for ( i=0; i<=5; i++)
printf("%d ",a[i]); Output
10 20 30 40 50 Garbage

Note:
 It is programmer’s responsibility to ensure:
 that the program refers to the array elements which are
 within the declared limits.

 If we refer to the array elements which are beyond the


declared limits:
 the compiler may not give any error message and
 we get unpredictable results (as shown above).
CABSMJ-1001 [2024-25]

Prob

Write a C program that reads marks obtained by students in a


test (maximum 10 students) and finds how many students have
secured marks > average marks.
CABSMJ-1001 [2024-25]
/* marks.c */
#include<stdio.h>
#define N 10 Enter marks-1: 50
main() Enter marks-2: 45
{ int m[N], sum=0, i, count=0; Enter marks-3: 55
float avg; Enter marks-4: 48
for(i=0; i<N; i++) Enter marks-5: 60
Enter marks-6: 65
{ printf("Enter marks-%d: ",i+1);
Enter marks-7: 58
scanf("%d",&m[i]);
Enter marks-8: 72
sum = sum+m[i];
Enter marks-9: 66
} Enter marks-10: 41
avg = (float)sum/N; Average Marks= 56.099998
for(i=0; i<N; i++) No. of students
{ if ( m[i]>avg ) count++; securing>Average marks= 5
}
printf("Average Marks= %f\n",avg);
printf("No. of students securing>Average marks= %d",count);
}
CABSMJ-1001 [2024-25]

Prob

Write a C program that reads n numbers in an array and finds


biggest and smallest number.
/* bigsmall.c */ CABSMJ-1001 [2024-25]
34 50 10 87 53 20 12 78 98 55
#include<stdio.h>
0 1 2 3 4 5 6 7 8 9
#define N 10
big=34, 50, 87, 98 int a[10] small = 34, 10
main()
{ int a[N], big, small, i;
printf("Enter %d integer numbers\n",N); Enter 10 integer numbers
for(i=0; i<=(N-1); i++) Enter number-1: 34
Enter number-2: 50
{ printf("Enter number-%d: ",i+1);
Enter number-3: 10
scanf("%d",&a[i]);
Enter number-4: 87
}
Enter number-5: 53
big = small = a[0]; Enter number-6: 20
for(i=1; i<=(N-1); i++) Enter number-7: 12
{ if ( a[i]>big ) Enter number-8: 78
big=a[i]; Enter number-9: 98
else if ( a[i]<small ) Enter number-10: 55
small=a[i]; Biggest= 98, Smallest= 10
}
printf("Biggest= %d, Smallest= %d",big,small);
}
CABSMJ-1001
Columns…. [2024-25]
0 1 2
2D Array 0 a00 a01 a02

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.

 Size of the 2D array is denoted by mxn.

Declaring 2D arrays:
int a[4][3]; /* total elements = 4x3 = 12 */
float b[m][n]; /* total elements = mxn */

 An element in ith row and jth column is denoted by a[i][j]


CABSMJ-1001 [2024-25]

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

 In C, 2D array elements are stored in memory in row-major


order (i.e. row-by-row):
25 30 15 20 10 12
row 0 row 1 row 2
CABSMJ-1001 [2024-25]

Prob

 Write a C program that reads an integer matrix of size mxn


and finds the:
 maximum value in the matrix, and
 sum of all the elements of the matrix.
CABSMJ-1001
Columns…. [2024-25]
R 0 1 2 3
/* matmax.c */ o
0 a00 a01 a02 a03
#include<stdio.h> w
#define M 3 s 1 a10 a11 a12 a13
#define N 4 2 a20 a21 a22 a23
main() int a[3[4]
{ int a[M][N], max, i, j, sum=0;
printf("Matrix size is: %dx%d\n",M,N);
for ( i=0; i<M; i++) /* varies row no. from 0 to 2 */
{ printf("Enter %d elements of row-%d\n",N,i);
for ( j=0; j<N; j++) /* varies column no. from 0 to 3 */
{ scanf("%d",&a[i][j]);
sum = sum + a[i][j];
}
}

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

Write a C program that reads a nxn integer matrix and finds


sum of its main diagonal elements.

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

 Write a C program that reads two mxn integer matrices a and


b and finds addition matrix c = a + b.

for example, if matrices a and b are of size 3x4 then matrix c


is computed as below:
a b c
1 2 3 4 4 5 6 7 5 7 9 11
5 6 7 8 + 8 9 1 2 = 13 15 8 10
9 1 2 3 3 4 5 6 12 5 7 9
CABSMJ-1001 [2024-25]

/* 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.

 Transpose of a mxn matrix A is an nxm matrix T such that:


Tji = Aij for 0  i  m-1 and 0  j  n-1
i.e. the rows of A are written as the new columns of T.
 If size of A is mxn, then size of T will be nxm.
/* transpose.c */ CABSMJ-1001 [2024-25]
#include<stdio.h>
main()
{ int a[10][10], transpose[10][10], m, n, i, j;
printf("Enter number of rows (MAX value 10): ");
scanf("%d",&m);
printf("Enter number of columns (MAX value 10): ");
scanf("%d",&n);
printf("Matrix size %dx%d - Enter matrix elements row-wise:\n",m,n);
for (i=0; i<m; i++)
{ for (j=0; j<n; j++)
{ scanf("%d",&a[i][j]);
}
}
printf("\nEntered matrix:\n");
for (i=0; i<m; i++)
{ for (j=0; j<n; j++)
{ printf("%d\t",a[i][j]);
}
printf("\n"); Contd...
}
a[i][j] t[j][i]
CABSMJ-1001 [2024-25]

/* finding transpose matrix */


for (i=0; i<m; i++)
{ for (j=0; j<n; j++)
{ transpose[j][i] = a[i][j];
}
}
printf("\nTranspose of the matrix:\n");
for (i=0; i<n; i++)
{ for (j=0; j<m; j++)
{ printf("%d\t",transpose[i][j]);
}
printf("\n");
}
}
CABSMJ-1001 [2024-25]
Output
Enter number of rows (MAX value 10): 3
Enter number of columns (MAX value 10): 4
Matrix size 3x4 - Enter matrix elements row-wise:
11 12 13 14
15 16 17 18
19 20 21 22
Entered matrix:
11 12 13 14
15 16 17 18
19 20 21 22
Transpose of the matrix:
11 15 19
12 16 20
13 17 21
14 18 22
CABSMJ-1001 [2024-25]

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

 A string is a sequence of characters enclosed in double quote


marks.

 In C, a 1D char array is used to hold a single string, e.g.


char str[21]; /* can store a string consisting of max 20 chars */
char name[31]="NEW DELHI"; /*assigning string while declaring */
A NULL character '\0' is auto appended to the string when it is
stored in the memory that denotes the end of the string.

 After a 1D char array is declared, it is used as an ordinary variable


for performing string I/O operations & other manipulations:
e.g. scanf("%s",str); /* array name refers to the whole string */
printf("%s",str);
CABSMJ-1001 [2024-25]
s A R I F K H A N \0 …
0 1 2 3 4 5 6 7 8 ……. 30

gets() Function (Reading a String/Text Line from Keyboard)


 gets(s); reads a string/text line from stdin (i.e. keyboard)
 into the buffer pointed to by s
 until a newline character is encountered.

char s[31];
gets(s); Input
ARIF KHAN

 A NULL character '\0' is auto appended to the string:


 when it is stored in the memory
 that denotes the end of the string.
CABSMJ-1001 [2024-25]
s A R I F K H A N \0 …
0 1 2 3 4 5 6 7 8 ……. 30

fgets() Function (Reading a String/Text Line from Keyboard)


 fgets(s,n,stdin); reads a string/text line:
 from the stdin stream i.e. keyboard or a specified file and
 stores it into the string pointed to by s.

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

Example: Reading name and address of a person:


char name[31], address[81];
printf("Enter name (max 30 chars)\n");
gets(name);
printf("Enter address (max 80 chars)\n");
fgets(address, 81, stdin); Output
printf("%s\n",name); Enter name (max 30 chars)
printf("%s\n",address); ARIF KHAN
Enter address (max 80 chars)
X-56, New Sir Syed Nagar, Aligarh
ARIF KHAN
X-56, New Sir Syed Nagar, Aligarh
CABSMJ-1001 [2024-25]

scanf() v/s s[31] C \0 …


gets() 0 1 2 3 4 5 6 7 8 9 ..…. 30

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.

 Therefore to read an entire multiword string, gets() or fgets()


functions should be used:
gets(s); or fgets(s,31,stdin); /* input: C IS EASY */
printf("%s",s); /* output: C IS EASY */

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]

puts() Function (Writing/displaying a String/Text Line on the Screen)


 The statement puts(s); writes the string s followed by a
newline character to the stdout stream i.e. screen.

char s[31] = "C IS EASY"; Output


puts(s); C IS EASY
|
fputs() Function
 The statement fputs(s, stdout); writes the string s to the
stdout stream i.e. screen.
 Like puts(), it does not write a trailing newline.
char s[31] = "C IS EASY";
Output
fputs(s,stdout);
C IS EASY|
CABSMJ-1001 [2024-25]

C program to illustrate use of gets(), fgets(), puts() & fputs()


/* getsfgets.c */
#include<stdio.h>
main()
{ char name[31], address[81];
puts("Enter name (max 30 chars)");
gets(name);
fputs("Enter address (max 80 chars)\n",stdout);
fgets(address, 81, stdin); Output
puts("You entered:"); Enter name (max 30 chars)
puts(name); E Balagurusamy
fputs(address, stdout); Enter address (max 80 chars)
} Chairman, EBG Foundation, Coimbatore.
You entered:
E Balagurusamy
Chairman, EBG Foundation, Coimbatore.
CABSMJ-1001 [2024-25]

How to Access a Particular Character of a String

s[31] C I S E A S Y \0 …
0 1 2 3 4 5 6 7 8 9 .… 30

 ith character of a string s can be accessed using:


s[i]
 Example: int i = 0;
char s[31] = "C IS EASY";
while ( s[i] != '\0' )
{ printf("%c",s[i]); /*prints string char-by-char */
i++;
} Output
C IS EASY
CABSMJ-1001 [2024-25]

Prob

Write a C program that reads a string (containing lowercase and


uppercase letters) and converts its all lowercase letters to
uppercase.
CABSMJ-1001 [2024-25]
/* touppercase.c */
#include<stdio.h> Output
#include<ctype.h> Enter a string containing lowercase & uppercase letters
#define N 81 This text will be converted to uppercase
main() String in uppercase
{ char s[N]; THIS TEXT WILL BE CONVERTED TO UPPERCASE
int i = 0;
printf("Enter a string containing lowercase & uppercase letters\n");
gets(s);
while( s[i] !='\0' ) /* conversion without using library fn */
{ if ( islower(s[i]) ) /* if ( s[i]>='a' && s[i]<='z' ) */
s[i] = toupper(s[i]); /* s[i] = s[i] - 32; */
i++;
}
printf("String in uppercase\n");
puts(s);
}
CABSMJ-1001 [2024-25]

ASCII codes of
Uppercase and
Lowercase Alphabets
CABSMJ-1001 [2024-25]

Prob

Write a C program that counts occurrences of a given character


c in a given string s.
For example, if string is "honesty is the best policy" and we
want to count how many times the character 'e' appears in the
string then the answer is 3.
CABSMJ-1001 [2024-25]
Output
Enter a string
/* countchar.c */ this is the given string
#include<stdio.h> Enter the character to be counted
main() i
{ char s[81], c; Character i appears 4 times in the string
int i=0, count=0;
printf("Enter a string (max 80 chars)\n");
gets(s);
printf("Enter the character to be counted\n");
c = getchar();
while ( s[i] !='\0' )
{ if ( s[i]==c )
count++;
i++;
}
printf("Character %c appears %d times in the string",c,count);
}
CABSMJ-1001 [2024-25]

Library Functions For String Manipulation


 C supports following string manipulation functions.
 They are defined in string.h header file.
Gives no. of characters in the string (excluding \0
strlen(s)
char)
strcpy(s1,s2) Copies string s2 into s1
strncpy(s1,s2,n) Copies upto n characters from string s2 into s1
strcat(s1,s2) Appends/adds string s2 to the end of s1
Compares string s1 with s2 i.e. it finds whether
strcmp(s1,s2) s1<s2 or s1=s2 or s1>s2 (returns –ve, 0 or +ve
value respectively)
strncmp(s1,s2,n) Compares first n characters of string s1 with s2
and returns –ve, 0 or +ve value
CABSMJ-1001 [2024-25]

Library Functions For String Manipulation (Contd…)

strrev(s) Reverses the order of characters in the string s

strupr(s) Converts string s to uppercase

strlwr(s) Converts string s to lowercase


CABSMJ-1001 [2024-25]

Prob

Given following three strings:


char s1[]="Computer ", s2[]="Science ", s3[]="Department";
Write a C Program to illustrate various string operations on
these strings using built-in string manipulation functions.
CABSMJ-1001 [2024-25]
/* stroperations.c */
#include<stdio.h>
#include<string.h>
main()
{ char s1[]="Computer ", s2[]="Science ", s3[]="Department";
char csd[81];
/* comparing s1 with s2 */
if ( strcmp(s1,s2)<0 )
printf("s1 < s2\n");
else if ( strcmp(s1,s2)==0 )
printf("s1 = s2\n");
else if ( strcmp(s1,s2)>0 )
printf("s1 > s2\n");
/* adding the 3 strings together in csd */
strcpy(csd,s1);
strcat(csd,s2);
strcat(csd,s3);
printf("Strings after concatenation\n");
Contd...
puts(csd);
CABSMJ-1001 [2024-25]
/* converting csd to uppercase */
strupr(csd);
printf("String in uppercase\n");
puts(csd);
/* reversing string csd */
strrev(csd);
printf("String in reverse order\n");
puts(csd);
} Output
s1 < s2
Strings after concatenation
Computer Science Department
String in uppercase
COMPUTER SCIENCE DEPARTMENT
String in reverse order
TNEMTRAPED ECNEICS RETUPMOC
CABSMJ-1001 [2024-25]

Prob
Write a C program that reads a string s and reverses its
characters without using strrev() library function.

How to reverse string characters?


len = strlen(s); A L I G A R H len=7 #exchanges
for( i=0; i<len/2; i++) 0 1 2 3 4 5 6 =len/2 =3

{ /* interchange s[i] with s[len-i-1] */ Execute a loop from


exchanges i = 0 to len/2 -1
t = s[i]; s[i] s[len-i-1]
s[i] = s[len-i-1]; s[0] s[6] (interchange)
s[len-i-1] = t; s[1] s[5] “
H R A G I L A s[2] s[4] “
}
CABSMJ-1001 [2024-25]
A L I G A R H
/*strreverse.c */ 0 1 2 3 4 5 6
#include<stdio.h>
#include<string.h> exchanges
main()
H R A G I L A
{ char s[81], t;
int i=0, len;
printf("Enter a string (max 80 chars)\n");
gets(s);
len = strlen(s); Output
for( i=0; i<len/2; i++) Enter a string (max 80 chars)
{ t = s[i]; This is my string
s[i] = s[len-i-1]; String after reversing its characters
s[len-i-1] = t; gnirts ym si sihT
}
printf("String after reversing its characters\n");
puts(s);
}
CABSMJ-1001 [2024-25]

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

Write a program that tests whether a given string s is a


Palindrome or not without using strrev() library function.
How to find whether a given string is a palindrome or not by
comparing individual characters?
ispalindrome = 1; string s len #Comp.
len = strlen(s); 5 =(len/2) = 2
for ( i=0; i<len/2; i++) A B C B A Execute a loop from
{ if ( s[i] != s[len-i-1] ) 0 1 2 3 4 i = 0 to len/2 -1
{ ispalindrome = 0; Compare
break; comparisons s[i] s[len-i-1]
} s[0] s[4]
} s[1] s[3]
#include<stdio.h> /* palindrome2.c */ CABSMJ-1001 [2024-25]

#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

Write a C program that reads a string s, removes all vowels


from it and creates a new string s2.
/* stringremvowels.c */ CABSMJ-1001 [2024-25]
#include<stdio.h> s[81] C P r o g r a m m i n g \0 …
main() 0 1 2 3 4 5 6 7 8 9 ..…. 80

{ char s[81], s2[81]; s2[81] C P r g r m m n g \0


int i, j=0;
printf("Enter a string (max length: 80 chars)\n");
gets(s);
for ( i=0; s[i]!='\0'; i++ )
{ if (s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u')
continue;
else Output
{ s2[j] = s[i]; Enter a string (max length: 80 chars)
j++; C Programming
} String after removing vowels
} C Prgrmmng
s2[j] = '\0';
printf("String after removing vowels\n");
puts(s2);
}
CABSMJ-1001 [2024-25]

Prob

 Write a C program that reads name of a person and breaks it


into first name, middle name and last name.
 For example:

A F T A B A H MA D K H A N \0 R A H U L \0 …

First name First name


Middle name Middle name=Empty
Last name Last name=Empty

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

Write a C program that reads n names and finds longest name.


/* longestname.c */ CABSMJ-1001 [2024-25]
#include<stdio.h>
#include<string.h>
#define N 10
main() Output
{ char name[N][31], longest[31]; Enter 10 names
int i; Rafique Ahmad
printf("Enter %d names\n",N); Harsh Varshney
for (i=0; i<N; i++) Tayyaba Junaid
{ gets(name[i]); Mohd Maaz Zakir
} Mohammad Shakir Qidwai
strcpy(longest,name[0]); Ghufran Ahmad
for (i=1; i<N; i++) Neha Agarwal
{ if ( strlen(name[i]) > strlen(longest) ) Nikhil Verma
strcpy(longest,name[i]); Sabih Ahmad Khan
} Sudhir Sharma
puts("Longest name is"); Longest name is
puts(longest);
Mohammad Shakir Qidwai
}
CABSMJ-1001 [2024-25]

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.

Input format: 99CABSA101 65 67 87


CABSMJ-1001 [2024-25]
/* avgmarks.c */ rno[10][11] m[10][3] avg[10]
#include<stdio.h> 0 99CABSA101\0 65 67 87
#define N 10 1 99CABSA102\0 55 62 67
main() 2 99CABSA103\0 45 56 78
{ char rno[N][11]; : : : : : :
int m[N][3], i, loch=0; 9 99CABSA110\0 56 34 78
float avg[N];
printf("Enter rollno and 3 SessMarks of %d students\n",N);
for (i=0; i<=(N-1); i++)
{ scanf("%s %d %d %d",rno[i],&m[i][0],&m[i][1],&m[i][2]);
avg[i] = ( m[i][0] + m[i][1] + m[i][2] )/3.0;
} Input format:
printf("Average sessional marks\n"); 99CABSA101 65 67 87
for (i=0; i<=(N-1); i++)
{ printf("%s %d %d %d %f\n",rno[i],m[i][0],m[i][1],m[i][2],avg[i]);
}
Contd...
CABSMJ-1001 [2024-25]

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


{ if ( avg[i] > avg[loch] )
loch = i;
}
printf("Details of student securing highest average marks\n");
printf("%s %d %d %d %f",rno[loch],m[loch][0],m[loch][1],
m[loch][2],avg[loch]);
} Output
Enter rollno and 3 SessMarks of 10 students
21CABSA101 65 67 87
21CABSA102 55 62 67
21CABSA103 45 56 78
21CABSA104 76 75 74
21CABSA105 43 61 54
:
:
21CABSA110 56 34 78 Contd...
CABSMJ-1001 [2024-25]

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;

 struct keyword is used to create the struct type user-defined


data type.
 Unlike an array, a structure can contain many different data
types (built-in type like int, float, double, char etc. as well as
user-defined type).
 Each variable in the structure is known as a member of the
structure.
 Structure template describes a format to represent
information as shown in fig.
CABSMJ-1001 [2024-25]
s1
Structure Declaration rno name age height
s2

 We can declare a structure by using the struct keyword and


declare each of its members inside the curly braces:
struct studtype  It only provides info to the compiler that
Structure it is a struct which contains 4 members.
template
{ char rno[11];
char name[41];  No memory is reserved for this structure,
int age; so we can’t store data.
float height;  Using its typename (struct studtype), we
}; can create variables/arrays of this type.

Creation of variables of studtype structure


struct studtype s1,s2;
typedef struct studtype student;
student s3,s4;
CABSMJ-1001 [2024-25]
s1
Structure rno name age height
s2

Structure declaration & Variable creation can be combined


struct studtype
{ char rno[11]; /*members are stored in contiguous mem. locations*/
char name[41];
int age;
float height;
} s1, s2;

Initial values can also be assigned while creating structure


variables
struct studtype s3 = {"21CABSA101", "Mohd Javed", 20, 163};
CABSMJ-1001 [2024-25]
s1
Accessing Structure rno name age height
Members

Syntax:
StructName.MemberName
e.g. s1.rno /* to access rno member of structure s1 */

Reading input in structure members


scanf("%s",s1.rno); /* char array */
gets(s1.name); /* char array */
scanf("%d %f",&s1.age,&s1.height);

Outputting structure members


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

Copying the Contents of a Structure into Another Structure

Contents of a structure s1 can be copied into s2 in two ways:

(i). Copying member by member


strcpy(s2.rno, s1.rno);
strcpy(s2.name, s1.name); s1 99CABSA101 Jameel Ahmad 21 167
s2.age = s1.age; rno name age height
s2.height = s1.height; s2

(ii). Assigning one structure to another


(just like an ordinary variable)
s2 = s1;
/* all the members of s1 are copied into corresponding members of s2 */
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads details (rno, name, age, height)


of two students in two structure variables and prints the
details of the student having larger height.
/* struct1.c */ CABSMJ-1001 [2024-25]
s1
#include<stdio.h> rno name age height
void main()
s2
{ struct studtype
{ char rno[11];
char name[41];
int age;
float height;
};
struct studtype s1, s2;
printf("Student-1\n");
printf("Enter RollNo: ");
gets(s1.rno);
printf("Enter Name: ");
gets(s1.name);
printf("Enter Age and Height: ");
scanf("%d %f",&s1.age,&s1.height);
fflush(stdin); Contd...
CABSMJ-1001 [2024-25]
s1
rno name age height
printf("\nStudent-2\n");
printf("Enter RollNo: "); s2
gets(s2.rno);
printf("Enter Name: ");
gets(s2.name);
printf("Enter Age and Height: ");
scanf("%d %f",&s2.age,&s2.height);
printf("\nStudent with larger height\n");
if ( s1.height == s2.height )
printf("Both the students have same height\n");
else if ( s1.height > s2.height )
printf("%s\n%s\n%d\n%.1f\n",s1.rno,s1.name,s1.age,s1.height);
else
printf("%s\n%s\n%d\n%.1f\n",s2.rno,s2.name,s2.age,s2.height);
}
CABSMJ-1001 [2024-25]

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

Student with larger height


99CABSA101
Jameel Ahmad
21
167
CABSMJ-1001 [2024-25]

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

 An array whose elements are of type


structure is called an array of structures.

 After declaring a structure template, we can


declare an array of structures of the desired
size.

 Array of structures is generally useful when we need multiple


structure variables to store data in our program.

 For example, to store data of 50 students, we will need to


define an array of struct studtype of size 50.
rno name height CABSMJ-1001 [2024-25]
age
Array of
Structures s[0] s[1] s[2]
Array of structures

Declaring Array of Structures


Syntax: struct studtype ArrayName[size];
e.g. struct studtype s[3];

Accessing Members of the ith Structure


s[i].MemberName
e.g. to read input: gets( s[i].rno );
gets( s[i].name );
scanf("%d %f", &s[i].age, &s[i].height);
CABSMJ-1001 [2024-25]

Prob:

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


Price) of n books in an array of structures and prints the
details of the book having lowest price.
/* struct9.c */ titleauthor price CABSMJ-1001 [2024-25]
pages
#include<stdio.h>
#define N 3
b[0] b[1] b[2]
main()
Array of structures
{ struct book
{ char title[31];
char author[31];
int pages;
float price;
};
struct book b[N], mpbook; /* minimum priced book */
int i;
for (i=0; i<N; i++)
{ printf("Book-%d\n",i+1);
printf("Enter Title: ");
gets(b[i].title);
printf("Enter Author: ");
gets(b[i].author); Contd...
CABSMJ-1001 [2024-25]

printf("Enter #Pages and Price: ");


scanf("%d %f",&b[i].pages,&b[i].price);
fflush(stdin);
}
/* find minimum priced book */
mpbook = b[0];
for (i=1; i<N; i++)
{ if ( b[i].price < mpbook.price )
mpbook = b[i];
}
printf("Minimum Priced Book is\n");
printf("%s\n%s\n%d pages\nRs.%.2f\n",mpbook.title,
mpbook.author,mpbook.pages,mpbook.price);
}
CABSMJ-1001 [2024-25]
Output
Book-1
Enter Title: C Programming Language
Enter Author: Kernighan and Ritchie
Enter #Pages and Price: 288 355
Book-2
Enter Title: C: The Complete Reference
Enter Author: Herbert Schildt
Enter #Pages and Price: 832 813
Book-3
Enter Title: Programming in ANSI C
Enter Author: E Balagurusamy
Enter #Pages and Price: 581 500
Minimum Priced Book is
C Programming Language
Kernighan and Ritchie
288 pages
Rs.355.00
CABSMJ-1001 [2024-25]
dob.yr
dob.month
Nested Structure dob.day
s1
rno name height dob

 A nested structure in C is a structure within structure.

 One structure can be declared inside another structure:


 in the same way
 as structure members are declared inside a structure.

 This feature of nesting one structure within another structure


allows us to create complex data types.
CABSMJ-1001 [2024-25]
/* struct template can also be
defined inside as below: */
Example of Nested Structure
struct studtype
{ char rno[11];
struct date char name[31];
{ int day; float height;
int month; struct date
int yr; { int day;
}; int month;
struct studtype int yr;
{ char rno[11]; } dob;
char name[31]; };
float height;
dob.yr
struct date dob;
dob.month
}; dob.day
struct studtype s1; s1
rno name height dob
CABSMJ-1001 [2024-25]
dob.yr
dob.month
Nested Structure dob.day
s1
rno name height dob

Reading input in nested structure members


scanf("%d", &s1.dob.day);
scanf("%d", &s1.dob.month);
scanf("%d", &s1.dob.yr);

Outputting nested structure members


printf("%d", s1.dob.day);
printf("%d", s1.dob.month);
printf("%d", s1.dob.yr);
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads details (rno, name, height,


dob) of two students in two structure variables and finds the
student which is older than the other student based on their
date of birth.

Note: You have to use the nested structures.


CABSMJ-1001 [2024-25]
/* struct6.c Program to illustrate the use of nested structures */
#include<stdio.h>
struct date dob.day
{ int day; s1
int mon; rno name height dob
int yr;
}; dob.day
struct studtype s2
{ char rno[11]; rno name height dob
char name[41];
float height;
struct date dob;
};
typedef struct studtype student;
main()
{ student s1, s2;
printf("Student-1\n");
printf("Enter RollNo: ");
gets(s1.rno); Contd...
printf("Enter Name: "); CABSMJ-1001 [2024-25]
gets(s1.name);
printf("Enter Height: ");
scanf("%f",&s1.height);
printf("Enter dob (dd/mm/yyyy): ");
scanf("%d/%d/%d",&s1.dob.day,&s1.dob.mon,&s1.dob.yr);
fflush(stdin);
printf("\nStudent-2\n");
printf("Enter RollNo: ");
gets(s2.rno);
printf("Enter Name: ");
gets(s2.name);
printf("Enter Height: ");
scanf("%f",&s2.height);
printf("Enter dob (dd/mm/yyyy): ");
scanf("%d/%d/%d",&s2.dob.day,&s2.dob.mon,&s2.dob.yr);
printf("\nDetails of Students are:\n");
printf("%-10s %-30s %.1f %02d/%02d/%4d\n",s1.rno,s1.name,
s1.height,s1.dob.day,s1.dob.mon,s1.dob.yr);
printf("%-10s %-30s %.1f %02d/%02d/%4d\n",s2.rno,s2.name,
s2.height,s2.dob.day,s2.dob.mon,s2.dob.yr);
Contd...
CABSMJ-1001 [2024-25]

if (s1.dob.day==s2.dob.day && s1.dob.mon==s2.dob.mon &&


s1.dob.yr==s2.dob.yr)
printf("Both students have same age\n");

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

 Union is a user-defined type similar to struct, except for one key


difference:
Structure Union
a structure allocates whereas union can only hold any
enough space to store all one member’s value at a time
its members (each member (storage allocated is equal to the
has its own storage) largest storage required by a member)

 So, in union, all the members share the same storage.


 That is, union variable u1 can be used to store a char or an int
or a double, i.e. only one member’s value can be stored at one time.
CABSMJ-1001 [2024-25]
union cid 1001 1002 1003 1004 1005 1006 1007 1008
{ char c;
int i; c
double d; i (4 bytes)
d (8 bytes)
} u1;
Storage allocated: 8 bytes Memory representation of u1

 To store a double type value in u1, we can write:


u1.d = 545.5684;
Statement Output
 If we write: printf("%c",u1.c); Unpredictable value
printf("%d",u1.i); Unpredictable value

 printf("%lf",u1.d); 545.568400

Note: It is programmer’s responsibility to store and retrieve


correct information from the union.
CABSMJ-1001 [2024-25]
1001 1002 1003 1004 1005 1006 1007 1008
Example: c
i (4 bytes)
/* union1.c */ d (8 bytes)
#include<stdio.h>
main()
{ union cid
{ char c;
int i;
double d;
} u1;
u1.d = 545.5684; Output
printf("%c\n",u1.c); _
printf("%d\n",u1.i); 357341279
printf("%lf\n",u1.d);  545.568400 
}
CABSMJ-1001 [2024-25]

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

 If we solve it using only  So, such a problem is divided


main() function, we will into small independent sub-
face following problems: problems that are easier to solve.

1. Program will become too  For each sub-problem to solve,


large and complex. a function is developed.

2. It will become very  All these functions are integrated


difficult to understand, together to get the solution to
debug, modify & the original problem.
maintain the program.  Use of functions enable –
modular programming.
CABSMJ-1001 [2024-25]

Advantages of Modular Programming

 Avoids redundant programming


 Reduces length of program
 Faster program development
 Makes it easier to locate error(s) & correct them
 Easier to modify and maintain the program
 Reusability of code
CABSMJ-1001 [2024-25]

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,

2. to find sum/average/biggest/smallest of a set of


numbers,
3. to add/subtract/multiply two matrices etc.

 Functions written by programmers/users are called user-


defined functions.
CABSMJ-1001 [2024-25]

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
..........
}

 When a function is called for execution:


 control of the program is transferred to the function,
 the CPU executes the function code,
 when execution of function code is complete, program
control is transferred back to the calling function.
CABSMJ-1001 [2024-25]

Function Call and Return Statement

Syntax of function call:


functionName(argument1, argument2, ...);

 return statement returns a


float average(float x, float y, float z)
value to the calling function,
{ float sum, avg;
terminates the execution of
sum = x + y +z;
the function and transfers
avg = sum/3;
control to the calling function. return avg; Value avg is
} returned to the
 A function can return
calling function
zero/one/more values. main()
{ float a=10.5, b=12.3, c=15.4, avg;
 A function can be called any avg = average(a, b, c);
number of times by main() or ………
any other function. } Function call
CABSMJ-1001 [2024-25]

Function Arguments (or Function Parameters)


 Function arguments are the input values passed to a function when it
is called so that the function can use them while performing its task.
 For example, when avearge() function is called, values of
variables a, b and c are passed in x, y and z respectively.
Actual Arguments: float average(float x,float y,float z)
{ float sum, avg1; Formal
Arguments used in the sum = x + y +z;
function call statement. arguments
avg1 = sum/3;
Formal Arguments: return avg1;
}
Arguments used in the
main()
function’s header. { float a=10.5, b=12.3, c=15.4,
Note: Actual & formal avg;
arguments must match in their avg = average(a, b, c);
……… Actual
TYPE, NUMBER and ORDER.
} arguments
CABSMJ-1001 [2024-25]

Ways of Passing Arguments (Parameters) to a Function

 Arguments (or parameters) can be passed to a function in


TWO ways:

(i). Pass By Value

(ii). Pass By Reference


CABSMJ-1001 [2024-25]
float average(float a, float b, float c)
(i) Pass By Value { float avg = (a+b+c)/3;
return avg; /* returns one value */
}
main() average()
main()
x 10.5 a 10.5 { float x=10.5, y=20.5, z=30.5;
y 20.5 b 20.5 avg = average(x, y, z); /* function call */
z 30.5 c 30.5 ......
Actual arguments
}

 In pass by value, values of actual arguments are passed (copied)


in corresponding formal arguments.
 Function can’t change values of actual arguments. Changes
made in the formal arguments do not affect the actual
arguments.
 Function can return zero/one result through return statement.
CABSMJ-1001 [2024-25]

(i) Passing By Value


Example1: Function accepting values & returning a single value
#include<stdio.h>
int biggest(int a, int b, int c) /* accepts values */
{ int big = a;
if ( b > big ) big = b;
if ( c > big ) big = c;
return big; /* returns one value */
}
main()
{ int a=10, b=30, c=20;
int big;
big = biggest(a, b, c);
printf("%d",big);
}
CABSMJ-1001 [2024-25]

(i) Pass By Value

Example2: Function accepting values and returning no value

#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]

(i) Pass By Value

Example3: Function accepting no value and returning no value

#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

Write a C program that reads a non-negative integer n and


prints its factorial using a user-defined function factorial().
CABSMJ-1001 [2024-25]

/* 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

Write a C program that reads the values of n, r and computes


the value of Binomial coefficient using a user-defined function
factorial().

Formula: nCr = n! / ( r! * (n-r)! ) where n, r are +ve integers


and n>=r
CABSMJ-1001 [2024-25]
/* binomialcoeff.c */
nC = n! / ( r! * (n-r)! )
#include<stdio.h> r
int factorial(int n)
{ int i, fact=1;
for ( i=2; i<=n; i++ )
{ fact = fact * i;
} Output
return fact; Enter +ve int values for n and r (n>=r)
} 5 3
main() Binomial Coefficient = 10.000000
{ int n, r;
float ncr;
printf("Enter +ve int values for n and r (n>=r)\n");
scanf("%d %d",&n,&r);
ncr = (float)factorial(n)/(factorial(r)*factorial(n-r));
printf("Binomial Coefficient = %f",ncr);
}
#include<stdio.h>CABSMJ-1001 [2024-25]

Function Prototype float average(float, float, float);


main() Function prototype
(or Function Declaration)
{ float a=10.5, b=12.3, c=15.4, avg;
 A function prototype is
avg = average(a, b, c);
simply the declaration of a printf("%d", average);
function that specifies }
function's name, arguments’ float average(float x, float y, float z)
{ float sum, avg;
types and return type
sum = x + y +z;
terminated by semicolon.
avg = sum/3;
Arguments’ names may be
return avg;
omitted. }
 It provides information to the compiler that the function may
later be used in the program.
 The function prototype is needed if the function is defined
after the main() function.
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads n integers in a 1D array and finds


biggest using a user-defined function biggest().
/* biggestusingfn.c */ CABSMJ-1001 [2024-25]
#include<stdio.h>
#define N 100
int biggest(int a[ ],int size); /* or (int [], int) i.e. argument names may be*/
main() /* omitted in arg.list in function declaration */
{ int a[N], i, n;
printf("How many integers you want to input (1-%d)?\n",N);
scanf("%d",&n);
for (i=0; i<n; i++)
{ printf("Enter value-%d: ",i+1);
scanf("%d",&a[i]); Output
} How many integers you
printf("Biggest= %d\n",biggest(a,n)); want to input (1-100)?
} 5
int biggest(int a[ ],int size) Enter value-1: 75
{ int i, big=a[0]; Enter value-2: 110
for (i=1; i<size; i++) Enter value-3: 45
{ if ( a[i]>big ) Enter value-4: 80
big = a[i]; Enter value-5: 90
} Biggest= 110
return big;
}
CABSMJ-1001 [2024-25]

Prob

Write a C program that reads n integers in a 1D array and


searches a given value in the array using a user-defined
function linear_search().
/* linearsrch.c */ CABSMJ-1001 [2024-25]
#define N 10
10 70 55 30 45 60 38 57 85 95
#include<stdio.h> a[10]
int linear_search(int a[ ],int n,int x)
{ int i;
Output
for (i=0; i<=n-1; i++)
Enter 10 integer values to be stored in the
if ( a[i]==x ) return i;
array:
return -1;
10 70 55 30 45 60 38 57 85 95
}
Enter the integer value to be searched: 45
main()
Given value occurs at loc: 4 in the array
{ int a[N], i, x, loc;
printf("Enter %d integer values to be stored in the array:\n",N);
for(i=0; i<N; i++)
scanf("%d",&a[i]);
printf("Enter the integer value to be searched: ");
scanf("%d",&x);
loc = linear_search(a,N,x);
if (loc== -1)
printf("Given value - does not occur in the array\n");
else
printf("Given value occurs at loc: %d in the array",loc);
}
CABSMJ-1001 [2024-25]

Prob:
Write a C program that reads two positive integers and finds
their GCD (greatest common divisor) and LCM (lowest common
mean) using functions.

Euclid’s method to find GCD


int gcd(int x,int y)
{ int r = x % y;
x y r = x mod y
while ( r !=0 ) 20 75 20
{ x = y; 15
75 20
y = r;
r = x % y; 20 15 5
} 15 5 0
return y;
} GCD
CABSMJ-1001 [2024-25]

Finding LCM of num1 and num2

Step 1: Store the maximum num1=25, num2=40


of num1 and num2 into a max = 40
variable max. 41
42
Step 2: If max is divisible 43
by num1 and num2 both, then 44
max is the LCM. :
Step 3: If not divisible, then increment :
max by 1, and repeat step 2 until 200  LCM
max is divisible by both num1
and num2.
/* gcdlcmusingfns.c */ CABSMJ-1001 [2024-25]

#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

Write a C program that reads a string str and counts the


occurrences of a given character ch in the string using a user-
defined function countocc().
/* countoccusingfn.cpp */ CABSMJ-1001 [2024-25]
#include<stdio.h>
int countocc(char [],char); /* function prototype */
main()
{ char str[81], ch;
printf("Enter the string (Max 80 chars)\n");
gets(str);
printf("Enter the character whose occurrences to be counted\n");
scanf("%c",&ch);
printf("No. of occurrences = %d",countocc(str,ch));
}
int countocc(char s[],char ch)
{ int i=0, count=0;
Output
while ( s[i] != '\0' )
Enter the string (Max 80 chars)
{ if ( s[i] == ch)
Learning C programming is easy
count++;
i++; Enter the character whose occurrences to be counted
r
}
No. of occurrences = 3
return count;
}
CABSMJ-1001 [2024-25]

Prob

Write a C program that reads n integers in a 1D integer array


and sorts them in ascending order using a user-defined function
sort().
CABSMJ-1001 [2024-25]

Bubble Sort method

To sort an array in ascending order:


 0th element is compared with the 1st element. If they are not
in the desired order, they are interchanged.

 Then 1st element is compared with the 2nd element, if they


are not in the desired order, they are interchanged.

 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

 Similarly, in the 2nd pass, the same process is repeated on


first n-1 elements. This places the 2nd largest value in its final
position and so on.

 Thus, after making n-1 such passes, the data gets sorted.
CABSMJ-1001 [2024-25]

Bubble sort method - Example


PASS-1 PASS-2
a[6]

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

Sorting a[6] using Bubble sort


CABSMJ-1001 [2024-25]

Bubble sort method - Example


PASS-3 PASS-4 PASS-5
a[6]
Sorted
0. 20 20 20 20 20 15
1. 25 25 25 15 15 20
2. 46 15 15 25 25 25
3. 15 46 46 46 46 46
4. 58 58 58 58 58 58
5. 65 65 65 65 65 65

Sorting a[6] using Bubble sort


Note: n-1 passes are required to sort the array a[n].
CABSMJ-1001 [2024-25]

C function for Bubble sort


void bubble_sort(int a[],int n)
{ int pass, i, temp;
/* sort the elements of a[n] in ascending order */
for (pass=1; pass<=(n-1); pass++) /* perform n-1 passes */
{ for (i=0; i<=(n-1-pass); i++)
{ if ( a[i]>a[i+1] ) 1 2 3 4 5 Sorted
{ temp = a[i]; 0.
0. 46 0. 20 0. 20 0. 20 20 15
a[i] = a[i+1]; 0.
1. 20 1. 46 1. 25 1. 25 15 20
a[i+1] = temp;
} 2. 65 2. 25 n-4 46 15 25 25
} 3. 25 n-3 58 15 46 46 46
}
n-2 58 15 58 58 58 58
}
15 65 65 65 65 65
CABSMJ-1001 [2024-25]
/* sortusingfn.c */
#include<stdio.h>
#define N 100
void sort(int [],int); /* function prototype */
main()
{ int a[N], i, n;
printf("How many integers you want to input for sorting (1-%d)?\n",N);
scanf("%d",&n);
for (i=0; i<n; i++)
{ printf("Enter value-%d: ",i+1);
scanf("%d",&a[i]);
}
sort(a,n); /* sorts in ascending order */
printf("Sorted numbers\n");
for (i=0; i<n; i++)
{ printf("%d\n",a[i]);
}
} Contd...
CABSMJ-1001 [2024-25]

void sort(int a[],int n)


{ int i, pass, temp; Output
for (pass=1; pass<=n-1; pass++) How many integers you want
{ for (i=0; i<=n-1-pass; i++) to input for sorting (1-100)?
{ if ( a[i]>a[i+1] ) 5
{ temp = a[i]; Enter value-1: 110
a[i] = a[i+1]; Enter value-2: 90
a[i+1] = temp; Enter value-3: 200
} Enter value-4: 50
} Enter value-5: 150
} Sorted numbers
} 50
90
110
150
200
CABSMJ-1001 [2024-25]

Prob

Write a C program that reads n names and sorts them in


alphabetically ascending order using a user-defined function
sortnames().
CABSMJ-1001 [2024-25]
name[10][31]
0 Shamshad Ahmad\0
/* sortnamesusingfn.c */
1 Shaheen\0
#include<stdio.h>
2 Adil Ahmad Khan\0
#include<string.h>
#define N 10 : :
void sortnames(char name[][31],int n); 9 Arpit Kumar Agarwal\0
main()
{ char name[N][31], temp[31];
int i, pass;
printf("Enter %d names (each on a separate line)\n",N);
for (i=0; i<=(N-1); i++)
gets(name[i]);
sortnames(name,N);
printf("Names in ascending order\n");
for (i=0; i<=(N-1); i++)
puts(name[i]);
}
Contd...
CABSMJ-1001 [2024-25]
Output
void sortnames(char name[][31],int n) Enter 10 names (each on a
{ int i, pass; separate line)
char temp[31]; Shamshad Ahmad
for (pass=1; pass<=(n-1); pass++) Shaheen
{ for(i=0; i<=(n-1-pass); i++) Adil Ahmad Khan
Rakesh Kumar
{ if ( strcmp(name[i],name[i+1])>0 )
:
{ strcpy(temp,name[i]);
:
strcpy(name[i],name[i+1]); Names in ascending order
strcpy(name[i+1],temp); Adil Ahmad Khan
} Arpit Kumar Agarwal
} Dilshad Ahmad
} Jamal Ahmad Khan
} Mohammad Yusuf Kidwai
Mohd Shabbeer
Rakesh Kumar
Rizwan Alam
Shaheen
Shamshad Ahmad
m-1 CABSMJ-1001 [2024-25]
a[m]: 15 18 35
Prob n-1
b[n]: 10 27 50 65 90

c[p]: 10 15 18 27 35 50 65 90
p=m+n

Write a C program that reads integers (in ascending order) in


two 1D arrays a and b of size m and n respectively and merges
them in the third array of size m+n using merge() function.
Note: Both arrays a and b must contain data in ascending order.

Merging is defined as combining the sorted elements of two


similar data structures into a single sorted data structure.
CABSMJ-1001 [2024-25]

Example Merging two sorted arrays:


m-1
a[m]: 15 18 35 i=0/ 1/ 2/ 3
0 1 2
n-1
b[n]: 10 27 50 65 90 j=0/ 1/ 2
0 1 2 3 4

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

i=j=k=0; if ( i > m-1 )


{ for(rem=j; rem<=n-1; rem++)
while ( i<=m-1 && j<=n-1 )
c[k++] = b[rem];
{ if ( a[i] < b[j] ) }
c[k++] = a[i++]; else
else { for(rem=i; rem<=m-1; rem++)
c[k++] = a[rem];
c[k++] = b[j++]; }
} }
/* merge.c */ CABSMJ-1001 [2024-25]
#include<stdio.h>
#define M 6
#define N 5
#define P (M+N)
void merge(int a[],int b[],int c[],int m,int n)
{ int i, j, k, rem;
i=j=k=0;
while (i<=m-1 && j<=n-1) /* repeat until one of the arrays is exhausted */
{ if ( a[i] < b[j] )
c[k++] = a[i++];
else
c[k++] = b[j++];
}
/* copy remaining elements into array c */
if ( i > m-1 )
{ for(rem=j; rem<=n-1; rem++)
c[k++] = b[rem];
} Contd...
CABSMJ-1001 [2024-25]
else
{ for(rem=i; rem<=m-1; rem++)
c[k++] = a[rem];
}
}
main()
{ int a[M], b[N], c[P], i;
printf("Array a: Enter %d integer values in ascending order:\n",M);
for(i=0; i<M; i++)
scanf("%d",&a[i]);
printf("Array b: Enter %d integer values in ascending order:\n",N);
for(i=0; i<N; i++)
scanf("%d",&b[i]);
printf("No. of values in the array a= %d\n",M);
for(i=0; i<M; i++)
printf("%d ",a[i]);
printf("\n");
Contd...
printf("No. of values in the array b= %d\n",N); CABSMJ-1001 [2024-25]
for(i=0; i<N; i++)
printf("%d ",b[i]);
printf("\n");
merge(a,b,c,M,N);
printf("Merged array: ");
printf("No. of values in the array c= %d\n",P);
for(i=0; i<P; i++) Output
printf("%d ",c[i]); Array a: Enter 6 integer values in ascending order:
printf("\n"); 5 10 15 20 25 30
} Array b: Enter 5 integer values in ascending order:
1 2 10 21 27
No. of values in the array a= 6
5 10 15 20 25 30
No. of values in the array b= 5
1 2 10 21 27
Merged array: No. of values in the array c= 11
1 2 5 10 10 15 20 21 25 27 30
CABSMJ-1001 [2024-25]

Prob

Write a C program that reads size of the integer matrices a and


b in variables m and n. Then it:
 reads matrix-a using user-defined function readmat()
 reads matrix-b using the above readmat() function
 adds matrices a and b to get matrix c using function addmat()
and
 prints addition matrix c using function printmat().
/* mataddusingfn.c */ CABSMJ-1001 [2024-25]

#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]

void readmat(int x[][N],int m,int n)


{ int i, j;
for (i=0; i<m; i++)
{ for (j=0; j<n; j++)
scanf("%d",&x[i][j]);
}
}
void printmat(int x[][N],int m,int n)
{ int i, j;
for (i=0; i<m; i++)
{ for (j=0; j<n; j++)
{ printf("%d\t",x[i][j]);
}
printf("\n");
}
} Contd...
CABSMJ-1001 [2024-25]
void addmat(int a[][N],int b[][N],int c[][N],int m,int n)
{ int i, j;
for (i=0; i<m; i++)
{ for (j=0; j<n; j++)
c[i][j] = a[i][j] + b[i][j];
}
Output
}
Enter Size (no. of rows & cols) of matrices (Range: 1-10)
2 3
Matrix-a (size 2x3) - enter elements row-wise
1 2 3
4 5 6
Matrix-b (size 2x3) - enter elements row-wise
7 8 9
3 4 5
Matrix-c
8 10 12
7 9 11

You might also like