0% found this document useful (0 votes)
2 views27 pages

C - Programming & Mat Lab Unit-2

This document provides an overview of conditional statements and arrays in C programming, detailing the syntax and usage of various conditional expressions such as if, else if, and switch statements. It includes sample programs demonstrating these concepts, along with explanations of loops like while, do-while, and for, as well as the differences between break and continue statements. Additionally, it covers the need for decision-making statements in programming and provides examples for practical applications.

Uploaded by

gadiprasad1986
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)
2 views27 pages

C - Programming & Mat Lab Unit-2

This document provides an overview of conditional statements and arrays in C programming, detailing the syntax and usage of various conditional expressions such as if, else if, and switch statements. It includes sample programs demonstrating these concepts, along with explanations of loops like while, do-while, and for, as well as the differences between break and continue statements. Additionally, it covers the need for decision-making statements in programming and provides examples for practical applications.

Uploaded by

gadiprasad1986
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/ 27

UNIT-2

Conditional Statements and Arrays

Describe the conditional expression


In C programming, the conditional expression, also known as the ternary operator, provides a concise way to evaluate
a condition and return one of two expressions based on the result. It is the only ternary operator in C and serves as a
shorthand for simple if-else statements.
Syntax:
condition ? expression_if_true : expression_if_false;
#include <stdio.h>
int main()
{
int a = 10, b = 20;
int max;
max = (a > b) ? a : b;
printf("Maximum value is %d\n", max);
return 0;
}
Output:
Maximum value is 20

Write sample programs based on conditional Statements


#include<stdio.h>
int main()
{
int age;
printf(“Enter your age:”);
scanf(“%d”,&age);
(age>=18) ? printf(“you are eligible for vote”) : printf(“you are not eligible for vote”);
return 0;
}

Output:
Enter your age:22
You are eligible for vote

List the four conditional statements supported by C


C program is a set of statements which are normally executed sequentially in the order. However, we have number of
situations where we may have to change the order of execution of statements based on certain conditions, or repeat a
group of statements until certain specified conditions are met.

1. Decision Making or Conditional Statements


a) Simple if statements
b) If-else statements
c) Nested if-else statements
d) Else-if ladder
e) Switch Statements
Decision Making Statements
Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to
execute a set of statements or not.
These decision-making statements in programming languages decide the direction of the flow of program execution.
These Decision- Making Statements are also called as Conditional Statements

Need of Decision Making Statement in programming


We need to make some decisions and based on these decisions we will execute the next block of code. For example,
In C if x occurs then execute y else execute z.
There can also be multiple conditions like in C if x occurs then execute p, else if condition y occurs execute q, else
execute r.
This condition of C else-if is one of the many ways of importing multiple conditions.

Simple If Statements
‘if’ is keyword .It is used to execute a set of statements when the logical condition is true.
Syntax:
if (condition)
{
Statements;
}

The statement is executed only when condition is true. In case condition is false then compiler skip the line within the
if block.

//program for simple if statement


#include<stdio.h>
int main()
{
int n;
printf (“ enter a number:”);
scanf(“%d”,&n);
If (n>10)
{
printf(“ number is grater”);
}
return 0;
}
Output: Enter a number: 12
Number is greater

If else Statements
The if else statement is a decision-making statements that is used to decide whether the part of the code will be
executed or not based on the specified condition. If the given condition is true, then the code inside of the if block is
executed, otherwise the code inside the else block is executed.
Syntax:
if (condition)
{
Statements;
}
Else
{
Statements;
}

// program for if else


#include<stdio.h>
int main ()
{
int a;
printf(“enter a value:”);
scanf(“%d”,&a);
if(a%2==0)
{
printf(“even”);
}
else
{
printf(“odd”);
}
return 0;
}
Output :1
enter a value : 5
odd
Output 2:
enter a value: 88
even
Nested if else statement
A nested if else statement is an if statement inside another if statement. (or) Either if block or else block or both
Contains another if statement or if else statements then it is called as nested if else statements.
Syntax:
if (condition 1)
{
if (condition 2)
{
Statement 1;
}
else
{
statement 2;
}
}
else
{
if(condition 3)
{
Statements 3;
}
else
{
Statements 4;
}
}

