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

C Programming Lab Manual (2018-19) V0.2

This document is a lab manual for a C programming course. It contains 12 modules that cover various topics in C programming, including programming basics, conditional statements, looping constructs, functions, pointers, arrays, strings, structures, and file handling. Each module contains multiple program examples related to the topic. The document also lists 5 course outcomes and maps them to the relevant modules, demonstrating how completing the modules will help students achieve the learning outcomes.

Uploaded by

K P RUTHWIK
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)
143 views

C Programming Lab Manual (2018-19) V0.2

This document is a lab manual for a C programming course. It contains 12 modules that cover various topics in C programming, including programming basics, conditional statements, looping constructs, functions, pointers, arrays, strings, structures, and file handling. Each module contains multiple program examples related to the topic. The document also lists 5 course outcomes and maps them to the relevant modules, demonstrating how completing the modules will help students achieve the learning outcomes.

Uploaded by

K P RUTHWIK
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/ 47

The National Institute of Technology, Mysuru

Department of Computer Science and Engineering

C Programming Lab (E-Box) Manual V0.2


2017-18

Ramya S
Shashank S
Tojo Mathew

1
Table of Contents
Course Outcomes & CO Mapping:......................................................................................................3
Module 1. Programming Basics...........................................................................................................4
1.1 Hello World in C........................................................................................................................4
1.2 Size of all data types..................................................................................................................4
1.3 Simple and Compound Interest..................................................................................................5
1.4 Celsius to Fahrenheit Converter................................................................................................5
1.5 Area of Circle.............................................................................................................................6
1.6 Area of triangle..........................................................................................................................7
1.7 Sum of two numbers..................................................................................................................8
Module 2. Conditional Statements.......................................................................................................9
2.1 Roots of a quadratic equation....................................................................................................9
2.2 Simple Calculator....................................................................................................................10
Module 3. Looping Constructs I.........................................................................................................12
3.1 Prime........................................................................................................................................12
3.2 Prime Series.............................................................................................................................13
3.3 Star Pattern...............................................................................................................................14
3.4 Multiplication Table.................................................................................................................15
Module 4. Looping Constructs II.......................................................................................................17
4.1 GCD and LCM.........................................................................................................................17
4.2 Palindrome...............................................................................................................................18
4.3 Factorial...................................................................................................................................19
4.4 Fibonacci Numbers..................................................................................................................20
Module 5. Functions and Pointers......................................................................................................21
5.1 Swapping two numbers............................................................................................................21
5.2 Sum of array elements.............................................................................................................22
Module 6. One-D Array......................................................................................................................23
6.1 Bubble Sort..............................................................................................................................23
6.2 Binary Search...........................................................................................................................25
Module 7. Two-D Array.....................................................................................................................27
Matrix Addition..............................................................................................................................27
Module 8. Arrays & Functions...........................................................................................................30
8.1 Linear Search...........................................................................................................................31
8.2 Sorting in Descending Order...................................................................................................33
8.3 Mean, Variance & Standard Deviation....................................................................................35
8.4 Matrix Multiplication...............................................................................................................37
Module 9. Strings...............................................................................................................................40
9.1 ASTROLOGY(Without Library functions).............................................................................40
9.2 ASTROLOGY(Using library functions)..................................................................................41
Module 10. Structures........................................................................................................................43
10.1 Employee Details(Structure)..................................................................................................43
Module 11. File Handling...................................................................................................................45
11.1 File IO....................................................................................................................................45

2
Course Outcomes & CO Mapping:
On Successful completion of this course, the students will be able to

1. Demonstrate the ability to solve simple problems using C.


2. Understand the problem and apply appropriate branching statement.
3. Illustrate the usage of different decision making and looping statements.
4. Illustrate basic operations that can be performed on arrays, structures and strings.
5. Demonstrate the different categories of functions and use of pointers.

COs Contributing Modules


CO1 Module 1
CO2 Module 2
CO3 Module 3, 4
CO4 Module 6,7,9,10
CO5 Module 5,8,11

3
Module 1. Programming Basics
1.1 Hello World in C
Write a C program to print "Hello World!"
Sample Output:
Hello World!

Solution:

#include<stdio.h>
int main()
{
printf("Hello World!");
return 0;
}

1.2 Size of all data types


Write a C program to print the size of various data types in C.
Input Format:
There is no input.
Output Format:
Output should display size of all data types(refer sample input and output).

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output :


Size of int is 4
Size of float is 4
Size of double is 8
Size of char is 1

Solution:
#include<stdio.h>
int main()
{
printf("Size of int is %d\n",sizeof(int));
printf("Size of float is %d\n",sizeof(float));
printf("Size of double is %d\n",sizeof(double));
printf("Size of char is %d\n",sizeof(char));

4
return 0;
}

1.3 Simple and Compound Interest

Write a c program to find simple and compound interest.

Input format:

The first line of the input consists of float value which corresponds to the principal value.
The second line of the input consists of float value which corresponds to the rate value.
The third line of the input consists of integer value which corresponds to the period in year.

Output format:

