0% found this document useful (0 votes)
42 views37 pages

Programs

The document contains examples of C programs to perform various operations like arithmetic operations on two numbers, finding volume of a sphere, area of a triangle, rotating values of variables, checking if a number is positive/negative, odd/even, largest of three numbers, increment/decrement operators, bitwise operators, checking if a number is even/odd with and without else, checking if a number is positive/negative/zero with nested if. The programs demonstrate basic concepts in C programming like input/output, conditional statements, operators etc.

Uploaded by

Akhila A
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)
42 views37 pages

Programs

The document contains examples of C programs to perform various operations like arithmetic operations on two numbers, finding volume of a sphere, area of a triangle, rotating values of variables, checking if a number is positive/negative, odd/even, largest of three numbers, increment/decrement operators, bitwise operators, checking if a number is even/odd with and without else, checking if a number is positive/negative/zero with nested if. The programs demonstrate basic concepts in C programming like input/output, conditional statements, operators etc.

Uploaded by

Akhila A
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/ 37

Session No.

1
(i) To accept two numbers and perform basic arithmetic operations (+, - *, /, %)

START
1. PROMPT the user to enter first number
2. READ the first number, a
3. PROMPT the user to enter second number
4. READ the second number, b
5. COMPUTE for the sum, sum = a + b
6. COMPUTE for the product, product = a * b
7. COMPUTE for the difference, diff = a – b
8. COMPUTE for the quotient, quotient = a / b
9. COMPUTE for the remainder, remainder = a % b
10. WRITE the sum, product, difference, quotient and remainder of the two
numbers, sum, product, diff, quotient, remainder
END
#include<stdio.h>
int main()
{
float a,b,add,dif,product,quotient;
int rem;
printf("enter two numbers\n");
scanf("%f%f",&a,&b);
add=a+b;
dif=a-b;

product=a*b;
quotient=a/b;
rem=(int)a%(int)b;
printf("sum of two numbers=%f\n",add);
printf("diffrence between two numbers=%f\n",dif);
printf("product of two numbers=%f\n",product);

printf("quotient of two numbers=%f\n",quotient);


printf("the remainder of two numbers=%d",rem);
return 0;
}

(ii) To find the volume of a Sphere using the formula, Volume = 4 / 3 Π r 3


START
1. INITIALIZE Pi, Pi = 3.
2. PROMPT the user to enter the radius of the sphere
3. READ the radius of the sphere, r
4. COMPUTE for the volume of the sphere, V = (4 .0/3) * Pi * r 3
5. WRITE the volume of the sphere, V
END
#include <stdio.h>
int main() {
float r;
float V;
const float Pi = 3.14159;
printf("Enter the radius of the sphere: ");
scanf("%f", &r);
V = (4.0/3.0) * Pi * (r * r * r);
printf("\nThe volume of the sphere is %.2f", V);
return 0;
}

(iii) To find the area of a Triangle with 3 sides given using formula, Area = √(s(s-a) (s-b) (s-c)) where a, b and c
are lengths of sides of Triangle, and s = (a+b+c) / 2

Start
Step-1: Input three arms of a triangle in variable a, b and c.
Step-2: Calculate s = (a+b+c)/2.
Step-3: Calculate area = √(s(s-a)(s-b)(s-c)).
Step-4: Print value of area.
Stop.
Session No.2

(i) Given the values of the variables x, y and z, write a program to rotate
their values such that x has the value of y, y has the value of z, and z has
the value of x.

Start
Step 1 : Read two numbers X Y and Z;
STEP 2: T = X
STEP 3: X = Y
STEP 4: Y = Z
STEP 5: Z=T;
STEP 6: PRINT X, Y ,Z
End
#include<stdio.h>
int main( )
{
int x,y,z,temp;
printf("enter three numbers\n");
scanf("%d%d%d",&x,&y,&z);
printf("before interchange the value of x=%d\t y=%d\t z=%d\n",x,y,z);
temp=x;
x=y;
y=z;
z=temp;
printf("after interchange the value of x=%d\t y=%d\t z=%d\n",x,y,z);
return 0;
}
(ii) To read floating-pointing number and then displays the right-most digit
of the integral part of the number.