// C program for largest of 3 numbers


#include<stdio.h>
int main ()
{
int a, b,c;
printf(“enter three values:”);
scanf(“%d %d %d”, &a, &b, &c);
{
if(a>b)
{
if(a>c)
{
printf(“a is greater”);
}
else
{
printf(“c is greater”);
}
else
{
if(b>c)
{
printf(“b is greater”);
}
else
{
printf(“c is greater”);
}
}
return 0;
}
Output 1:
enter three values : 5 6 7
c is greater
Output 2:
enter three values: 20 15 10
a is greater
Output 3:
enter three values: 55 78 39
b is greater

Else if statements or else if ladder


The else if ladder statement is an extension of if-else statements, it is used in the scenario where there are
multiple cases to be performed for different conditions.
If a condition is true then the statements defined in the if block will be executed, otherwise if some other
condition is true then else if block will be executed .at last none of the statements is true then else block will
execute.

Syntax is :-
if (condition)
{
Statement1;
}
else if (condition)
{
statement2;
}
else if (condition)
{
statement3;
}
else
{
statement4;
}

This process continue until there is no if statement in the last block. if one of the condition is satisfy the condition
other nested “else if” would not executed.

// C program to find average and to print grade


#include<stdio.h>
int main ()
{
int s1,s2,s3,s4,total;
float avg;
char grade;
printf(“Enter 4 subject marks”);
scanf(“%d %d%d%d”,&s1,&s2,&s3,&s4);
total = s1+s2+s3+s4;
avg = total/4;
printf(“Total marks :%d\n”, total);
printf(“Average : %.2f\n”, avg);
If(avg>60);
{
printf(“Grade = A\n”,grade);
}
elseif(avg>=50 && avg<60);
{
printf(“Grade = B\n”,grade);
}
elseif(avg>=35 && avg>50);
{
printf(“Grade = C\n”,grade);
}
else
{
printf(“Grade = D\n”, grade);
}
return 0;
}
Output:
Enter 4 subject marks: 10 20 40 50
Total marks: 120
Average = 30.00
Grade = D
Switch Statement
Switch Statement tests the value of variable and compress it with multiple cases. Once the case match is found,
a block of statements associated with that particular case is executed.
Rules for Switch Statement:
1. Switch expression must be an integer or character type.
2. The case value must be an integer or a character constant.
3. The case value can be used only inside the switch statements.
4. The break keyword in each case indicates the end of a particular case.
If there is no break statements found in case, all the cases will be executed after the matched case.
5.Case labels always ended with (:)

Syntax:
Switch (expression)
{
case value 1:
block 1;
break;
case value 2:
block 2;
break;
case value 3:
block 3;
break;
case value n:
block n;
break;
default:
default block;
break;
}

// Program for switch statement


#include<stdio.h>
int main ()
{
int num;
printf(“Enter a number”);
scanf(“%d”,&num);
switch(num)
{
case 7:
printf(“vaiue is 7);
break;
case8:
printf(“value is 8);
break;
case 9:
printf(“value is 9);
break;
default:
printf(“out of range”);
break;
}
return 0;
}
Output :
Enter a number : 8
value is 8

// Program without break statement


#include<stdio.h>
int main ()
{
int num = 0;
printf(“Enter a number :”);
scanf(%d”,&num);
switch (num)
{
case 10:
printf(“number is equal to 10\n”);
case 20:
printf(“number is equal to 20\n);
case 30:
printf(“number is equal to 30\n);
default:
printf(“ number is out of range”);
}
return 0;
}
Output:
Enter a number: 10
number is equal to 10
number is equal to 20
number is equal to 30

// C program to perform arithmetic operations using Switch statements


#include<stdio.h>
int main ()
{
int a,b,c;
char oper;
printf(“Enter operator:”);
scanf(“%c”,oper);
printf(“enter a,b values :);
scanf(“%d%d”,&a,&b);
switch oper;
{
case ‘+’:
c = a+b;
printf(“sum = %d”,c);
break;
case ‘-‘:
c = a-b;
printf(“diff = %d”,c);
break;
case ‘*’:
c = a*b;
printf(“multi = %d”,c);
break;
case ‘/’:
c= a/b;
printf(“div = %d”,c);
break;
case ‘%’:
c = a%b;
printf(“mod =%d”,c);
break;
default :
printf(“invalid operator. Try again”);
}
return 0;
}

Write a program to find whether a given year is leap year or not


#include <stdio.h>
int main()
{
int year;
printf(“Enter a year :”);
scanf(“%d”,& year);
if((year%4==0 && year%100!=0) II (year%400==0))
{
printf(“given year is leap year”);
}
else
{
printf(“given year is not a leap year”);
}
return 0;
}

Output:
Enter a year : 2024
given year is leap year

Write a program to check whether a given number is even or odd by using bitwise logical operator
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num & 1)
{
printf("%d is Odd.\n", num);
}
else
{
printf("%d is Even.\n", num);
}
return 0;
}