The first line of the output consists of float value which corresponds to the simple interest.
The second line of the output consists of float value which corresponds to the compound interest.
Print the output value with two decimal places as given in the sample input and output.

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output:


1500
5
5
Simple interest is 375.00
Compound interest is 414.42

Solution:

#include<stdio.h>
#include<math.h>
int main()
{
float p,q,r,SI,CI;
int n;
scanf("%f",&p);
scanf("%f",&r);
scanf("%d",&n);
SI=((p*r*n)/100);
printf("Simple interest is %.2f\n",SI);
q = 1+(r/100);
CI=p*pow(q,n)-p;
printf("Compound interest is %.2f\n",CI);
return 0;
}

1.4 Celsius to Fahrenheit Converter

5
The relatioship between Celcius (C) and Fahrenheit (F) degrees for measuring temperature is linear.
Find an equation relating C and F if 0 C corresponds to 32 F and 100 C corresponds to 212 F.
Write a C program to simulate Celcius to Fahrenheit Converter.

Input Format:
Input consists of a single integer which corresponds to a measure of temperature in Celcius.
Output Format:
Refer Sample Input and Output for exact formatting specifications.
[All floating point values are displayed correct to 1 decimal place]

Sample Input and Output:


[All text in bold corresponds to input and the rest corresponds to output]
12
53.6F

Solution:
#include <stdio.h>

int main()
{
float celsius, F;
scanf("%f", &celsius);
F = ((celsius * 9)/5) + 32;
printf("%.1fF",F);
return 0;
}

1.5 Area of Circle


Write a program to find area of circle. (Assume pi=3.14)

Input Format:
Input consists of float value which corressponds to radius of circle.

Output Format:
Output consist of area of circle in mtsq.

Sample Input:
5.5
Sample Output:
94.98

Solution:
#include<stdio.h>

int main()

6
{
float r,area;

scanf("%f",&r);
area = 3.14*r*r;
printf("%.2f",area);

return 0;
}

1.6 Area of triangle


Write a program to find the area of a triangle when the three sides of the triangle are given.

Input Format:
Input consists of three integer variables corresponding to three sides of the triangle.

Output Format:
The output consists of the area of the triangle.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to the input and the rest corresponds to output]
Sample Input:
5
6
7

Sample Output:

14.70

Additional Sample TestCases


Sample Input and Output 1 :
3
4
5
6.00

Solution:
#include<stdio.h>
#include<math.h>

int main()
{
int a,b,c;
float s,area;
scanf("%d %d %d",&a,&b,&c);
s = (a+b+c)/2.0;

7
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("%.2f",area);
return 0;

1.7 Sum of two numbers


Write a program to find the sum of two numbers.

Input Format:
Input consists of 2 integers.

Output Format:
The output consists of an Integer indicating the sum of inputs.

Sample Input:
4
7

Sample output:
11

Additional Sample TestCases


Sample Input and Output 1 :
2
3
Sum: 5

Sample Input and Output 2 :


22
108
Sum: 130

Solution:
#include<stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("Sum: %d",a+b);
return 0;
}

8
Module 2. Conditional Statements
2.1 Roots of a quadratic equation
Write a C program to find and output all the roots of a given quadratic equation, for non-zero
coefficients. (Using if…else statement)

Input Format:
Input consists of 3 integers corresponding to the coefficients of the Quadratic equation ax^2 + bx +
c
Output Format:
The output consists of the roots of the quadratic equation.

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]

SAMPLE INPUT OUTPUT 1 :


Enter the coefficients of a, b and c :
111
-0.50+0.87i and -0.50-0.87i

SAMPLE INPUT OUTPUT 2 :


Enter the coefficients of a, b and c :
372
-0.33 and -2.00

Additional Sample TestCases


Sample Input and Output 1 :
Enter the coefficients of a, b and c :

111

-0.50+0.87i and -0.50-0.87i

Sample Input and Output 2 :


Enter the coefficients of a, b and c :

372

-0.33 and -2.00


Solution:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
float d, x1, x2, r, img, a, b, c;

9
printf("Enter the coefficients of a, b and c :\n");
scanf("%f%f%f", &a, &b, &c);
d = b*b-4*a*c;

if(a == 0){
printf("invalid");
}
else if(d == 0){
x1 = x2 = -b/(2*a);
printf("%.2f", x1);
}
else if(d>0){
x1 = (-b+sqrt(d))/(2*a);
x2 = (-b-sqrt(d))/(2*a);
printf("%.2f and %.2f", x1, x2);
}
else if(d < 0){
r = -b/(2*a);
img = (sqrt(-d))/(2*a);
printf("%.2f+%.2fi and ",r,img);
printf("%.2f-%.2fi",r,img);
}
return 0;
}

2.2 Simple Calculator

Write a C program to simulate a simple calculator that performs arithmetic operations like addition,
subtraction, multiplication, and division only on integers. Error message should be reported, if any
attempt is made to divide by zero. (Using switch statement)

Input Format:
The first input consists of an integer which corresponds to the first operand, second input consists of
an operator(+,-,*,/,%) and the third input consists of an integer which corresponds to the second
operand.
Output Format:
Refer Sample Output

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]