Step 1: Read x where x is float type.


Step 2: Compute y=x where y is integer type.
Step 3: compute y %10 and store the result in z.
Step 4: Display z.
#include<stdio.h>
int main()

{
float x;
int y,z;
printf("enter the floating point number\n");
scanf("%f",&x);
y=(int)x;

z=y%10;
printf("the right most digit of integral part=%d",z);
return 0;
}
(iii) To read floating-pointing number, separate and displays the integral and
decimal part of the given.

Step 1: Read x where x is float type.


Step 2: Compute y=x where y is integer type.
Step 3: compute y %100 and store the result in z.
Step 4: Display z.

#include<stdio.h>
int main()
{
float x,z;
int y;
printf("enter the floating point number\n");
scanf("%f",&x);
y=(int)x;
z=x-y;
printf("the integral part of the number=%d",y);
printf("the decimal part of the number=%f",z);
return 0;
}
(iv) To print the size of various data types in “C” programming language
using “sizeof” operator

START

Step 1: Display the size of integer datatype using sizeof(int) function.

Step 2: Display the size of character datatype using sizeof(char) function.

Step 3: Display the size of float datatype using sizeof(float) function.

Step 4: Display the size of double datatype using sizeof(double) function.

END

include <stdio.h>
int main() {
int a = 16;
printf("Size of variable a : %d\n",sizeof(a));
printf("Size of int data type : %d\n",sizeof(int));
printf("Size of char data type : %d\n",sizeof(char));
printf("Size of float data type : %d\n",sizeof(float));
printf("Size of double data type : %d\n",sizeof(double));
return 0;
}
Session No.3

(i) Using ‘ternary’ operator, check whether a given number is Positive or


Negative.
#include<stdio.h>
int main()
{
float n;

printf("enter the number\n");


scanf("%f",&n);
(n>0)?printf("%f is positive number",n):printf("%f is negative number",n);
return 0;
}

(ii) Using ‘ternary’ operator, to check whether a given Year is a Leap Year or
Not.
#include<stdio.h>

int main()

int year;

printf("enter the year\n");

scanf("%d",&year);

(year % 100 == 0) ?

((year % 400 == 0)?

(printf("%d is leap year\n",year)):

(printf("%d is not leap year\n",year))

):

( (year % 4 == 0)?

(printf("%d is leap year\n",year)):

(printf("%d is not leap year\n",year))

);

return 0;

}
(iii) Using ‘ternary’ operator, find the largest of three numbers.

#include<stdio.h>
int main()
{
int year;
int a, b, c, big ;

printf("Enter three numbers : ") ;

scanf("%d %d %d", &a, &b, &c) ;

big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;

printf("\nThe biggest number is : %d", big) ;

return 0;
}

(iv) Using ‘&’ operator, check whether a given number is Odd or Even.
#include<stdio.h>

int main()
{
int n;
printf("enter the number\n");
scanf("%d",&n);

(n&1==1)?printf("%d is odd",n):printf("%d is even",n);


return 0;
}
Session No.4

(i) To illustrate the use of increment operator (postfix & prefix).


#include<stdio.h>
int main()