Write a program to check whether a given character is vowel or consonant by using switch case statement
#include <stdio.h>
int main()
{
char ch;
printf("Enter any alphabet: ");
scanf("%c", &ch);
switch(ch)
{
case 'a':
printf("Vowel");
break;
case 'e':
printf("Vowel");
break;
case 'i':
printf("Vowel");
break;
case 'o':
printf("Vowel");
break;
case 'u':
printf("Vowel");
break;
case 'A':
printf("Vowel");
break;
case 'E':
printf("Vowel");
break;
case 'I':
printf("Vowel");
break;
case 'O':
printf("Vowel");
break;
case 'U':
printf("Vowel");
break;
default:
printf("Consonant");
}

return 0;
}
Output:
Enter any alphabet: a
Vowel
Enter any alphabet:E
Vowel

Enter any alphabet : k


Consonant

Defining looping or Iteration


Sequence of statements is executed until some conditions for termination of the loop are satisfied.
A program loop consists of two segments:
a) Body of the loop
b) Control statements

Control statements test certain conditions and then directs the repeated execution of the statements contained
in the body of the loop.
1.The while statement
2.The do-while statement
3.The for statement

A looping process, in general include four steps:


1. Setting and initialization of a condition variable.
2. Execution of statements in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.

Initialization : it is assignment statement that is used to set the loop control variable.
Condition : It is relational expression that determining when the loop will exit.
Increment/ Decrement: defines how the loop control variable will change each time loop is repeated.

While Statement
The while is an entry- controlled loop statement.
The test condition is evaluated and if the condition is true, then the body of the loop is executed after execution
of the body, the test condition is once again evaluated if it is true.
This process of repeated execution of the body continues until the test condition becomes ‘false’ and control is
transferred out of the loop.
Syntax:
While(test condition)
{
Body of loop;
}

Flow chart:
#C program to check sum of digits of a given number
#include<stdio.h>
int main()
{
int n, sum=0,r;
printf(“Enter n value);
scanf(“%d”, &n);
while(n!=0)
{
r=n%10;
sum= sum+r;
n=n/10;
}
printf(“sum of digits:%d”,sum);
return 0;
}
Output:
Enter n value: 456
sum of digits :15

Do-while Statement
The do-while constructor provides an exit-control loop and therefore the body of the loop is always executed at
least once.
The program proceeds to evaluate the body of the loop first.At the end of the loop,the test condition in the
while statement is evaluated.
Syntax:
do
{
body of loop;
}
while(test-condition)

flow chart

#include<stdio.h>
int main ()
{
int k;
k=1;
do
{
printf(“%d”,k);
k++;
}
while(i<=5);
return 0;
}
Output:
12345

#C program to check the given number is Armstrong or not