Sample Input 1:
10
+
5

Sample Output 1:
The sum is 15

Sample Input 2:

10
10
-
5

Sample Output 2:
The difference is 5

Sample Input 3:
10
*
5
Sample Output 3:
The product is 50

Sample Input 4:
10
/
5
Sample Output 4:
The quotient is 2

Sample Input 5:
10
/
0

Sample Output 5:
Divide by Zero error!!!

Sample Input 6:
10
%
5
Sample Output 6:
The remainder is 0

Sample Input 7:
10
=
5

Sample Output 7:
Invalid Input

Solution:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a=0,b=0;

11
char op;
scanf("%d %c %d",&a,&op,&b); // Input format: 3 + 5 (Space required)

switch(op)
{
case '+' : printf("\nThe sum is %d",a+b);
break;
case '-' : printf("\nThe difference is %d",a-b);
break;
case '*' : printf("\nThe product is %d",a*b);
break;
case '/' : if(b==0)
{
printf("\nDivide by Zero error!!!");
exit(0);
}
else
{
printf("\nThe quotient is %d",a/b);
break;
}
case '%' : printf("\nThe remainder is %d",a%b);
break;
default:printf("\nInvalid Input");
}
return 0;
}

Module 3. Looping Constructs I


3.1 Prime
Write a program to find whether a given number is prime or not.
Input Format:
Input consists of a single integer.
Output Format:
Output should display whether the input is “Prime” or “Not prime”

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]
Sample Input and Output 1:
13
Prime

Sample Input and Output 2:

12
33
Not prime
Solution:

#include<stdio.h>
#include<math.h>

int main()
{
int n, c = 2, flag = 0;

scanf("%d",&n);

// Keep dividing the given number from 2 to n/2


// and if any time remainder is zero, not prime. Otherwise prime.
for ( c = 2 ; c <=n/2 ; c++ )
{
if ( n%c == 0 )
{
flag=1;
break;
}
}

if ( flag == 0 )
printf("Prime\n");
else
printf("Not prime\n");

return 0;
}

3.2 Prime Series


Write a program to print the following series
2 3 5 7 11 13 17 19 23 29 31 37 41 ...

Input and Output Format:

Input consists of a single integer that corresponds to n.


The outputconsists of n integers in the series, separated by a space. There is a trailing space.

Sample Input:
5
Sample Output:
2 3 5 7 11

13
Solution:

// First n prime numbers for a given input n


#include<stdio.h>

int main(){
int count=0,i,flag,n,num;

scanf("%d",&n);
num=2; // First prime number
while(count<n)
{
flag = 0;
for(i=2;i<=num/2;i++)
{

if(num%i==0)
{
flag=1;
break; // exit inner loop
}
}

if(flag==0)
{
printf("%d ",num);
count++;
}
num++;
}
return 0;
}

3.3 Star Pattern


Write a program to help Patrick to print the pattern given pattern using while loop?

Input and Output Format:


Input consists of single integer, n which corresponds to number of rows.

[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output1:


5
*
**
***
****
*****

14
Sample Input and Output 2:
3
*
**
***

Solution:
#include <stdio.h>
int main()
{
int i, j, rows;
scanf("%d",&rows);
i=1;
while(i<=rows)
{
for(j=1; j<=i; ++j)
{
printf("*");
}
printf("\n");
i++;
}
return 0;
}

3.4 Multiplication Table


Write a program to print Multiplication tables till 10 for given range "N" starting from 1 (Using
Nested for loop statement).

Input Format:
Input consists of an integer (0<N<20).

Output Format :
The output consists of tables from 1 to N as shown in sample input-output format.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to the input and the rest corresponds to output]

Sample Input :
5

Sample Output:
12345
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

15
6 12 18 24 30
7 14 21 28 35
8 16 24 32 40
9 18 27 36 45
10 20 30 40 50

Solution:

#include <stdio.h>

int main()
{
int i , j;
int n,num;

scanf("%d",&n);
for(i=1; i<=10; i++)
{
num= i;
for(j=1; j<=n; j++)
{
printf("%d ",(num*j));
}
printf("\n");
}
return 0;
}

16
Module 4. Looping Constructs II
4.1 GCD and LCM
Write a C program to find the GCD and LCM of two integers and output the results along with the given integers.
Use Euclid’s algorithm. (Using looping constructs)

Input Format:
The first and the second input are two integers.
Output Format:
Output consists of GCD and LCM of the 2 input numbers.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output:


Enter two numbers
50
25
GCD = 25 and LCM = 50 of 50 and 25

Solution:
#include <stdio.h>

int main() {
int a, b, x, y, rem=0, gcd, lcm;
printf("Enter two numbers\n");
scanf("%d%d", &x, &y);
a = x;
b = y;

/*
If b > a,after first iteration a & b
exchanges values after first iteration.
*/

while (b != 0) {
rem = a % b;
a=b;
b = rem;
}
gcd = a;
lcm = (x*y)/gcd;

printf("GCD = %d and LCM = %d of %d and %d\n", gcd,lcm,x, y);


return 0;
}

