Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Assiggnment F CP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Name: Pranjal Gupta A

BASIC PROGRAMS
Program 1:
Aim: Introduction to C programming with a simple program to print "Hello, World!"
Theory:
1. #include:
#include instructs the compiler to add the content of stdio. Above program has hash
define statements which is included within the (standard input-output header) file so
on.
2. Purpose of stdio. h: This file contains declarations for the standard I/O functions such as
printf, scanf etc. This program uses printf() to print the output so stdio. h must be
included.
3. int main():
Main Function: The execution of every C program begins from the main() function. The
int before main means that the function returns int values (in this case, 0 to indicate
successful execution).
main() function: It is the main and always mandatory to write this; that is entry point of
any c program, So Your Program start with it.
4. { }:
Curly Braces: The curly braces { } are used to denote the main() function nodes. If the
program is run, all of the code inside these braces will be executed.
5. printf("Hello World!"):
printf() Function : This is an library function from stdio. Output (print) text to the console
were what h used for.
print() function followed by parentheses () and inside those, the string Hello World! is
provided as an argument. We will print that string to the screen
Semicolon;:.making in C, after every statement we put a semicolon. This signals the
compiler that this statement is now complete.

6. return 0;
Return statement – When program ends this statement returns integer 0 to operating
system A return of 0 means the program executed successfully with no errors being
produced. This is because in int main(), a function which was declared as an integer, we
need to return some value from int. Here, 0 is used as the success completion
benchmark.

Program code:
#include<stdio.h>

int main()

printf("Hello World!");

Name: Pranjal Gupta A


return 0;

Output:

Conclusion:
The "Hello, World!" program serves as a foundational exercise in C programming, allowing
beginners to grasp fundamental concepts in a simple and clear manner. It sets the stage for
more complex programming tasks, such as working with variables, loops, conditionals, and
functions. Through this program, one learns the importance of correct syntax, the inclusion of
necessary libraries, and the basic structure of a C program.

Program 2:
Aim: Program to perform basic arithmetic operations (addition, subtraction, multiplication,
division).

Theory:
1. Variable Declaration:
int num1, num2, sum, sub, mul: These integer variables are declared to store the input
numbers (num1, num2) and the results of the arithmetic operations (sum, sub, mul).
float div: The div variable is declared as a float to store the result of the division
operation. Since division may result in decimal values, a floating-point variable is
necessary.
char operator: This variable is declared to store the arithmetic operator (+, -, *, /) entered
by the user.

2. User Input:
The program uses the scanf() function to take input from the user:
scanf("%d", &num1); takes the first integer.
scanf("%d", &num2); takes the second integer.
scanf("%c", &operator); takes the operator, but note that there are multiple scanf() calls
for the operator due to the newline character issue explained below.

3. Switch Statement:
The switch statement evaluates the value of the operator variable and executes the
corresponding case:
case '+': Adds the two numbers and stores the result in sum.

Name: Pranjal Gupta A


case '-': Subtracts the second number from the first and stores the result in sub.
case '*': Multiplies the two numbers and stores the result in mul.
case '/': Divides the first number by the second, storing the result in div. Before
performing the division, the program checks if the second number (num2) is zero to
prevent a division by zero error.
Each case includes a break; statement to exit the switch block once the operation is
performed.
Division by Zero Check
if (num2 == 0): Before performing the division, the program checks if the second number
is zero. If it is, it prints "Not divisible," preventing a runtime error.
If num2 is not zero, the program performs the division and prints the result.

4. printf() for Output:


After each arithmetic operation, the program prints the result:
Addition (+): printf("The sum of two = %d", sum);
Subtraction (-): printf("The sub of two = %d", sub);
Multiplication (*): printf("The sum of two = %d", mul); (Note: this label should ideally be
changed to "The product of two" for clarity.)
Division (/): printf("The sum of two = %f", div); is used to print the floating-point result of
division.

Program Code:
#include<stdio.h>

int main()

int num1,num2,sum,sub,mul;

float div;

char operator;