#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf(“Enter n value”);
scanf(“%d”,&n);
n=temp;
do
{
r=r%10;
sum=sum+(r*r*r);
n=n%10;
}
while(n!=0);
if(sum==temp)
{
printf(“Armstrong”);
}
else
{
printf(“Not Armstrong”);
}
return 0;
}
Output:1
Enter n value 153
Armstrong
Output :2
Enter n value 123
Not Armstrong

For loop :
The for loop is another entry-controlled loop that provides a more concise loop control structure.
Syntax:
for(initialization; test condition; increment/decrement);
{
body of loop;
}
Flow chart:

Example:
#include<stdio.h>
int main()
{
int k=1;
for(k=1;k<=5;k++)
{
printf(“%d”,k);
}
}
Output:
12345

# C program to print Fibonacci numbers


Fabonacci series is a sequence of numbers where each number is the sum of two preceding ones.
0 ,1,1,2,3,5,8,13,21,34,…………….

#include<stdio.h>
int main()
{
int I,n,first=0,second=1,next;
printf(“Enter the number of terms:”);
scanf(“%d”,&n)”
for(I=0;I<n;I++)
{
printf(“%d , ”,first);
first=second;
next=first+second;
second=next;
}
return 0;
}
Output:
Enter the number of terms: 9
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 ,
Differentiate while & do while loops

while do-while

Statement(s) is executed atleast once, thereafter condition is


Condition is checked first then statement(s) is executed.
checked.

It might occur statement(s) is executed zero times, If condition is


At least once the statement(s) is executed.
false.

No semicolon at the end of while. while(condition) Semicolon at the end of while. while(condition);

Variable in condition is initialized before the execution of loop. variable may be initialized before or within the loop.

while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) { statement(s); } do { statement(s); } while(condition);

Differentiate break & continue statements

Break Statement Continue Statement


The Break statement is used to exit from The continue statement is not used to
the loop constructs. exit from the loop constructs.

The break statement is usually used with The continue statement is not used with
the switch statement, and it can also use the switch statement, but it can be used
it within the while loop, do-while loop, or within the while loop, do-while loop, or
the for-loop. for-loop.

When the continue statement is


When a break statement is encountered
encountered then the control
then the control is exited from the loop
automatically passed from the beginning
construct immediately.
of the loop statement.
Syntax: Syntax:
break; continue;

Break statements uses switch and label It does not use switch and label
statements. statements.

Leftover iterations can be executed even


Leftover iterations are not executed after
if the continue keyword appears in a
the break statement.
loop.
Write the syntax of nested loops and explain

Nested loop is a loop inside another loop. This means that there is an inner and outer loop.
The inner loop is completely contained within the body of the outer loop.
Each time outer loop runs, the inner loop runs several times.
Syntax:
for(initialization; condition; updation)
{
for(initialization; condition; updation)
{
Statements of inner loop;
}
Statements of outer loop;
}

Flow chart:

C program to print the given pattern