17
4.2 Palindrome
Write a C program to reverse a given integer number and check whether it is a palindrome or not. Output the
given number with suitable message. (Using While statement)

Input Format:
The first input consists of an integer.
Output Format:
Output consists of a statement in which we print whether the input is palindrome or not.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output 1:


Enter an integer :
15651
15651 is a palindrome.

Sample Input and Output 2:


Enter an integer :
100
100 is not a palindrome.

Solution:
#include <stdio.h>

int main()
{
long int num, n, reverse = 0;

printf("Enter an integer :\n");


scanf("%ld", &num);
n = num;

while (n != 0)
{
reverse = reverse * 10; // Shifting the digit left by one poistion.
reverse = reverse + n%10; // extracting & appending right most digit of n to reverse.
n = n/10; // Discardng the right most digit of n.
}

if(num == reverse)
{
printf("%ld is a palindrome.",num);
}
else
{
printf("%ld is not a palindrome.",num);
}

return 0;

18
}

4.3 Factorial
Write a program to find the factorial of a given number(Using While loop).
Input Format:
Input consists of a single integer, n.
Output Format:
The output consists of a single integer which corresponds to n!
Sample Input :
4
Sample Output :
24

Additional Sample TestCases


Sample Input and Output 1 :
5

120

Solution:
#include<stdio.h>

int main()
{
int n, temp;

long int fact = 1;

scanf("%d",&n);
temp = 1;

while(temp<=n)
{
fact = fact*temp;
temp++;
}

printf("%ld",fact);

return 0;
}

19
4.4 Fibonacci Numbers
Write a C program to generate and print first ‘N’ Fibonacci numbers. (Using do-While statement)
Input Format:
The first input consists of an integer.
Output Format:
Output consists of series of n fibinacci numbers.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output 1:


Enter an integer :
7
0112358

Sample Input and Output 2:


Enter an integer :
5
01123

Solution:
/* Fibonacci Series C language */
#include<stdio.h>

int main()
{
int n, prev = 0, current = 1, next, count;

printf("Enter an integer :\n");


scanf("%d",&n);

count = 0;
do
{

if ( count <= 1 )
{
printf("%d ",count); // For 0 & 1
}
else
{
next = prev + current; // Next value
printf("%d ",next);
prev = current; // Update previous value
current = next; // Update current value
}
count++;
}
while(count<n);

20
return 0;
}

Module 5. Functions and Pointers


5.1 Swapping two numbers

Mrs. Anitha , our favourite Maths teacher wanted to teach her students to swap
two elements.
Write a program to accept 2 integers and to swap them using functions and
pointers.

Function Specification:
void swap(int *a,int *b)
This functions swaps 2 integers.

Input Format:
The input consists of 2 integer.

Output Format:
Refer to the sample input and output for formatting details.
[All text in bold corresponds to input and the rest corresponds to
output.]

Sample Input and Output:


Enter the value of a
5
Enter the value of b
3
Before swapping
a=5b=3
After swapping
a=3b=5

Function Definitions:

voidswap(int *, int *)

Solution:

21
#include<stdio.h>

void swap(int *p,int *q);

int main()
{
int a,b;

printf("Enter the value of a\n");


scanf("%d",&a);

printf("Enter the value of b\n");


scanf("%d",&b);

printf("Before swapping\n");
printf("a = %d b = %d\n",a,b);

swap(&a,&b);

printf("After swapping\n");
printf("a = %d b = %d\n",a,b);

return 0;
}

void swap(int *p,int *q)


{
int temp;
temp = *p;
*p = *q;
*q = temp;
}

5.2 Sum of array elements


Write a program to fnd the sum of the elements in an arra..

Function Specification:
int sum(int *arr,int n)
This functionadds all the elements in an arra.. And returns the added Sum.

Input Format:
Input consists of n+1 integers. The frst integer corresponds to ‘n’,the size of
the arra.. The next ‘n’ integers correspond to the elements in the arra..
Assume that the maximum value of n is 15.
Output Format:
Refer sampleoutput for better understanding.
Sample Input 1:
5

22
2
3
6
8
1
Sample Output 1:
The sum of the elements in the arra. is 20

Solution:

#include<stdio.h>
int sum(int *arr,int n);
int main()
{
int i,n,s;
int a[20];
scanf("%d",&n);

for(i=0;i<n;i++)
scanf("%d",&a[i]);
s = sum(a,n);

printf("The sum of the elements in the array is %d\n",s);


return 0;

int sum(int *arr,int n)


{
int i,sum = 0;

for(i=0;i<n;i++)
sum += arr[i];

return sum;

Module 6. One-D Array


6.1 Bubble Sort
Write a C program to input N integer numbers into a single dimension arra.. Sort them in
ascending order using bubble sort technique. Print both the given arra. and the sorted
arra. with suitable headings.

Input Format:
The frst input consists of an integer which corresponds to the number of elements present
in the single dimension arra..

23
The next n inputs are the elements in the arra..

Output Format:
First line output consists of arra. elements before sorting and the next line of the
outputconsists of arra. elements after sorting.

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output:

Enter the number elements in the arra. :


5
Enter the elements of the arra. :
9
6
7
4
5
Before sorting the arra. :
96745
After sorting the arra. :
45679

Solution:
#include<stdio.h>
int main()
{

int array[100],n,i,j,temp;

printf("Enter the number elements in the array\n");


scanf("%d",&n);

printf("Enter the elements of the array\n");


for(i=0;i<n;i++)
scanf("%d",&array[i]);

printf("Before sorting the array\n");


for(i=0;i<n;i++)
printf("%d ",array[i]);

for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(array[j]>array[j+1])

24
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}

printf("\nAfter sorting the array\n");


for (i=0;i<n;i++)
printf("%d ",array[i]);

return 0;
}

6.2 Binary Search


Write a C program to input N real numbers in ascending order into a single dimension
arra.. Conduct a binar. search for a given ke. integer number and report success or failure
in the form of a suitable message.

Input Format:
The frst input consists of an integer which corresponds to the number of elements present
in the single dimension arra..
The next n inputs are the elements in the arra..
The next inputconsists of an integer which corresponds to the ke. element to be searched.
Output Format:
Output should displa. whether the ke. is present in the arra. or not.

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output 1:


Enter the number of elements :
5
Enter the elements :
6
3
1
7
1
Enter the ke. to be searched :
1
The ke. is present in the arra.
Atindex2

Sample Input and Output 2:

25
Enter the number of elements :
5
Enter the elements :
6
2
3
7
1
Enter the ke. to be searched :
2
The ke. is not present in the arra.

Additional Sample TestCases


Sample Input and Output 1 :

Sample Input and Output 2 :

Enter the number of elements :


6
Enter the elements :
2
4
5
6
8
9
Enter the key to be searched :
1
The key is not present in the array

Solution:

#include<stdio.h>
int main()
{

int a[20],n,i,key,low,high,mid;
printf("Enter the number of elements\n");
scanf("%d",&n);

printf("Enter the elements\n");


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

printf("Enter the key to be searched\n");


scanf("%d",&key);

26
low=0;
high=n-1;

while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==key)
{
printf("The key is present in the array\n");
printf("At index %d\n",mid);
goto label1;
}
if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}
printf("The key is not present in the array\n");
label1: return 0;
}

Module 7. Two-D Array


Matrix Addition
Write a C program to read two matrices A(M x N) and B(P x Q) and perform addition.
Output the input matrices and the resultant matrix with suitable headings and format.
(Using two dimension arra.s where arra. size M, N, P,Q ≤ 4)
Input Format:

The frst input consists of an integer which corresponds to the number of elements present
in the two dimension arra..
The next n inputs are the elements of the frst matrix and then followed b.elements of the
second matrix.

Output Format:
The output consist of the frst matrix and then the second matrix and then the resultant
matrix which corresponds to the addition of two matrix.
Print "Matrix addition is not possible" if the size(order) of two matrixis not same.

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output:

Enter the size of frst matrix :


2
2
First matrix :

27
8
9
6
3
Enter the size of Second matrix :
2
2
Second matrix :
1
4
5
6
First input matrix :
89
63
Second input matrix :
14
56
Resultant matrix :
9 13
11 9

Additional Sample TestCases


Sample Input and Output 1 :
Enter the size of First matrix :
2
3
First matrix :
1
2
3
4
5
6
Enter the size of Second matrix :
3
2
Second matrix :
1
2
3
4
5
6
Matrix Addition not possible

28
Sample Input and Output 2 :
Enter the size of First matrix :
2
2
First matrix :
8
9
6
3
Enter the size of Second matrix :
2
2
1
Second matrix :
4
5
6
First input matrix :
89
63
Second input matrix :
14
56
Resultant matrix :
9 13
11 9

Solution:

//Program to add two matrices


#include<stdio.h>
int main()
{
int i,j,m,n,p,q,a[10][10],b[10][10],c[10][10];
printf("Enter the size of First matrix :\n");
scanf("%d%d",&m,&n);

printf("First matrix :\n");


for ( i = 0 ; i < m ; i++ )
for ( j = 0 ; j < n ; j++ )
{
scanf("%d", &a[i][j]);
}

printf("Enter the size of Second matrix :\n");


scanf("%d%d",&p,&q);

printf("Second matrix :\n");


for ( i = 0 ; i < m ; i++ )
for ( j = 0 ; j < n ; j++ )
scanf("%d", &b[i][j]);

29
if(m!=p||n!=q)
{
printf("Matrix addition not possible");
return 0;
}

printf("First input matrix :\n");


for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
printf("%d ", a[i][j]);
}
printf("\n");
}

printf("Second input matrix :\n");


for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
printf("%d ", b[i][j]);
}
printf("\n");
}

// Adding the two matrices & storing in matrix c


for ( i = 0 ; i < m ; i++ )
for ( j = 0 ; j < n ; j++ )
c[i][j]=a[i][j]+b[i][j];