{
int a,b,c;
printf("enter the value of a");
scanf("%d",&a);
b=++a;
printf("the value of a after preincrement is %d\n",a);

printf("the value of b=%d\n",b);


c=a++;
printf("the value of a after postincrement is %d\n",a);
printf("the value of c=%d\n",c);
return 0;

(ii) To illustrate the use of decrement operator (postfix & prefix).

#include<stdio.h>
int main()

{
int a,b,c;
b=--a;
printf("the value of a after predecremet is %d\n",b);
printf("the value of d=%d\n",b);
c=a--;
printf("the value of a after postdecrement is %d\n",c);
printf("the value of e=%d\n",c);
return 0;
}
(iii) To perform the following using bitwise operators:

c=a&b; d=a|b; e = ~a

f = a >> n; g = a << n; h=a^b

#include<stdio.h>

int main()
{
int a,b,c,d,e,f,g,h,n;
printf("enter the value of a and b");
scanf("%d%d",&a,&b);
c=a&b;

printf("the result of a&b is %d\n",c);


d=a|b;
printf("the result of a|b is %d\n",d);
e=~a;
printf("the result of ~a is %d\n",e);
printf("enter the value of n to move the number of bits to left or right");

scanf("%d",&n);
f=a>>n;
printf("the result of leftshift is %d\n",f);
g=a<<n;
printf("the result of rightshift is %d\n",g);
h=a^b;

printf("the result of xor(a^b) is %d\n",h);


return 0;
}
Session No.5

(i) To determine whether a given number is ‘Odd’ or ‘Even’ and print the
message NUMBER IS EVEN or NUMBER IS ODD with and without using
‘else’ statement.
i. With using else option
#include<stdio.h>
int main()
{
int n;
printf("enter the number\n");

scanf("%d",&n);
if(n%2==0)
printf("number is even");
else
printf("number is odd");
return 0;

ii. without using else option


#include<stdio.h>
int main()
{
int n;
printf("enter the number\n");
scanf("%d",&n);
if(((n%2==0)&&
printf("number is even"))||

printf("number is odd"));
return 0;
}
(ii) To determine whether a given number is ‘Positive’, ‘Negative’ or ‘ZERO’
and print the message ‘NUMBER IS POSITIVE’, ‘NUMBER IS NEGATIVE’ or
‘NUMBER IS ZERO’ using nested ‘if’ statement.
#include <stdio.h>
int main()
{
int num;

/* Input number from user */


printf("Enter any number: ");
scanf("%d", &num);
if(num > 0)
{
printf("Number is POSITIVE");

}
if(num < 0)
{
printf("Number is NEGATIVE");
}

if(num == 0)
{
printf("Number is ZERO");
}
return 0;
}
(iii) To compute all the roots of a quadratic equation by accepting the non-
zero coefficients. Print appropriate messages

#include<stdio.h>
#include<math.h>
int main()
{
int a,b,c,d;

double root1,root2;
printf("enter the valule of a b and c\n");
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if (d < 0)
{
printf("First root = %.2lf + i%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
printf("Second root = %.2lf - i%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
}
else
{
root1 = (-b+sqrt(d))/(2*a);
root2 = (-b-sqrt(d))/(2*a);
printf("First root = %.2lf\n", root1);
printf("Second root = %.2lf\n", root2);
}
return 0;
}
Session No.6

(i) To generate an electricity bill by accepting meter number of the


consumer, number of units consumed and print out the detail charges
for the below scenario:
An electricity board charges the following rates for the use of
electricity:
• for the first 200 units 80 paise per unit
• for the next 100 units 90 paise per unit
• beyond 300 units Rs 1 per unit

All users are charged a minimum of Rs. 100 as meter charge. If the total
amount is more than Rs. 400, then an additional surcharge of 15% of total
amount is charged.
#include <stdio.h>
#include <string.h>
int main()
{
int custid, conu;
float chg, surchg=0, gramt,netamt;
char connm[25];

printf("Input Customer ID :");


scanf("%d",&custid);
printf("Input the name of the customer :");
scanf("%s",connm);
printf("Input the unit consumed by the customer : ");
scanf("%d",&conu);
if (conu <200 )

chg = 0.80;
else if (conu>=200 && conu<300)
chg = 0.90;
else
chg = 1.00;
gramt = conu*chg;

if (gramt>400)
surchg = gramt*15/100.0;
netamt = gramt+surchg;
if (netamt < 100)
netamt =100;
printf("\nElectricity Bill\n");
printf("Customer IDNO :%d\n",custid);
printf("Customer Name :%s\n",connm);
printf("unit Consumed :%d\n",conu);
printf("Amount Charges @Rs. %4.2f per unit :%8.2f\n",chg,gramt);

printf("Surchage Amount :%8.2f\n",surchg);


printf("Net Amount Paid By the Customer :%8.2f\n",netamt);
return 0;
}

(ii) A Telecommunication department charges the following tariffs for the


use of Telephone-Line:
• For the first 100 units 95 paise per unit
• For the next 75 units Rs. 1.50 per unit
• Beyond 175 units Rs 2.85 per unit.

All users are charged a minimum of Rs. 75 as service charge. If the total
amount is more than Rs 500, then an additional surcharge of 12.5% of
total amount is charged. Write a program to read the name of the user,
number of units consumed and print out the charges

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

{
int custid, conu;
float chg, surchg=0, gramt,netamt;
char connm[25];

printf("Input Customer ID :");


scanf("%d",&custid);
printf("Input the name of the customer :");
scanf("%s",connm);
printf("Input the unit consumed by the customer : ");
scanf("%d",&conu);
if (conu <100 )
chg = 0.95;
else if (conu>=101 && conu<175)
chg = 1.50;
else
chg = 2.85;

gramt = conu*chg;
if (gramt>500)
surchg = gramt*12.5/100.0;
netamt = gramt+surchg;
if (netamt < 100)
netamt =75;

printf("\nTelecommunication Bill\n");
printf("Customer IDNO :%d\n",custid);
printf("Customer Name :%s\n",connm);
printf("unit Consumed :%d\n",conu);
printf("Amount Charges @Rs. %4.2f per unit :%8.2f\n",chg,gramt);
printf("Surchage Amount :%8.2f\n",surchg);

printf("Net Amount Paid By the Customer :%8.2f\n",netamt);


return 0;
}
Session No.7

(i) To input month number and display its respective month in word.
#include <stdio.h>
void main()

{
int monno;
printf("Input Month No : ");
scanf("%d",&monno);
switch(monno)
{

case 1:
printf("January\n");
break;
case 2:
printf("February\n");

break;
case 3:
printf("March\n");
break;
case 4:
printf("April\n");
break;
case 5:
printf("May\n");
break;
case 6:
printf("June\n");

break;
case 7:
printf("July\n");
break;
case 8:
printf("August\n");

break;
case 9:
printf("September\n");
break;
case 10:
printf("October\n");
break;
case 11:
printf("November\n");
break;

case 12:
printf("December\n");
break;
default:
printf("invalid Month number. \nPlease try again ....\n");
break;

}
}

(ii) To simulates a simple calculator to perform the basic arithmetic


operations (Consider the operators +, -, x, / and % using ‘switch’
statement)
#include<stdio.h>
int main()
{
int num1,num2,opt;
printf("Enter the first Integer:\n");
scanf("%d",&num1);
printf("Enter the second Integer:\n");
scanf("%d",&num2);
printf("\n\n\n\nEnter the your option:\n");
printf("1-Addition.\n2-Substraction.\n3-Multiplication.\n4-Division.\n5-Exit.\n");
scanf("%d",&opt);
switch(opt)
{
case 1:printf("\nAddition of %d and %d is: %d",num1,num2,num1+num2);

break;
case 2:printf("\nSubstraction of %d and %d is: %d",num1,num2,num1-num2);
break;
case3:printf("\nMultiplication of %d and %d is: %d",num1,num2,num1*num2);
break;
case 4:
if(num2==0)
{
printf("OOps Devide by zero\n");
}

else
{
printf("\n Division of %d and %d is: %d",num1,num2,num1/num2);
}
break;
case 5: return 0;

break;
default:printf("\n Enter correct option\n");
break;
}
}

(iii) To check whether a given alphebet is vowel or consonant using ‘switch’


statement

#include <stdio.h>

int main()
{
char ch;

printf("Enter a character: ");


scanf("%c",&ch);

//condition to check character is alphabet or not


if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
//check for VOWEL or CONSONANT
switch(ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':

case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a VOWEL.\n",ch);
break;

default:
printf("%c is a CONSONANT.\n",ch);
}
}
else
{

printf("%c is not an alphabet.\n",ch);


}

return 0;
}
Session No.8

(i) To sum Natural, Odd and Even numbers up to ‘N’.

#include<stdio.h>
void main()
{
int n,sum=0,even_sum=0,odd_sum=0;
printf("enter the number\n");

scanf("%d",&n);
for(int i=1;i<=n;i++)
{
sum=sum+i;
if(i%2==0)
even_sum=even_sum+i;
else
odd_sum=odd_sum+i;
}
printf("the sum of all natural numbers upto %d is %d\n",n,sum);
printf("the sum of all even numbers upto %d is %d\n",n,even_sum);
printf("the sum of all odd_numbers upto %d is %d\n",n,odd_sum);
return 0;
}

(ii) To generate and print the first ‘N’ Fibonacci numbers such that Fn = F(n-
1) + F(n-2) where n>2. A Fibonacci sequence is defined as “the first and
second terms in the sequence are 0 and 1. Subsequent terms are found
by adding the preceding two terms in the sequence”.

#include<stdio.h>
void main()
{
int n,first,second,third,term;
printf("enter the limit\n");

scanf("%d",&n);
first=0;
second=1;
printf("the fibonacci series are\n");
printf("%d\t%d\t",first,second);
third=first+second;
term=2;
while(term<n)
{
printf("%d\t",third);

first=second;
second=third;
third=first+second;
term++;
}
return 0;

(iii) To find the sum of individual digits of a positive integer number reducing
into single digit.
#include<stdio.h>
Int main()
{
int n,sum,rem;
printf("enter the number\n");
scanf("%d",&n);

while((n/10)!=0)
{
sum=0;

while(n!=0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
n=sum;
}
printf("the sum of digits=%d",sum);
return 0;
}

(iv) To reverse a given four-digit integer number and check whether it is a


palindrome or not. Output the given number with suitable message

#include<stdio.h>
int main()
{
int n,rem,revno,orno;
printf("enter the number\n");

scanf("%d",&n);
orno=n;
revno=0;
while(n!=0)
{
rem=n%10;

revno=(revno*10)+rem;
n=n/10;
}
if(orno==revno)
printf("%d is a palindrome number",orno);
else
printf("%d is not a palindrome number",orno);
return 0;
}
Session No.9

(i) To determine whether a given number is Prime or not.


#include<stdio.h>
Int main()

{
int n,count=2,flag=1;
printf("enter the number\n");
scanf("%d",&n);
while(count<n)
{

if(n%count==0)
{
flag=0;
break;
}

count++;
}
if(flag==1)
printf("%d is prime number",n);
else
printf("%d is not a prime number",n);
return 0;
}

(ii) To generate and print all the prime numbers between range N1 and N2,
where ‘N1’ and ‘N2’ are value supplied by the user.
#include <stdio.h>
int main()
{
int n1,n2,i,flag;
printf("Enter start value:");
scanf("%d",&n1);

printf("Enter end value : ");


scanf("%d",&n2);
printf("Prime Numbers between %d and %d :", n2,n1);
while (n1<n2)
{
flag=0;
for(i=2; i<=n1/2; ++i)
{
if(n1%i==0)
{
flag=1;
break;

}
}
if(flag==0)
printf("%d\t",n1);
++n1;
}

return 0;
}

(iii) To find the value of cos(x) using the series, 1 - x2/2! + x4/4! - x6/6! +
x8/8! - ... up to N terms accuracy (With and without using in-built
function)
#include <stdio.h>
int main()
{
int i, j, n, fact, sign = - 1;
float x, p, sum = 0;
printf("Enter the value of x : ");
scanf("%f", &x);
printf("Enter the value of n : ");
scanf("%d", &n);
for (i = 2; i <= n; i += 2)
{
p = 1;
fact = 1;
for (j = 1; j <= i; j++)

{
p = p * x;
fact = fact * j;
}
sum += sign * p / fact;
sign = - 1 * sign;
}
printf("cos %0.2f = %f", x, 1+sum);
return 0;
}

(iv) To find the value of sin(x) using the series, x - x 3 /3! + x 5 /5! - x 7 /7! +
x9 /9! - ... up to N terms accuracy (With and without using in-built
function)
#include <stdio.h>
int main()
{
int i, j, n, fact, sign = - 1;
float x, p, sum = 0;
printf("Enter the value of x : ");
scanf("%f", &x);
printf("Enter the value of n : ");
scanf("%d", &n);
for (i = 1; i <= n; i += 2)
{
p = 1;
fact = 1;
for (j = 1; j <= i; j++)
{
p = p * x;
fact = fact * j;
}
sign = - 1 * sign;
sum += sign * p / fact;
}
printf("sin %0.2f = %f", x, sum);
return 0;
}
Session No.10

(i) To input N Real Numbers and to find mean, variance and standard
deviation using appropriate formula.
#include <stdio.h>
#include <math.h>
#define MAXSIZE 10
Int main()

{
float x[MAXSIZE];
int i, n;
float average, variance, std_deviation, sum = 0, sum1 = 0;

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

scanf("%d", &n);
printf("Enter %d real numbers \n", n);
for (i = 0; i < n; i++)
{
scanf("%f", &x[i]);

}
/* Compute the sum of all elements */
for (i = 0; i < n; i++)
{
sum = sum + x[i];
}
average = sum / (float)n;
/* Compute variance and standard deviation */
for (i = 0; i < n; i++)
{
sum1 = sum1 + pow((x[i] - average), 2);
}
variance = sum1 / (float)n;
std_deviation = sqrt(variance);

printf("Average of all elements = %.2f\n", average);


printf("variance of all elements = %.2f\n", variance);
printf("Standard deviation = %.2f\n", std_deviation);
return 0;
}
(ii) To input N integer numbers into a single dimension array, sort them in to
ascending order using “BUBBLE SORT” technique, and then to print both
the given array and the sorted array with suitable headings.
#include<stdio.h>
int main()
{
int a[10],n,i,j,temp;

printf(“enter the number of elements”);


scanf(“%d”,&n);
printf(“enter the elments”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);

}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{

if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}

}
printf(“the sorted elments are”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
return 0;
}
(iii) To input N integer numbers in into a single dimension array, and then to
perform “LINEAR SEARCH” for a given Key integer number and report
success or failure in the form of a suitable message
#include<stdio.h>
int main()
{
int n,i,a[10],key;

printf(“enter the number of elements”);


scanf(“%d”,&n);
printf(“enter the elements”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);

}
printf(“enter the key elment to search”);
scanf(“%d”,&key);
for(i=0;i<n;i++)
{

if(a[i]==key)
{
printf(“the %d found at the position %d”,key,i+1);
}
}
if(i>n)

printf(“key element not found”);


return 0;
}
Session No.11

(i) To input N integer numbers in ascending order into a single dimension


array, and then to perform “BINARY SEARCH” for a given Key integer
number and report success or failure in the form of a suitable message.
#include<stdio.h>
int main()
{
int n,a[10],key,beg,end,mid;
printf(“enter the number of elements”);
scanf(“%d”,&n);

printf(“enter the elements”);


for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“enter the key element to search”);
scanf(“%d”,&key);
beg=0;

end=n-1;
while(beg<=end)
{
mid=(beg+end)/2;
if(key==a[mid])
{
printf(“%d found at the position %d”,key,mid+1);
break;
}
else if(key>a[mid])
beg=mid+1;

else
end=mid-1;
}
if(beg>end)
printf(“%d is not found”,key);
return 0;

}
(ii) To perform addition and subtraction of two matrices after checking their
compatibility and print both input & output matrices with suitable
headings. Use userdefined functions to read and print the matrices.
#include<stdio.h>
#include<stdlib.h>

// function to add two 3x3 matrix

void add(int m[3][3], int n[3][3], int sum[3][3])


{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
sum[i][j] = m[i][j] + n[i][j];
}

// function to subtract two 3x3 matrix


void subtract(int m[3][3], int n[3][3], int result[3][3])
{
for(int i=0;i<3;i++)

for(int j=0;j<3;j++)
result[i][j] = m[i][j] - n[i][j];
}

// function to display 3x3 matrix


void display(int matrix[3][3])

{
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
printf("%d\t",matrix[i][j]);

printf("\n"); // new line


}
}

// main function
int main()
{
// matrix
int a[][3] = { {5,6,7}, {8,9,10}, {3,1,2} };
int b[][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
int c[3][3];

// print both matrix


printf("First Matrix:\n");

display(a);
printf("Second Matrix:\n");
display(b);

// variable to take choice


int choice;

// menu-driven
do
{
// menu to choose the operation
printf("\nChoose the matrix operation,\n");

printf("----------------------------\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Exit\n");
printf("----------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
add(a, b, c);
printf("Sum of matrix: \n");
display(c);
break;
case 2:
subtract(a, b, c);
printf("Subtraction of matrix: \n");
display(c);
break;
case 3:
printf("Thank You.\n");
exit(0);
default:

printf("Invalid input.\n");
printf("Please enter the correct input.\n");
}
}while(1);

return 0;

}
Session No.12

(i)To read a matrix A (M x N), find the TRANSPOSE of the given matrix and output
both the input matrix and the transposed matrix. Use user-defined functions to
find the TRANSPOSE.
#include <stdio.h>

void transpose(int p[3][3], int t[3][3]);

int main() {

int i, j;

int p[3][3], t[3][3];

printf("Enter matrix P\n");

for (i = 0; i < 3; i++) {

for (j = 0; j < 3; j++) {

printf("Enter the elements of matrix P [%d,%d]: ", i, j);

scanf("%d", & p[i][j]);

transpose(p, t);

printf("Transpose of matrix P is:\n\n");

for (i = 0; i < 3; i++) {

for (j = 0; j < 3; j++) {

printf("%d ", t[i][j]);

printf("\n");

void transpose(int p[3][3], int t[3][3]) {

int row, col;

for (row = 0; row < 3; row++) {

for (col = 0; col < 3; col++) {

t[row][col] = p[col][row];

}
(ii) To find the TRACE and NORM of a given matrix A (M x N) by checking the
compatibility and print both input & output matrices with suitable headings. Use
user-defined functions to find their TRACE and NORM.

// C program to find trace


// and normal of given matrix
#include <math.h>

#include <stdio.h>

// Returns Normal of a matrix


// of size n x n
int findNormal(int mat[][3],
int n)

{
int sum = 0;

// Run nested loop to access


// elements of matrix

for (int i = 0; i < n; i++)


for (int j = 0; j < n; j++)
sum += mat[i][j] * mat[i][j];
return sqrt(sum);
}

// Returns trace of a matrix of


// size n x n
int findTrace(int mat[][3], int n)
{
int sum = 0;

// Run a loop to access diagonal


// elements of matrix
for (int i = 0; i < n; i++)
sum += mat[i][i];
return sum;
}

// Driven code
int main()
{
int mat[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
printf("Normal of Matrix = %d",

findNormal(mat, 3));
printf("\nTrace of Matrix = %d",
findTrace(mat, 3));
return 0;
}

You might also like