printf("Enter the first number: ");

scanf("%d",&num1);

printf("Enter the second number: ");

scanf("%d",&num2);

printf("Enter the operator: ");

scanf("%c",&operator);

scanf("%c",&operator);

scanf("%c",&operator);

switch (operator){

case '+': sum=num1+num2;

Name: Pranjal Gupta A


printf("The sum of two = %d",sum);

break;

case '-': sub=num1-num2;

printf("The sub of two = %d",sub);

break;

case '*': mul=num1*num2;

printf("The sum of two = %d",mul);

break;

case '/': div=num1/num2;

if(num2==0)

printf("Not divisible");

else

printf("The sum of two = %f",div);

break;

return 0;

Output:
1. Addition:

2. Subtraction:

Name: Pranjal Gupta A


3. Multiplication:

4. Division:

Conclusion:
This program showcases the use of a switch statement for handling multiple cases, user input,
arithmetic operations, and error handling for division by zero. It demonstrates the fundamental
control structures of C, which are important for solving complex problems in a structured
manner.

Name: Pranjal Gupta A


Program 3:
Aim: Calculating simple interest with given principal, rate, and time.
Theory:
1. Variable Declaration:
The program declares four variables:

int p, r, t;: These variables are integers that represent the principal amount (p), the rate of
interest (r), and the time (t).

float si;: This variable is declared as a float type to store the calculated value of the
simple interest (si). A float is used here because the result of the division could be a
decimal value.

2. User Input (scanf()):


The program uses the scanf() function to take inputs from the user:

scanf("%d", &p);: Reads an integer input from the user and stores it in the variable p
(principal amount).

scanf("%d", &r);: Reads an integer input for the rate of interest and stores it in r.

scanf("%d", &t);: Reads an integer input for the time period and stores it in t.

The format specifier %d is used to indicate that the input is of integer type, and the &
symbol is used to provide the memory address of the variables where the input values
will be stored.

3. Simple Interest Calculation:


si = ((p * r * t) / 100);: This formula calculates the simple interest based on the inputs
provided.

The principal (p), rate of interest (r), and time (t) are multiplied together and then divided
by 100 to obtain the simple interest

The result is stored in the floating-point variable si since division can result in a decimal
value.

Order of Operations: The multiplication (p * r * t) is performed first, followed by the


division by 100.

4. Displaying the Result (printf()):


printf("The Simple Interest SI = %f", si);: This line outputs the result of the simple interest
calculation to the user.

%f is the format specifier used to print floating-point values (decimals).

The calculated value of si is substituted in place of %f in the output.

Name: Pranjal Gupta A


Program Code:
#include<stdio.h>

int main(){

int p,r,t;

float si;

printf("Enter the principal amount: ");

scanf("%d",&p);

printf("Enter the rate of interest r: ");

scanf("%d",&r);

printf("Enter the time: ");

scanf("%d",&t);

si=((p*r*t)/100);

printf("The Simple Interest SI=%f",si);

return 0;

Output:

Conclusion:
This program demonstrates how to calculate simple interest based on user input using basic
arithmetic operations in C. It introduces the use of scanf() for taking input and printf() for
displaying the output, along with fundamental concepts like variable declaration, data types
(integer and float), and simple mathematical operations. By mastering this type of program, you
can expand to more complex calculations and financial applications in C.

Name: Pranjal Gupta A


Program 4:
Aim: Program to convert temperature from Celsius to Fahrenheit and vice versa.
Theory:
1. Variable Declaration

The program uses different variables for different cases:

int choice;: This variable is used to store the user's selection for the type of conversion
(Fahrenheit to Celsius or Celsius to Fahrenheit).

For Fahrenheit to Celsius:

int f;: Used to store the Fahrenheit temperature entered by the user.

float c;: Used to store the calculated Celsius temperature, as it may contain decimal
values.

For Celsius to Fahrenheit:

int C;: Used to store the Celsius temperature entered by the user.

float F;: Used to store the calculated Fahrenheit temperature.

2. User Input (scanf())

The program prompts the user to enter a choice for conversion:

Press 1 for Fahrenheit to Celsius and press 2 for Celsius to Fahrenheit: : The user is
prompted to choose the type of conversion.

scanf("%d", &choice);: Reads the user’s choice as an integer and stores it in the choice
variable.

3. Switch Case for User Choice

A switch statement is used to evaluate the value of choice and execute the appropriate
block of code based on the user’s selection.

Case 1: Fahrenheit to Celsius

If the user chooses 1:The program asks the user to input the temperature in Fahrenheit.
Scanf("%d", &f);: Reads the Fahrenheit temperature and stores it in the variable f.

Case 2:

If the user chooses 2:The program asks the user to input the temperature in Celsius.

scanf("%d", &C);: Reads the Celsius temperature and stores it in the variable C.

Default Case:
If the user enters an invalid choice (not 1 or 2), the default case will handle it. In this
program, the default block does not print any error message or perform any action.

Name: Pranjal Gupta A


Program Code:
#include<stdio.h>

int main()

int choice;

printf("Press 1 for Fahrenheit to Celsius and press 2 for Celsius to Fahrenheit: ");

scanf("%d",&choice);

switch(choice){

case 1:

int f;

float c;

printf("Enter Fahrenheit F: ");

scanf("%d",&f);

c=((f - 32)*(5/9));

printf("Celsius is: %f",c);

break;

case 2:

int C;

float F;

printf("Enter Celsius C: ");

scanf("%d",&C);

F= ((C*(9/5))+32);

printf("Fahrenheit is: %f",F);

break;

default:

break;

return 0;

Output:

Name: Pranjal Gupta A


1. Fahrenheit to Celsius:

2. Celsius to Fahrenheit:

Conclusion:
This program demonstrates the use of conditional logic with a switch statement to perform two
different tasks (temperature conversions) based on user input. It introduces fundamental
concepts such as handling user input, arithmetic operations, and correcting potential errors
related to integer division. This type of problem-solving structure is common in programs that
offer multiple options based on user input.

Program 5:
Aim: Calculating the sum of natural numbers up to a given limit using loops.
Theory:
1. Variable Declaration

The program declares three variables:

int i;: This is a loop control variable used to iterate from 1 to n.

int n;: This stores the user input, representing the upper limit for the sum (i.e.,
the total number of natural numbers to be added).

int sum = 0;: This variable holds the accumulated sum of the numbers. It is
initialized to 0 because the sum starts from zero.

2. User Input (scanf())

printf("Enter the number n: ");: The program prompts the user to enter a value for n.

Name: Pranjal Gupta A


scanf("%d", &n);: Reads the user input as an integer and stores it in the variable n. The
%d format specifier is used because the input is an integer.

3. For Loop

for(i = 1; i <= n; i++): This loop runs from i = 1 to i = n, incrementing i by 1 each time (using
i++ The loop controls how many times the code inside the loop body will be executed.

For each iteration, the current value of i is added to sum.

sum = sum + i;: This is the core operation of the program, where the current
value of i is added to the sum, and the result is stored back into sum.

For example, if n = 5, the loop will work as follows:

Iteration 1: sum = 0 + 1 = 1

Iteration 2: sum = 1 + 2 = 3

Iteration 3: sum = 3 + 3 = 6

Iteration 4: sum = 6 + 4 = 10

Iteration 5: sum = 10 + 5 = 15

After the loop finishes, the accumulated value of sum will be printed using the printf statement.

Program Code:
#include<stdio.h>

int main()

int i,n,sum=0;

printf("Enter the number n: ");

scanf("%d",&n);

for(i=1;i<=n;i++){

sum=sum+i;

printf("Sum=%d",sum);

return 0;

Output:

Name: Pranjal Gupta A


Conclusion:
This program demonstrates a simple use of loops, variable manipulation, and basic
input/output operations in C. It also shows how to calculate the sum of a series of numbers
using iteration, which is a fundamental concept in programming.

Program 6:
Aim: Program to determine if a number is even or odd using if-else statements.
Theory:
1. variable declaration:
the program declares one variable:int n;: this variable is used to store the number input
by the user.

2. user input (scanf()):


printf("Enter the number n: ");: prompts the user to enter an integer value.
scanf("%d", &n);: reads the integer input provided by the user and stores it in the variable
n. the format specifier %d is used because n is an integer.

3. conditional check (if-else):


the core logic of the program is the conditional check to determine whether the number
is even or odd:
if(n % 2 == 0): the program checks if the remainder when n is divided by 2 is zero (n % 2
== 0). the modulus operator (%) is used to calculate the remainder of the division. If the
condition is true, it means n is divisible by 2 and is, therefore, an even number.
else: if the condition is false (i.e., n % 2 is not equal to 0), the program executes the else
block

Program Code:
#include<stdio.h>

int main()

Name: Pranjal Gupta A


{

int n;

printf("Enter the number n: ");

scanf("%d",&n);

if(n%2==0)

printf("N is even");

else

printf("N is odd");

return 0;

Output:

Conclusions:
This program is a simple demonstration of how to check whether a number is even or odd using
basic arithmetic and conditional statements. it illustrates the use of the modulus operator,
conditional logic, and input/output operations in c.

Program 7:
Aim: Finding the factorial of a number using for loop.

Name: Pranjal Gupta A


Theory:
1. variable declaration:
the program declares the following variables:
int n;: stores the number for which the factorial is to be calculated, provided by the
user.int i;: used as a loop control variable for iterating through the numbers from 1 to n.
int rlt = 1;: stores the result of the factorial calculation. it is initialized to 1 because
multiplying any number by 1 doesn't change its value.

2. user input (scanf()):


printf("Enter the number n: ");: prompts the user to enter an integer value.
scanf("%d", &n);: reads the integer input provided by the user and stores it in the variable
n. the format specifier %d is used because n is an integer.

3. special case for n = 0


since the factorial of 0 is defined as 1, the program handles this special case separately,
if n is equal to 0, the program directly prints "the factorial of 0 is 1" and skips the rest of
the calculations.

4. Factorial calculation using a for loop


for values of n greater than 0, the program uses a for loop to calculate the factorial:

for(i = 1; i <= n; i++): the loop iterates through the numbers from 1 to n.

rlt = rlt * i;: in each iteration, the current value of i is multiplied with the current
value of rlt, which stores the result of the factorial calculation.

for example, if n = 5, the loop performs the following multiplications:

▪ iteration 1: rlt = 1 * 1 = 1

▪ iteration 2: rlt = 1 * 2 = 2

▪ iteration 3: rlt = 2 * 3 = 6

▪ iteration 4: rlt = 6 * 4 = 24

▪ iteration 5: rlt = 24 * 5 = 120

5. displaying the result:


after the loop completes, the program prints the calculated factorial the result is
displayed as an integer because the factorial of any non-negative integer is always an
integer.

Program Code:
#include<stdio.h>

int main()

Name: Pranjal Gupta A


int n,i,j,rlt=1;

printf("Enter the number n: ");

scanf("%d",&n);

if(n==0)

printf("The factorial of 0 is 1");

else

for(i=1;i<=n;i++){

rlt=rlt*i;

printf("The factorial is %d",rlt);

return 0;

Output:

Conclusion:
This program provides a simple and efficient way to calculate the factorial of a given number
using loops and conditional statements. it demonstrates basic programming concepts such as

Name: Pranjal Gupta A


variable manipulation, loops, and conditional checks, which are essential for problem-solving
in c.

Program 8:
Aim: Program to define, initialize, and display a 1-D array.
Theory:
1. Array Declaration and Initialization:

The 1-D array array[5] is defined to hold 5 integers. The array is initialized with the values
{10, 20, 30, 40, 50}.

2. Displaying the Elements:

A for loop is used to iterate over the array and print each element along with its index.
The loop runs from i = 0 to i = 4 (5 iterations, as array indexing starts at 0).

Program Code:
#include <stdio.h>

int main() {

// Define and initialize a 1-D array

int array[5] = {10, 20, 30, 40, 50};

// Display the elements of the array

printf("Elements of the array are:\n");

for (int i = 0; i < 5; i++) {

printf("Element at index %d: %d\n", i, array[i]);

return 0;

Output:

Name: Pranjal Gupta A


Conclusion:
This program demonstrates how to define, initialize, and display the elements of a 1-D array in
C.

Program 9:
Aim: To find smallest, largest, average, max and min from list of n numbers
Theory:
1. Array Declaration:

The array arr[] is declared and initialized with 10 integer values: {2, 4, 5, 1, 7, 10, 3, 6, 8,
9}. The number of elements in the array (n) is calculated by dividing the total size of the
array (sizeof(arr)) by the size of one element (sizeof(arr[0])).

2. Initialization of Variables:

Three variables are initialized:

o smallest and largest are set to the first element of the array (arr[0]).

o sum is initialized to 0 to accumulate the sum of all array elements.

o average is declared as a float to store the average value.

3. Iteration Through the Array:

The program uses a for loop to iterate through the array, calculating the sum of the
elements, and comparing each element to find the smallest and largest values.

4. Calculating the Average:

Name: Pranjal Gupta A


Once the sum is calculated, the program computes the average by dividing the sum by
the number of elements (n).

The program begins by initializing the smallest and largest values to the first element of the
array. As it iterates through each element of the array:

• It adds the element to the running total sum.

• It checks if the current element is smaller than smallest or larger than largest, and
updates those values accordingly.

And Finally, it calculates the average and prints the results.

Program Code:
#include <stdio.h> int

main() {

int arr[] = {2, 4, 5, 1, 7, 10, 3, 6, 8, 9};

int n = sizeof(arr) / sizeof(arr[0]);

int smallest = arr[0]; int


largest = arr[0]; int sum = 0;

float average;

// Iterate through the array


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

{ // Calculate the sum

sum += arr[i];
// Find the smallest and largest numbers

if (arr[i] < smallest) {

smallest = arr[i];

if (arr[i] > largest) {

largest = arr[i];

// Calculate the average

average = (float)sum / n;

// Print the results

Name: Pranjal Gupta A


printf("Smallest: %d\n", smallest);

printf("Largest: %d\n", largest);

printf("Average: %.2f\n", average);

return 0;

}
Output:

Conclusion:
This program effectively calculates the smallest, largest, and average values of a given array
using basic iteration and conditional checks. It showcases fundamental array operations, such
as accessing elements, calculating sums, and finding minimum and maximum values.

Program 10:
Aim: Swapping two numbers using and without using third variable
Theory:
1. Variable Declaration:

The program declares three integer variables:

int a, b, c;:a and b are the two numbers whose values will be swapped. c is a temporary
variable used to hold the value of one of the variables during the swapping process.

2. User Input (scanf())

printf("Enter the number a: ");: The program prompts the user to enter the first number,
which will be stored in a.

scanf("%d", &a);: This function reads the integer input and stores it in a. The format
specifier %d is used because a is an integer.

Name: Pranjal Gupta A


printf("Enter the number b: ");: The program prompts the user to enter the second
number, which will be stored in b.

scanf("%d", &b);: This function reads the integer input and stores it in b.

a. Using third variable:


The swapping is performed using a temporary variable c:
c = a;: The value of a is stored in c. This step is crucial because it prevents the
original value of a from being lost when we assign a new value to a.
a = b;: The value of b is assigned to a, effectively changing the value of a to that of b.
b = c;: The original value of a (now stored in c) is assigned to b. This completes the
swap, as b now contains the initial value of a.
And then at last the values are made to be printed after using the logic.

b. Without using third variable:


The swapping is done using addition and subtraction:
a = a + b;: The sum of a and b is stored in a. At this point, a contains the total of the
original values of a and b.
b = a - b;: The value of b is calculated by subtracting the original value of b from the
new value of a (which is a + b). This effectively assigns the original value of a to b.
a = a - b;: The value of a is recalculated by subtracting the new value of b (which is
now the original value of a) from the new value of a (which is a + b). This results in a
being assigned the original value of b.

Program Code:
1. Using third variable:
#include<stdio.h>

int main()

int a,b,c;

printf("Enter the number a: ");

scanf("%d",&a);

printf("Enter the number b: ");

scanf("%d",&b);

c=a;

a=b;

b=c;

// values after swapping

printf("Values after swapping\na=%d\n",a);

Name: Pranjal Gupta A


printf("b=%d",b);

return 0;

2. Without using third variable:


#include<stdio.h>
int main()
{
int a,b;
printf("Enter the number a: ");
scanf("%d",&a);
printf("Enter the number b: ");
scanf("%d",&b);
a=a+b;
b=a-b;
a=a-b;
// values after swapping
printf("Values after swapping\na=%d\n",a);
printf("b=%d",b);
return 0;
}

Output:
1. With using third variable:

2. Without using third variable:

Name: Pranjal Gupta A


Conclusion:
Both methods achieve the same goal of swapping two numbers, but each has its advantages
and trade-offs. Using a third variable is simpler and easier to follow, while swapping without a
third variable is more memory-efficient but requires careful implementation, especially in
arithmetic methods to avoid overflow issues. Understanding both approaches is valuable in
mastering problem-solving in C.

Name: Pranjal Gupta A


INTERMIDIATE PROGRAMS
Program 1:
Aim: Program to perform addition of two 2-D arrays (matrices).
Theory:
1.Variable Declaration:

int rows, cols, i, j;: These variables are declared to store the number of rows and columns of the
matrices, as well as for loop counters (i and j).

a[rows][cols], b[rows][cols], and sum[rows][cols]: These are the 2D arrays used to store the two
input matrices and the resultant matrix after addition. The size of the matrices is determined by
the user input for rows and cols.

3. Input for the First Matrix and Second Matrix:


The program then asks the user to enter the elements for the first matrix using a nested
for loop. The outer loop iterates over the rows, and the inner loop iterates over the
columns. Similarly, the program prompts the user to input the elements for the second
matrix using the same nested loop structure.

4. Matrix Addition:
The program performs the element-wise addition of the two matrices using a nested
loop. Each element in a[i][j] is added to the corresponding element in b[i][j], and the
result is stored in sum[i][j].

5. Displaying the Resultant Matrix:


After performing the addition, the program prints the resultant matrix (sum) to the
console. Each element of the matrix is displayed with a tab space (\t) for formatting.

Program code:
#include<stdio.h>

int main() {

int rows, cols, i, j, a[rows][cols], b[rows][cols], sum[rows][cols]

printf("Enter the number of rows: ");

scanf("%d", &rows);

printf("Enter the number of columns: ");

scanf("%d", &cols);

// Input elements for the first matrix

Name: Pranjal Gupta A


printf("Enter elements for the first matrix:\n");

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

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

printf("Element at [%d][%d]: ", i, j);

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

// Input elements for the second matrix

printf("Enter elements for the second matrix:\n");

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

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

printf("Element at [%d][%d]: ", i, j);

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

// Perform addition of the two matrices

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

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

sum[i][j] = a[i][j] + b[i][j];

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

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

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

printf("\n");

Name: Pranjal Gupta A


return 0;

Output:

Conclusion:
This program provides a clear example of how to perform matrix addition in C. It takes two
matrices as input, adds them element-by-element, and prints the resulting matrix. Matrix
addition is a fundamental operation in linear algebra and computer science, and this program
serves as a foundation for more advanced matrix operations like multiplication and
transposition.

Program 2:
Aim: Program to perform multiplication of two 2-D arrays

Name: Pranjal Gupta A


Theory:
1. Variable Declarations: Several variables are declared to store the dimensions of the matrices
(rows1, cols1, rows2, cols2), as well as loop control variables (i, j, k).rows1 and cols1 represent the
number of rows and columns of the first matrix. Rows2 and cols2 represent the number of rows and
columns of the second matrix.Matrices matrix1, matrix2, and resultMatrix are 2D arrays that store the
first matrix, second matrix, and the result of their multiplication, respectively.

3. Input Dimensions of Matrices:


The program prompts the user to input the dimensions (number of rows and columns) of both
matrices. These dimensions must be such that the number of columns in the first matrix
(cols1) equals the number of rows in the second matrix (rows2) for matrix multiplication to be
valid.
4. Multiplication Feasibility Check: The program checks whether the matrices can be
multiplied by ensuring that the number of columns in the first matrix equals the number of
rows in the second matrix (cols1 == rows2). If not, matrix multiplication is not possible, and
the program terminates.
5. Matrix Declaration: The program then declares three matrices:
matrix1[rows1][cols1]: stores the elements of the first matrix.matrix2[rows2][cols2]:
stores the elements of the second matrix.resultMatrix[rows1][cols2]: stores the result
of the matrix multiplication, initialized to zero.
6. Matrix Multiplication Logic: The multiplication of the two matrices is performed using
three nested for loops:The outermost loop iterates over the rows of the first matrix.The
middle loop iterates over the columns of the second matrix.The innermost loop
calculates the dot product of the rows of the first matrix and the columns of the
second matrix. This dot product is stored in the corresponding element of
resultMatrix[i][j].

Program Code:
#include<stdio.h>

int main() {

int rows1, cols1, rows2, cols2, i, j, k;

// Input the dimensions of the first matrix

printf("Enter the number of rows for the first matrix: ");

scanf("%d", &rows1);

printf("Enter the number of columns for the first matrix: ");

scanf("%d", &cols1);

Name: Pranjal Gupta A


// Input the dimensions of the second matrix

printf("Enter the number of rows for the second matrix: ");

scanf("%d", &rows2);

printf("Enter the number of columns for the second matrix: ");

scanf("%d", &cols2);

// Check if matrix multiplication is possible (number of columns in first matrix must equal
number of rows in second matrix)

if (cols1 != rows2) {

printf("Matrix multiplication is not possible.\n");

return 0;

// Declare two matrices and one result matrix

int matrix1[rows1][cols1], matrix2[rows2][cols2], resultMatrix[rows1][cols2];

// Initialize the result matrix to zero

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

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

resultMatrix[i][j] = 0;

// Input elements for the first matrix

printf("Enter elements for the first matrix:\n");

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

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

printf("Element at [%d][%d]: ", i, j);

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

Name: Pranjal Gupta A


// Input elements for the second matrix

printf("Enter elements for the second matrix:\n");

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

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

printf("Element at [%d][%d]: ", i, j);

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

// Matrix multiplication logic

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

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

for (k = 0; k < cols1; k++) {

resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];

// Display the result matrix (product of matrix1 and matrix2)

printf("\nResultant matrix after multiplication:\n");

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

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

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

printf("\n");

return 0;

Output:

Name: Pranjal Gupta A


Conclusion:
The matrix multiplication program demonstrates how to multiply two 2-D arrays (matrices) by
following specific mathematical rules. The key takeaway is that matrix multiplication is only
possible when the number of columns in the first matrix equals the number of rows in the
second matrix. The resulting matrix will have dimensions equal to the number of rows of the first
matrix and the number of columns of the second matrix.

Program 3:
Aim: Program to create a multi-level menu using switch cases that perform various basic
mathematical operations (Add, Subtract, Divide, Multiply, Exponent).

Theory:
1. Variable Declaration:

Name: Pranjal Gupta A


int num1, num2, sum, sub, mul: These integer variables are declared to store the input
numbers (num1, num2) and the results of the arithmetic operations (sum, sub, mul).
float div: The div variable is declared as a float to store the result of the division
operation. Since division may result in decimal values, a floating-point variable is
necessary.
char operator: This variable is declared to store the arithmetic operator (+, -, *, /) entered
by the user.

2. User Input:
The program uses the scanf() function to take input from the user:
scanf("%d", &num1); takes the first integer.
scanf("%d", &num2); takes the second integer.
scanf("%c", &operator); takes the operator, but note that there are multiple scanf() calls
for the operator due to the newline character issue explained below.

3. Switch Statement:
The switch statement evaluates the value of the operator variable and executes the
corresponding case:
case '+': Adds the two numbers and stores the result in sum.
case '-': Subtracts the second number from the first and stores the result in sub.
case '*': Multiplies the two numbers and stores the result in mul.
case '/': Divides the first number by the second, storing the result in div. Before
performing the division, the program checks if the second number (num2) is zero to
prevent a division by zero error.
Each case includes a break; statement to exit the switch block once the operation is
performed.
Division by Zero Check
if (num2 == 0): Before performing the division, the program checks if the second number
is zero. If it is, it prints "Not divisible," preventing a runtime error.
If num2 is not zero, the program performs the division and prints the result.

4. printf() for Output:


After each arithmetic operation, the program prints the result:
Addition (+): printf("The sum of two = %d", sum);
Subtraction (-): printf("The sub of two = %d", sub);
Multiplication (*): printf("The sum of two = %d", mul); (Note: this label should ideally be
changed to "The product of two" for clarity.)
Division (/): printf("The sum of two = %f", div); is used to print the floating-point result of
division.
Module(%): printf(“expo: %d”,&expo);

Program Code:
#include<stdio.h>

int main()

Name: Pranjal Gupta A


{

int num1,num2,sum,sub,mul;

float div;

char operator;

printf("Enter the first number: ");

scanf("%d",&num1);

printf("Enter the second number: ");

scanf("%d",&num2);

printf("Enter the operator: ");

scanf("%c",&operator);

scanf("%c",&operator);

scanf("%c",&operator);

switch (operator){

case '+': sum=num1+num2;

printf("The sum of two = %d",sum);

break;

case '-': sub=num1-num2;

printf("The sub of two = %d",sub);

break;

case '*': mul=num1*num2;

printf("The sum of two = %d",mul);

break;

case '/': div=num1/num2;

if(num2==0)

printf("Not divisible");

else

printf("The sum of two = %f",div);

break;

case ‘%’:

Name: Pranjal Gupta A


expo=a%b;

printf(“expo: %d”,&expo);

return 0;

Output:

Name: Pranjal Gupta A


Conclusion:
This program showcases the use of a switch statement for handling multiple cases, user input,
arithmetic operations, and error handling for division by zero. It demonstrates the fundamental
control structures of C, which are important for solving complex problems in a structured
manner.

Program 4:
Aim: Program to implement linear search in a 1-D array
Theory:
1.Array Declaration and Initialization:

Name: Pranjal Gupta A


The array marks[10] is declared and initialized with 10 integer values. This array
represents the collection of data (marks in this case) that the program will search
through.

2.For Loop for Traversal:

A for loop is used to iterate over the elements of the array.

The loop starts at index 0 and continues until it reaches the last index, 9 (since array indexing
starts from 0).

3. Conditional Check (if statement):

Inside the loop, the program checks whether the current element in the array (marks[i]) is
equal to 35.

If the condition is true, the program prints the index i where the element 35 is located.

The program searches through the array marks, which contains 10 elements. It compares
each element with 35 and prints the index where 35 is found. In this example, 35 is present at
index 4, so the output will be: 4

Program Code:
#include

int main()

int marks[10] = {78, 56, 65, 24, 35, 54, 21, 29, 89, 95};

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

if (marks[i] == 35)

printf("Element is present at index: %d ", i);

return 0;

Output:

Name: Pranjal Gupta A


Conclusion:
This program effectively illustrates how to traverse an array using a loop and find the index of a
specific element by applying conditional logic (if statement). It introduces basic array
operations and searching techniques in C.

Name: Pranjal Gupta A


Name: Pranjal Gupta A
Name: Pranjal Gupta A

You might also like