printf("Resultant matrix :\n");


for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
printf("%d ", c[i][j]);
}
printf("\n");
}

return 0;
}

Module 8. Arrays & Functions

30
8.1 Linear Search
Write C program for user-defned functions:
1. To input N integer numbers into a single dimension arra..
2. To conduct a linear search.
Using these functions, write a C program to accept the N integer numbers & given ke.
integer number and conduct a linear search. Report success or failure in the form of a
suitable message.

Function Specification:
void search(int a[ ],int b,int n)
This function will search whether the element 'b' is present in anarray "a" of size n. Andprint "The ke.
is present in the arra.."if foundelseprint"The ke. is not present in the arra..".
Input Format:
The first input consists of an integer which corresponds to the number of elements present in the single
dimension array.
The next n inputs are the elements in the array.
The next input consistsof an integer which corresponds to the ke. element to be searched.

Output Format:
The output should displa. whetherthe ke. is present in the arra. or not.

Refer sample input and output for formatting specifications.


[All text in bold corresponds to the input and the rest corresponds to output]

Sample Input and Output 1:


Enter the number of elements :
5
Enter the elements :
6
3
1
7
1
Enter the ke. to be searched :
3
The ke. is present in the arra..
At index 1

Sample Input and Output 2:


Enter the number of elements :
5
Enter the elements :
6
3
1
7
1
Enter the ke. to be searched :
2
The ke. is not present in the arra..

31
Additional Sample TestCases
Sample Input and Output 1 :
Enter the number of elements :
7
Enter the elements :
3
6
2
4
12
25
64
Enter the key to be searched :
25
The key is present in the array.
At index 5
Sample Input and Output 2 :
Enter the number of elements :
5
Enter the elements :
2
4
6
8
10
Enter the key to be searched :
9
The key is not present in the array.

Solution:

#include<stdio.h>
#include<stdlib.h>
int i,n;
void linear(int a[10],int key);
void input(int a[10]);
int main()
{
int a[10],key;
printf("Enter the number of elements :\n");
scanf("%d",&n);
input(a);
printf("Enter the key to be searched :\n");
scanf("%d",&key);
linear(a,key);
return 0;
}
void input(int a[10])