*
**
***
****
*****
#include<stdio.h>
int main ()
{
int I,j;
for(I=1;I<=5;I++)
{
for (j=0;j<I;j++)
{
printf(“*”);
}
printf(“\n”);
}
return 0;
}
Write a program to find sum of n natural numbers
# include <stdio.h>
int main ()
{
int i=1, n, sum=0;
printf(“Enter n value:”);
scanf(“%d”,&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf(“%d”,sum);
return 0;
}

Output:
Enter n value : 5
15

Write a program to print even and odd numbers


#include<stdio.h>
int main()
{
int i,n,even=0,odd=0;
printf("\nEnter the Ending value:");
scanf("%d",&n);
printf("\nEven numbers:");
for(i=0;i<=n;i++)
{
if(i%2==0)
{
printf("\n%d",i);
even++;
}
}
printf("\nOdd numbers:");
for(i=1;i<=n;i++)
{
if(i%2==1)
{
printf("\n%d",i);
odd++;
}
}
printf("\nTotal even numbers:%d",even);
printf("\nTotal odd numbers:%d",odd);
return 0;
}

Output:
Enter the Ending value: 8
Even numbers:
0
2
4
6
8
Odd numbers:
1
3
5
7
Total even numbers:5
Total odd numbers: 4

Write a program to check whether a given number is prime number or not


#include<stdio.h>
int main()
{
int i, n, count=0;
printf(“Enter a number :”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
if( n%i==0)
{
count++;
}
}
if(count==2)
{
printf(“Prime”);
}
else
{
print(“Not a prime”);
}
return 0;
}
Output:
Enter a number : 5
Prime

Write a program to print prime numbers between two given numbers


#include <stdio.h>

int main()
{
int lower, upper, i, j, isPrime;
printf("Enter lower limit: ");
scanf("%d", &lower);
printf("Enter upper limit: ");
scanf("%d", &upper);
printf("Prime numbers between %d and %d are:\n", lower, upper);

for (i = lower; i <= upper; i++)


{
if (i < 2)
isPrime = 1;
for (j = 2; j * j <= i; j++)
{
if (i % j == 0)
{
isPrime = 0;
break;
}
}

if (isPrime)
printf("%d ", i);
}

printf("\n");
return 0;
}

Output
Enter lower limit: 10
Enter upper limit: 30
Prime numbers between 10 and 30 are:
11 13 17 19 23 29

Write a program to check whether a given number is PALINDROME or not


#include <stdio.h>
int main ()
{
int n, r, original, reverse=0;
printf(“Enter n value”);
scanf(“%d”&n);
n=original;
while(n!=0)
{
r =n%10;
reverse = (reverse *10)+r;
n = n/10;
}
if(reverse==original)
{
printf(“Given number is Palindrome”);
}
else
{
printf(“Given number is Not Palindrome”);
}
return 0;
}
Output:1
Enter n value : 12
Given number is Palindrome

Output: 2
Enter n value : 150
Given number is not Palindrome

Define an Array.
An Array is a fixed –size sequenced collection of elements of the same data type. It can be used to represents a
list of numbers or list of names. It can be used to store the collection of primitive data types such as int, char,
float, etc., and also derived and user-defined data types such as pointers, structures, etc.

C Array Declaration
In C, we have to declare the array like any other variable before using it. We can declare an array by specifying
its name, the type of its
elements, and the size of its dimensions. When we declare an array in C, the compiler allocates the memory
block of the specified size to
the array name.
Syntax of Array Declaration
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];

Example:
// C Program to illustrate the array declaration
#include <stdio.h>
int main()
{
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];
return 0;
}

C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is declared or
allocated memory, the elements
of the array contain some garbage value. So, we need to initialize the array to some meaningful value. There
are multiple ways in which
we can initialize an array in C.

1. Array Initialization with Declaration


In this method, we initialize the array along with its declaration. We use an initializer list to initialize multiple
elements of the array.
An initialize list is the list of values enclosed within braces { } separated b a comma.
data_type array_name [size] = {value1, value2, ... valueN};

2. Array Initialization with Declaration without Size


If we initialize an array using an initializer list, we can skip declaring the size of the array as the compiler can
automatically deduce the
size of the array in these cases. The size of the array in these cases is equal to the number of elements present
in the initializer list as
the compiler can automatically deduce the size of the array.
data_type array_name[] = {1,2,3,4,5};
3. Array Initialization after Declaration (Using Loops)
We initialize the array after the declaration by assigning the initial value to each element individually. We can
use for loop, while
loop, or do-while loop to assign the value to each element of the array.
for (int i = 0; i < N; i++)
{
array_name[i] = valuei;
}

Example of Array Initialization in C


// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
// array initialization using initialize list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++)
{
arr2[i] = (float)i * 2.1;
}
return 0;
}

One dimensional array in C


Arrays are a fundamental concept in programming, and they come in different dimensions. One-dimensional
arrays, also known as single
arrays, are arrays with only one dimension or a single row.
Syntax of One-Dimensional Array in C
dataType arrayName [arraySize];
dataType : specifies the data type of the array. It can be any valid data type in C programming language, such
as int, float, char, double,
etc.
arrayName: is the name of the array, which is used to refer to the array in the program.
arraySize: specifies the number of elements in the array. It must be a positive integer value.

Example of One-Dimensional Array in C


#include <stdio.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
for(int i=0; i<5; i++)
{
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}

Output:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Initializing One Dimensional Array in C


In C programming language, we can initialize a one-dimensional array while declaring it or later in the
program. We can initialize a one
dimensional array while declaring it by using the following
syntax: dataType arrayName[arraySize] = {element1, element2, ..., elementN};

Example of Initializing One Dimensional Array in C


#include <stdio.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
for(int i=0; i<5; i++)
{
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}
Output of the code:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Accessing Elements of One-Dimensional Array in C


In a one-dimensional array, each element is identified by its index or position in the array. The index of the
first element in the array is 0,
and the index of the last element is arraySize - 1.
To access an element of a one-dimensional array in C programming language, we use the following
syntax: arrayName[index]
arrayName is the name of the array.
index is the index of the element we want to access.

Example of Accessing Elements of One-Dimensional Array in C


#include <stdio.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
printf("The first element of the array is: %d\n", numbers[0]);
printf("The third element of the array is: %d\n", numbers[2]);
return 0;
}

Output:
The first element of the array is: 10
The third element of the array is: 30

i) Write a C program to find largest / smallest number in an array


ii) Write a C program to sort the numbers in an array in ascending order
iii) Write a C program to find sum of elements of an array

Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They can be visualized in
the form of rows and
columns organized in a two-dimensional plane. However, 2D arrays are created to implement a relational
database lookalike data
structure. It provides ease of holding the bulk of data at once which can be passed to any number of functions
wherever required.
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];

Declaration of two dimensional Array in C


The syntax to declare the 2D array is : data_type array_name[rows][columns];
Consider the following example : int twodimen[4][3];

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being
done simultaneously. However, this will not work with 2D arrays.
At Compile time: Int a[2][3]={0,0,0,1,1,1}; or {{0,0,0},{1,1,1}};

#include<stdio.h>
int main()
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

Run time:
int a[2][3];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
printing the elements ....
56 10 30
34 21 34
45 56 78

Sample programs on matrix addition, subtraction, and matrix multiplication


Program to Add Two Matrices
#include <stdio.h>
int main()
{
int r, c, a[r][c], b[r][c], sum[r][c], i, j;
printf("Enter the number of rows : ");
scanf("%d", &r);
printf("Enter the number of columns : ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
scanf("%d", &b[i][j]);
}
// adding two matrices
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j)
{
sum[i][j] = a[i][j] + b[i][j];
printf(“%d\t”,c[i][j]);
}
Printf(“\n”);
}
Enter the number of rows : 2
Enter the number of columns : 3
Enter elements of 1st matrix:
Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3
Sum of two matrices:
-2 8 7
10 8 6
Addition of two matrices:
#include<stdio.h>
int main ()
int a[2][3],b[2][3],c[2][3],i,j;
printf(“Enter first matrix:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter second matrix:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“sum of two matrices:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
return 0;
}
Output:
Enter first matrix:
123456
Enter second matrix:
678912
sum of two matrices:
7 9 11
13 6 8

Multiplication of two matrices:


#include<stdio.h>
int main ()
int a[3][3],b[3][2],c[3][2],i,j,sum;
printf(“Enter the elements of first matrix :\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the elements of second matrix :\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“printing the first matrix:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
printf(“printing second matrix :\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(“%d”,b[i][j]);
}
printf(“\n”);
}
printf(“Multiplication of two matrices:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
sum =0;
for(k=0;k<3<k++)
{
sum=sum+a[i][k]*b[k][j];
}
c[i][j]=sum;
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
return 0;
}
Output:
Enter elements of first matix:
0 5 2 -1 1 0 3 5 7 5
Enter elements of second matix:
1201254
Printing the first matrix:

0 5 2 -1 1 0
3 7 5

Printing the first matrix:


1 2
0 1
5 4
Multiplication of two matrices:
10 13 -1 -1
28 33

You might also like