32
{
printf("Enter the elements :\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}

void linear(int a[10],int key)


{
int index = -1;
for(i=0;i<n;i++)
{
if(a[i]==key)
{
index = i;
//printf("Found at position:%d\n",i+1);
}
}
if(index == -1)
printf("The key is not present in the array.\n");
else
printf("The key is present in the array.\nAt index %d",index);
}

8.2 Sorting in Descending Order


Write C program for user defned functions:
To input N integer numbers into a single dimension arra..
To sort the integer numbers in descending order using selection sort technique.
To print the single dimension arra. elements.
Using these functions, write a C program to input N integer numbers into a single
dimension arra., sort them in descending order, and print both the given arra. & the
sorted arra. with suitable headings.

Input Format:
The frst input consists of an integer which corresponds to the number of elements present
in the single dimension arra..
The next n inputs are the elements in the arra..

Output Format:
First line output consists of arra. elements before sorting and the next line of the output
consists of arra. elements after sorting the elements in descending order.

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output:


Enter the number elements in the arra. :
5
Enter the elements of the arra. :
9
6
5

33
8
3
Before sorting the arra. :
96583
After sorting the arra. :
98653

Solution:

//Program to sort using selection sort technique


#include <stdio.h>

void selection(int a[],int size);


void input(int a[],int size);
void display(int a[],int size);

int main()
{
int n;
int a[10];

printf("Enter the number elements in the array :\n");


scanf("%d",&n);

input(a,n);

printf("Before sorting the array :\n");


display(a,n);

selection(a,n); //calling selection sort function

printf("\nAfter sorting the array :\n");


display(a,n);

return 0;

void input(int a[],int size)


{
int i;
printf("Enter the elements of the array :\n");
for ( i = 0 ; i < size ; i++ )
scanf("%d", &a[i]);
}

void display(int a[],int size)


{
int i;
for ( i = 0 ; i <size; i++ )
printf("%d ", a[i]);

34
}

// Descending order sort


void selection(int a[],int n)
{
int pos,temp;
int i,j;
for ( i = 0 ; i < ( n - 1 ) ; i++ )
{
pos = i;
for ( j = i + 1 ; j < n ; j++ )
{
if ( a[pos] < a[j] )
pos = j;
}

if ( pos != i )
{
temp = a[i];
a[i] = a[pos];
a[pos] = temp;
}
}
}

8.3 Mean, Variance & Standard Deviation


Write C program for user defned functions:
To input N real numbers into a single dimension arra..
Compute their mean.
Compute their variance
Compute their standard deviation.
Using these functions, write a C program to input N real numbers into a single
dimension arra., and compute their mean, variance & standard deviation.
Output the computed results with suitable headings.

Input Format:
The frst input consists of an integer which corresponds to the number of
elements present in the single dimension arra..
The next n inputs are the elements in the arra..

Output Format:
First line output consists of 3 foat values which corresponds to the mean,
variance & standard deviation values.

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and the rest corresponds to
output]

35
Sample Input and Output:
Enter the number of elements in the arra.
5
Enter the elements in the arra.
6
8
9
1
4
The Mean = 5.60, Variance = 8.24 and Standard deviation = 2.87

Solution:

// Find mean,varianace and standard deviation using functions


#include<stdio.h>
#include<math.h>

void input(int n, int a[]);


float mean(int n, int a[]);
float variance(int n, int a[]);
float sd (int n, int a[]);

int main()
{
float m,s,v;
int n;
int a[10];
printf("Enter the number of elements in the array\n");
scanf("%d",&n);
input(n,a);
m = mean(n,a);

s =sd(n,a);

v= variance(n,a);
printf("The Mean = %.2f, Variance = %.2f and Standard deviation = %.2f",m,v,s);

return 0;
}
void input(int n, int a[])
{
int i;
printf("Enter the elements in the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}

float sd(int n, int a[])


{

36
float std=sqrt(variance(n, a));
return std;
}

float variance(int n, int a[])


{
float m,v,sum;
int i;
m=mean(n,a);
sum=0;

for(i=0;i<n;i++)
sum=sum + pow(a[i]-m,2);

v=sum/n;
return v;
}

float mean(int n, int a[])


{
int sum,i;
float m;
sum=0;
for(i=0;i<n;i++)
{
sum=sum+a[i];
}

m=(float)sum/n;
return m;
}

8.4 Matrix Multiplication


Write a ‘C’ Program to fnd the product of two matrices.

Input andOutput Format :

Refer Sample Input and Output for further details.

Sample Input and Output 1 :

[ All text of bold corresponds to Input and the rest output]

Enter the size of the First matrix :


2

37
2
Enter the size of the Second matrix :
2
2
Enter the elements of First matrix
1
2
3
4
Enter the elements of Second matrix
5
6
7
8
The Matrix after Multiplication is
19 22
43 50

Solution:

//Matrix Multiplication using functions


#include<stdio.h>

void mul();
void input(int x[10][10],int m,int n);
void display(int x[10][10], int m,int n);

// Global 2-D arrays & variables


int a[10][10], b[10][10],c[10][10],m,n,p,q;

int main()
{

printf("Enter the size of the First matrix :\n");


scanf("%d%d",&m,&n);

printf("Enter the size of the Second matrix :\n");


scanf("%d%d",&p,&q);

if(n!=p)
{
printf("Incompatible Array size\n");
return -1;
}
else

38
{

printf("Enter the elements of First matrix\n");


input(a,m,n);

printf("Enter the elements of Second matrix\n");


input(b,p,q);

mul();

printf("The Matrix after Multiplication is\n");


display(c,m,q);
}

return 0;
}

void mul()
{
int i,j,k;

for (i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]= c[i][j]+ a[i][k]*b[k][j];
}
}
}

void input(int x[10][10], 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 display(int x[10][10], int m,int n)


{
int i,j;
for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ", x[i][j]);
printf("\n");
}

39
printf("\n");
}

Module 9. Strings

9.1 ASTROLOGY(Without Library functions)


Whole India is tweeting about the probable names for Aishwar.a Rai's daughter. Some
astrologers are suggesting that she will grow up to be a more famous celebrit. than
Aishwar.a if her name is a palindrome. As we all know, a palindrome is a word that can be
read the same wa. in either direction.

Write a C program to determine whether a given word is a palindrome or not. Do not use
an. string librar. functions.

Input Format:
Input consists of a single string. Assume that the maximum length of the string is 50.

Output Format:
Refer sample input and output for formatting specifcations.

Sample Input and Output 1:


[All text in bold corresponds to input and the rest corresponds to output.]

Enter the word


hannah
hannah is a palindrome

Sample Input and Output 2:


[All text in bold corresponds to input and the rest corresponds to output.]

Enter the word


bina
bina is not a palindrome

Solution:
// Check for string palindrome without using built-in functions
#include <stdio.h>
#include <string.h>

int checkpalindrom(char string[]);

int main(){
char str[20];

40
int flag = 0;

printf("Enter the word\n");


scanf("%s", str);

flag = checkpalindrom(str);
if (flag) {
printf("%s is not a palindrome", str);
}
else {
printf("%s is a palindrome", str);
}
return 0;
}

int checkpalindrom(char string[])


{
int i, length=0;
int flag = 0;

// Finding length of string without library function


while(string[length]!='\0')
{
length++;
}
// printf("String length= %d\n",length);
for(i=0;i < length ;i++){

if(string[i] != string[length-i-1])
{
flag = 1;
break;
}
}

return flag;
}

9.2 ASTROLOGY(Using library functions)


Whole India is tweeting about the probable names for Aishwar.a Rai's daughter. Some
astrologers are suggesting that she will grow up to be a more famous celebrit. than
Aishwar.a if her name is a palindrome. As we all know, a palindrome is a word that can be
read the same wa. in either direction.

Write a C program to determine whether a given word is a palindrome or not. Use String
built-in function.

Input Format:
Input consists of a single string. Assume that the maximum length of the string is 50.

41
Output Format:
Refer sample input and output for formatting specifcations.

Sample Input and Output 1:


[All text in bold corresponds to the input and the rest corresponds to output.]

Enter the word


hannah
hannah is a palindrome

Sample Input and Output 2:


[All text in bold corresponds to input and the rest corresponds to output.]

Enter the word


bina
bina is not a palindrome

Solution:
// Check for string palindrome using built-in functions
#include <stdio.h>
#include <string.h>

int checkpalindrom(char string[]);


void strrev(char str[])
{
int len,i;
char temp;
len = strlen(str);
//printf("Original: %s",str);

for(i = 0;i<len/2;i++)
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}

//printf("Reversed: %s",str);

int main(){

char str[20];
int flag = 0;

printf("Enter the word\n");


scanf("%s",str);

42
flag = checkpalindrom(str);
if (flag ==1) {
printf("%s is a palindrome\n", str);
}
else {
printf("%s is not a palindrome\n", str);
}
return 0;
}

int checkpalindrom(char string[])


{

char str[20];
int flag = 0;

strcpy(str,string); // create a copy of input string


strrev(str); // reverse string

//printf("Reversed string is: %s\n",str);

if(strcmp(string,str) == 0)
flag = 1;

return flag;
}

Module 10. Structures


10.1 Employee Details(Structure)
Write a C program to create a structure called Emplo.ee with members Name, Job, Salar..
Create a structure variable. Accept the input values for the structure members at run time.
Suitabl. displa. the same.

Input Format:
The frst input is an integer which corresponds to the number of emplo.ees.
Secondinput is a charecter arra. which corresponds to the name of the emplo.ee.
Third input is a charecter arra. which corresponds to the job of the emplo.ee.
Fourth input is a foat which corresponds to the salar. of the emplo.ee.

Output Format
Output should displa. the emplo.ee details which is given in the sample input and output
format.

Refer sample input and output for formatting specifications.

43
[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output:


Enter the number of Emplo.ees :
3
Enter the details of Emplo.ee :1
Enter the Name :
Bala
Enter the Job :
SoftwareEngineer
Enter the Salar. :
30000
Enter the details of Emplo.ee :2
Enter the Name :
Jenifer
Enter the Job :
Teacher
Enter the Salar. :
10000
Enter the details of Emplo.ee :3
Enter the Name :
Kavin
Enter the Job :
Police
Enter the Salar. :
25000
Details of Emplo.ee :1
Name :Bala
Job :SoftwareEngineer
Salar. :30000.00
Details of Emplo.ee :2
Name :Jenifer
Job :Teacher
Salar. :10000.00
Details of Emplo.ee :3
Name :Kavin
Job :Police
Salar. :25000.00

Solution:

#include<stdio.h>
#include<string.h>

int main()
{

44
struct employee
{
char name[20];
char job[20];
float salary;
};
struct employee e[10];
int i,n;
printf("Enter the number of Employees :\n");
scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("Enter the details of Employee :%d\n",i+1);

printf("Enter the Name :\n");


scanf("%s",e[i].name);
printf("Enter the Job :\n");
scanf("%s",e[i].job);
printf("Enter the Salary :\n");
scanf("%f",&e[i].salary);
}
for(i=0;i<n;i++)
{
printf("Details of Employee :%d\n",i+1);
printf("Name :%s\n",e[i].name);
printf("Job :%s\n",e[i].job);
printf("Salary :%.2f\n",e[i].salary);
}
return 0;
}

Module 11. File Handling


11.1 File IO
Write a C program to record the student details into the fle. Get the student detailsNAME,
USN, BRANCH,SEMESTERfrom the user and write those information in a fle called
student.rec
Below is the format of the output fle.
Name : aarshad
USN : 12345
Branch : IT
Semester : 54321
Input and Output Format:

45
Get the student detailsNAME, USN, BRANCH,SEMESTERfrom the user
[All text in bold corresponds to input and the rest corresponds to output]

Sample Input and Output :


Enter name:
aarshad
Enter USN:
12345
Enter branch:
IT
Enter sementer:
54321

Solution:

#include <stdio.h>
int main()
{
int num,sem;
char name[100];
char branch[100];

FILE *fptr;
fptr = fopen("student.rec","w");

if(fptr == NULL)
{
printf("Error!");
return 0;
}

printf("Enter name:\n");
scanf("%s",name);
fprintf(fptr,"Name : ");
fprintf(fptr,"%s\n",name);

printf("Enter USN:\n");
scanf("%d",&num);
fprintf(fptr,"USN : ");
fprintf(fptr,"%d\n",num);

printf("Enter branch:\n");
scanf("%s",branch);
fprintf(fptr,"Branch : ");
fprintf(fptr,"%s\n",branch);

printf("Enter sementer:\n");
scanf("%d",&sem);

46
fprintf(fptr,"Semester : ");
fprintf(fptr,"%d\n",sem);

fclose(fptr);

return 0;
}

47

You might also like