0% found this document useful (0 votes)
91 views68 pages

C Programming Lab Manual

This is C programming lab manual.
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)
91 views68 pages

C Programming Lab Manual

This is C programming lab manual.
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/ 68

Mahatma Gandhi Mission University

University Department of information and Technology

LAB MANUAL

C Programming

for

First Year Students


B.Tech. IT / AIML / Data Science

Mahatma Gandhi Mission University


University Department of information and Technology,
N-6, Cidco, Aurangabad, Maharashtra 431001
website: www.mgmu.ac.in
FORWARD

It is my great pleasure to present this laboratory manual for Second year


engineering students for the subject of Information Technology.
As a student, many of you may be wondering with some of the questions in your
mind regarding the subject and exactly what has been tried is to answer through
this manual.
As you may be aware that MGM has already been awarded with ISO 9001:2000
certification and it is our endure to technically equip our students taking the
advantage of the procedural aspects of ISO 9001:2000 Certification.
Faculty members are also advised that covering these aspects in the initial stage
itself, will greatly relieve them in future as much of the load will be taken care by
the enthusiasm energies of the students once they are conceptually clear.

Dr. H. S. Shinde
Dean Engineering
LABORATORY MANUAL CONTENTS

This manual is intended for the Second year students of Computer Science and
Engineering in the subject of Programming in C. This manual typically contains
practical/Lab Sessions related Programming. In C programming covering various
aspects related to the subject to enhance understanding.

Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and
conceptual visualization of theoretical aspects covered in the books.

Good Luck for your Enjoyable Laboratory Sessions

Mr. Ashish K. Bhise Dr. S. C. Tamane


Ms. Sushma Adsul HOD,IT
Asst. Prof., IT Dept.
DOs and DON’Ts in Laboratory:

1. Make an entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting from
their left to right.
3. All the students are supposed to enter the terminal number in the logbook.
4. Do not change the terminal on which you are working.
5. All the students are expected to get at least the algorithm of the
program/concept to be implemented.
6. Strictly observe the instructions given by the teacher/Lab Instructor.

Instruction for Laboratory Teachers:

1. Submissions related to whatever lab work has been completed should be


done during the next lab session. The immediate arrangements for printouts
related to submission on the day of practical assignments.
2. Students should be taught to take the printouts under the observation of the
lab teacher.
3. The promptness of submission should be encouraged by way of marking
and evaluation patterns that will benefit the sincere students.
Vision of UDICT

The UDICT shall establish a center-of-excellence with social and global


approaches for the development of trained human resources with professional
approaches to innovation, entrepreneurship, and knowledge of emergent
technologies for industry and research in diverse domains.

Mission of UDICT

The UDICT shall


1. Empower students with human values, environment-friendly qualities
and ethical approaches.
2. Create technocrats for a sustainable growth in the industrial sector with
an interdisciplinary aptitude.
3. Hone their skills for becoming experts with state-of-art knowledge in
social perspectives and research directions.
Program Outcomes:

PO1. Engineering Knowledge


PO2. Problem Analysis
PO3. Design/Development of Problem
PO4. Conduct Investigation of Complex Problem
PO5. Modern Tool Usage
PO6. The Engineer and society
PO7. Environment and Sustainability
PO8. Ethics
PO9. Individual and Team work
PO10. Communication
PO11. Project Management
PO12. Lifelong Learning

Program Educational Objectives

1. PEO1. The graduates will utilize their expertise in the IT industry and
solve industry technological problems.
2. PEO2. Graduates should excel in engineering positions in industry
and other organizations that emphasize design & implementation of
IT applications.
3. PEO3. Graduates will be innovators & professionals in
technology development, deployment & system implementation.
4. PEO4. Graduates will be pioneers in engineering, engineering
management, research and higher education.
5. PEO5. Graduates will be good citizens & cultured human being
with full appreciation of of IT professional ethical & social
responsibilities
Program Specific Outcomes

1. PSO1. An ability to design, develop and implement computer


programs in the areas related to Algorithms, Multimedia, Website
Design, System Software, DBMS and Networking.
2. PSO2. Develop software systems that would perform tasks related to
Research, Education and Training and/or E governance.
3. PSO3. Design, develop, test and maintain application software that
would perform tasks related to information management and mobiles by
utilizing new technologies to an individual or organizations.
C Programming Course Objectives

In this course, students will learn about:

● Programming basics and the fundamentals of C


● Data types in C
● Mathematical and logical operations
● Using if statement and loops
● Arranging data in arrays
● Implementing pointers

C Programming Course Outcomes


After completing this course, you will be able to:

CO1. Understand and develop C programming using variables and data types..

CO2. Apply the concepts of looping, branching, and decision-making statements for a
given problem.

CO3.Implement strings in your C program.

CO4. Implement and perform operations using multidimensional arrays.

CO5.Apply code reusability with functions and pointers


B.Tech. First year
SEMESTER - I

Course Code: APS21ESP105 Title: Building Programming logic in C Lab


Teaching Scheme Examination Scheme
Theory: Mid Semester:
Tutorial Class Test:
Total credits: End Semester:
Duration of theory paper:

Suggestive List of Programs


Sr. No.
Name of the program
a) Write a C program to find the sum and average of three numbers.
1 b) Write a C program to find the sum of individual digits of a given positive
(Operators) integer.
a) Write a C program to generate the first n terms of the Fibonacci sequence
2 b) Write a C program to generate prime numbers between 1 to n.
(Control Statements) c) Write a C program to check if the given number is Armstrong or not
3 a) Write a C program to check whether the given number is perfect or not
(Control Statements) b) Write a C program to check whether the given number is strong or not
4 a) Write a C program to find the roots of a quadratic equation.
(Control Statements) b) Write a C program performing arithmetic operations using switch
statements.
5 a) Write a C program to perform addition of two matrices.
(Arrays) b) Write a C program using a function to perform multiplication of two
matrices.
6 a) Write a C program to find the largest and smallest number in a list of
(Arrays) integers.
b) Write a C program to Sort the Array in an Ascending Order.
c) Write a C program to find whether the given matrix is symmetric or not.
7 a) a) Write a C program to use a function to insert a sub-string into a given main
(Functions) string from a given position.
b) b) Write a C program to swap the values of two variables using
d) (i) Call by value (ii) Call by reference
8 e) Write a C program to find factorial of a given integer using non-recursive
(Functions) function
f) Write a C program to find factorial of a given integer using recursive
function
9 a) Write a C program to find GCD of two integers by using a recursive
(Functions) function.
b) Write a C program to find GCD of two integers by using non-recursive
function.
a) Write a C program using user-defined functions to determine whether the
(Functions) given string is palindrome or not.
10 b) Write a C program that displays the position or index in the main string S
where the sub string T begins, or - 1 if S doesn't contain T.
a) Write a C program to count the number of lines, words and characters in a
11 given text.
(Pointers) b) Write a C program to find the sum of integer array elements using pointers.
12 a) Write a C Program to Calculate Total and Percentage marks of a student
(Structure-Union) using structure.
Experiment No. 1

Aim:- (a) Write a C program to find the sum and average of three numbers.

Theory:

Before we begin with our first C program do remember the following rules that are applicable to
all C programs:
(a) Each instruction in a C program is written as a separate statement. Therefore a complete C
program would comprise a series of statements.
(b) The statements in a program must appear in the same order in which we wish them to be
executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of
control to a statement, which is out of sequence.
(c) Blank spaces may be inserted between two words to improve the readability of the statement.
However, no blank spaces are allowed within a variable, constant or keyword.
(d) All statements are entered in small case letters.
(e) C has no specific rules for the position at which a statement is to be written. That’s why it is
often called a free-form language.
(f) Every C statement must end with a ;. Thus ; acts as a statement terminator. Let us now write
down our first C program.

Compilation and Execution

Assuming that you are using a Turbo C or Turbo C++ compiler, here are the steps that you need
to follow to compile and execute your first C program…
(a) Start the compiler at C> prompt.
(b) The compiler (TC.EXE is usually present in C:\TC\BIN directory).
( c) Select New from the File menu.
(d) Type the program. Save the program using F2 under a proper name (say Program1.c).
(e) Use Ctrl + F9 to compile and execute the program. Use Alt + F5 to view the output.
Flowchart:

Program:
#include <stdio.h>
int main()
{
int a, b, c, sum;
float avg;
// Asking for input
printf("Enter 3 numbers: \n");
scanf("%d %d %d", &a, &b, &c);
// Calculating sum
sum = a + b + c;
// Calculating average of 3 numbers
avg = sum / 3;
// Displaying output
printf("Sum = %d \n", sum);
printf("Average = %.2f", avg);
return 0;
}

Output:
Enter 3 numbers:
3
5
7
Sum = 15
Average = 5.00

Aim:- (b) Write a C program to find the sum of individual digits of a given positive integer.

Flowchart
Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0;
printf("enter a +ve integer"); // enter a integer value
scanf("%d",&n);
while(n>0) // checks the condition
{
sum=sum+n%10; // sum + remainder value
n=n/10;
}
printf("sum of individual digits of a positive integer is %d",sum); // prints the sum of individual
digits
}

Output:
enter a +ve integer456
sum of individual digits of a positive integer is 15
Experiment No. 2

Aim:- Write a C program to generate the first n terms of the Fibonacci sequence.

Theory:

C has three major decision making instructions—the if statement, the if-else statement, and the
switch statement. A fourth, somewhat less important structure is the one that uses conditional
operators. In this chapter we will explore all these ways (except switch, which has a separate
chapter devoted to it, later) in which a C program can react to changing circumstances.
A decision control instruction can be implemented in C using:
(a) The if statement
(b) The if-else statement
(c) The conditional operators

C uses the keyword to implement the decision control instruction. The general form of if
statement looks like this:

if ( this condition is true )


execute this statement ;

The if-else Statement


The if statement by itself will execute a single statement, or a group of statements, when the
expression following if evaluates to true. It does nothing when the expression evaluates to false.
Can we execute one group of statements if the expression evaluates to true and another group of
statements if the expression evaluates to false? Of course! This is what is the purpose of the else
statement that is demonstrated in the following example:

For Loop

Three steps—initialization, testing and incrementation


—required for the loop construct have now been incorporated in the for statement. Let us now
examine how the for statement gets executed:
− When the for statement is executed for the first time, the value of
count is set to an initial value 1. − Now the condition count <= 3 is
tested. Since count is 1 the condition is satisfied and the body of the
loop is executed for the first time.
− Upon reaching the closing brace of for, control is sent back to the
for statement, where the value of count gets incremented by 1.
− Again the test is performed to check whether the new value of
count exceeds 3.
− If the value of count is still within the range 1 to 3, the
statements within the braces of for are executed again.
− The body of the for loop continues to get executed till count
doesn’t exceed the final value 3. − When count reaches the value 4 the
control exits from the loop and is transferred to the statement (if
any) immediately after the body of for.

Program:
#include <stdio.h>
int main()
{
int i, n;
// initialize first and second terms
int t1 = 0, t2 = 1;
// initialize the next term (3rd term)
int nextTerm = t1 + t2;
// get no. of terms from user
printf("Enter the number of terms: ");
scanf("%d", &n);
// print the first two terms t1 and t2
printf("Fibonacci Series: %d, %d, ", t1, t2);
// print 3rd to nth terms
for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}

Output:
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

b) Write a C program to generate prime numbers between 1 to n.

Flowchart
Program:

#include<stdio.h>
void main()
{
int i, num, n, count;
printf("Enter the range: ");
scanf("%d", &n);
printf("The prime numbers in between the range 1 to %d:",n);
for(num = 1;num<=n;num++){
count = 0;
for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}
if(count==0 && num!= 1)
printf("%d ",num);
}
}

Output:
Enter the range:50
The prime numbers in between the range 1 to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

c) Write a C program to check if the given number is Armstrong or not

Flowchart
Program

#include <stdio.h>
int main() {
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;
while (originalNum != 0) {
// remainder contains the last digit
remainder = originalNum % 10;
result += remainder * remainder * remainder;
// removing last digit from the orignal number
originalNum /= 10;
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;
}

Output:
Enter an integer: 1634
1634 is an Armstrong number.
Experiment No. 3

Aim:- 3 a) Write a C program to check whether the given number is perfect or not

Flowchart:

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
// declare and initialize the variables
int num, rem, sum = 0, i;
// take input from the user.
printf("Enter a number\n");
scanf("%d", &num);
// find all divisors and add them
for(i = 1; i < num; i++)
{
rem = num % i;
if (rem == 0)
{
sum = sum + i;
}
}
if (sum == num)
printf(" %d is a Perfect Number");
else
printf("\n %d is not a Perfect Number");
getch();
}

Output:
Enter a number
28
Entered number is a Perfect Number

b) Write a C program to check whether the given number is strong or not

#include<stdio.h>
int main(){
int n,i;
int fact,rem;
printf("Enter a number : ");
scanf("%d",&n);
printf("");
int sum = 0;
int temp = n;
while(n){
i = 1,fact = 1;
rem = n % 10;
while(i <= rem){
fact = fact * i;
i++;
}
sum = sum + fact;
n = n / 10;
}
if(sum == temp)
printf("%d is a strong number",temp);
else
printf("%d is not a strong number",temp);
return 0;
}
Output:

Enter a number 145


Number is a strong
Experiment No. 4

Aim:-
4 a) Write a C program to find the roots of a quadratic equation.

Theory : Quadratic equation is an equation in the form ax2 + bx + c = 0


where a ≠ 0.
• For the quadratic function f(x) = a (x + p) 2 + q, the graph of y = f(x)
has a turning point at (−p, q)
• For the quadratic equation ax2 + bx + c = 0, the expression b2 – 4ac is called the discriminant.
The value of the discriminant shows how many roots f(x) has:
- If b2 – 4ac > 0 then the quadratic function has two distinct real roots.
- If b2 – 4ac = 0 then the quadratic function has one repeated real root.
- If b2 – 4ac < 0 then the quadratic function has no real roots.

Roots are evaluated by formula


2
x = (-b ± √ (b - 4ac) )/2a

So,
Flowchart:

Program:

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

int main () {
float a,b,c,r1,r2,d;

printf ("Enter the values of a b c: ");


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

d= b*b - 4*a*c;
if (d>0) {
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf ("The real roots = %f %f", r1, r2);
}
else if (d==0) {
r1 = -b/(2*a);
r2 = -b/(2*a);
printf ("Roots are equal =%f %f", r1, r2);
}
else
printf("Roots are imaginary");

return 0;
}
Output:
Case 1:
Enter the values of a b c: 1 4 3
The real roots = -3.000000 -5.000000
Case 2:
Enter the values of a b c: 1 2 1
Roots are equal =-1.000000 -1.000000
Case 3:
Enter the values of a b c: 1 1 4
Roots are imaginary

b) Write a C program performing arithmetic operations using switch statements.

Theory:

Decisions Using switch The control statement that allows us to make a decision from the number
of choices is called a switch, or more correctly a switch case-default, since these three keywords
go together to make up the control statement. They most often appear as follows:

switch ( integer expression )


{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}

Program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a, b, i;
printf("Enter Number 1 :--> ");
scanf("%d", &a);
printf("\nEnter Number 2 :--> ");
scanf("%d", &b);
do
{
printf("\nEnter 1 for 'Addition' ");
printf("\nEnter 2 for 'Subtraction' ");
printf("\nEnter 3 for 'Multiplication' ");
printf("\nEnter 4 for 'Division' \n");
printf("Enter 0 for Exit ");
printf("\nEnter your choice :--> ");
scanf("%d", &i);
switch(i)
{
case 0: break;
case 1:
printf("\na + b = %d\n", a + b);
break;
case 2:
printf("\na - b = %d\n", a - b);
break;
case 3:
printf("\na * b = %d\n", a * b);
break;
case 4:
printf("\na / b = %f\n", a / b);
break;
default:
printf("\nEnter valid option\n");
}
} while(i != 0);
}

Output:
Enter Number 1 :--> 8

Enter Number 2 :--> 3

Enter 1 for '+'


Enter 2 for '-'
Enter 3 for '*'
Enter 4 for '/'
Enter 0 for Exit
Enter your choice :--> 1

a + b = 11

Enter 1 for '+'


Enter 2 for '-'
Enter 3 for '*'
Enter 4 for '/'
Enter 0 for Exit
Enter your choice :--> 2
Experiment No. 5

Aim:-
5 a) Write a C program to find factorial of a given integer using non-recursive function

Theory:
A function is a self-contained block of statements that perform a coherent task of some kind.
Every C program can be thought of as a collection of these functions. As we noted earlier, using
a function is something like hiring a person to do a specific job for you. Sometimes the
interaction with this person is very simple; sometimes it’s complex

A function definition in C programming consists of a function header


and a function body. Here are all the parts of a function −

​ Return Type − A function may return a value. The return_type is


the data type of the value the function returns. Some functions
perform the desired operations without returning a value. In
this case, the return_type is the keyword void.

​ Function Name − This is the actual name of the function. The
function name and the parameter list together constitute the
function signature.

​ Parameters − A parameter is like a placeholder. When a function
is invoked, you pass a value to the parameter. This value is
referred to as an actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a
function. Parameters are optional; that is, a function may
contain no parameters.

​ Function Body − The function body contains a collection of
statements that define what the function does.

Flowchart:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n, i;
unsigned long long factorial = 1;

printf("Enter a number to find factorial: ");


scanf("%d",&n);

// show error if the user enters a negative integer


if (n < 0)
printf("Error! Please enter any positive integer number");

else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of Number %d = %llu", n, factorial);
}

getch();
}
Output:
Enter a number to find factorial:5
Factorial of Number 5 = 20

b) Write a C program to find factorial of a given integer using recursive function

Flowchart
Figure: Recursion

Program:

#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}

long int multiplyNumbers(int n) {


if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}

Output:
Enter a positive integer: 6
Factorial of 6 = 720

Experiment No. 6

Aim:-
6 a) Write C program to find GCD of two integers by using recursive function.

Theory:

Recursion: A function can call itself. Such a process is called ‘recursion’.

Flowchart:
#include <stdio.h>
int hcf(int n1, int n2); //function declaration
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);

printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2)); // function call


return 0;
}
int hcf(int n1, int n2) //function definition
{ if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1; }

Output:
Enter two positive integers: 366
60
G.C.D of 366 and 60 is 6.

b) Write C program to find GCD of two integers by using non-recursive function.


Program:

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

int nonrecgcd(int x, int y);


int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, nonrecgcd(n1, n2));
return 0;
}

int nonrecgcd(int x, int y)


{
int z;
while(x % y != 0)
{
z = x % y;
x = y;
y = z;
}
return(y);
}

Output:
enter the two numbers:10 30
GCD of 10
Experiment No. 7

Aim:-

7a) Write a C program to find the largest and smallest number in a list of integers.

Theory:

Array
An array in C is a fixed-size collection of similar data items stored in contiguous memory
locations. 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.

Syntax of Array Declaration

data_type array_name [size];


or
data_type array_name [size1] [size2]...[sizeN];

where N is the number of dimensions.

Flowchart:

#include<stdio.h>
int main()
{
int i, large,n;
int a[n];
//int a[5]={4,3, 5,8,7};
printf("Enter count for array elements");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

large=a[0];

for(i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
}
printf("largest no. is: %d",large);
}

Output:
Enter count for array elements 5
Enter array elements 3 6 9 4 2
largest no. is: 9
Program:

#include<stdio.h>
int main()
{
int i,small,n;
int a[n];
//int a[5]={4,3, 5,8,7};
printf("Enter count for array elements");
scanf("%d",&n);
printf("Enter array elements");

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

small=a[0];

for(i=1;i<n;i++)
{
if(a[i]<small)
small=a[i];
}
printf("Smallest no. is: %d",small);
}

Output:
Enter count for array elements 5
Enter array elements 6 2 8 4 9
Smallest no. is: 2
b) Write a C program to Sort the Array in an Ascending Order.

Flowchart:
#include <stdio.h>
void main (){
int num[20];
int i, j, a, n;
printf("enter number of elements in an array");
scanf("%d", &n);
printf("Enter the elements");
for (i = 0; i < n; ++i)
scanf("%d", &num[i]);

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


{
for (j = i + 1; j < n; ++j)
{
if (num[i] > num[j])
{
a = num[i];
num[i] = num[j];
num[j] = a;
}
}
}
printf("The numbers in ascending order is:");
for (i = 0; i < n; ++i){
printf("%d", num[i]);
}
}

Output:
enter number of elements in an array
5
Enter the elements
12
23
89
11
22
The numbers in ascending order is:
11
12
22
23
89

c) Write a C program to find whether the given matrix is symmetric or not.

#include <stdio.h>
int main() {
int A[3][3], B[3][3];
int row, col, isSym;
// Take a matrix A as input from user
printf("Enter the elements in matrix of size 3x3: \n");
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
scanf("%d", &A[row][col]);
}
}
// Finds the transpose of matrix A
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
// Stores each row of matrix A to each column of matrix B
B[row][col] = A[col][row];
}
}

// Checks whether matrix A is equal to its transpose or not


isSym = 1;
for (row = 0; row < 3 && isSym; row++) {
for (col = 0; col < 3; col++) {
if (A[row][col] != B[row][col]) {
isSym = 0;
break;
}
}
}

// If the given matrix is symmetric.


if (isSym == 1) {
printf("\n Matrix is Symmetric. \n");

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


for (col = 0; col < 3; col++) {
printf("%d ", A[row][col]);
}

printf("\n");
}
} else {
printf("\n Matrix is not Symmetric.");
}
return 0;
}

Output:
Enter elements in matrix of size 3×3:
123
345
456

Matrix is not Symmetric.


Experiment No. 8

Aim:- 8 a) Write a C program to perform addition of two matrices.

Theory:
Two-Dimensional Array in C
The two-dimensional array is also called a matrix

The basic form of declaring a 2D array with x rows and y columns in C is shown below.
Syntax:
data_type array_name[x][y];
where,
● data_type: Type of data to be stored in each element.
● array_name: name of the array
● x: Number of rows.
● y: Number of columns.

We can declare a two-dimensional integer array say ‘x’ with 10 rows and 20 columns as:

● Example:

int x[10][20];
Program:
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}

return 0;
}

Output:

Enter the number of rows (between 1 and 100): 2


Enter the number of columns (between 1 and 100): 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
b) Write a C program using function to perform multiplication of two matrices.

Program:

#include <stdio.h>
#include <stdlib.h>
#define r1 2
#define c1 3
#define r2 3
#define c2 2
void Matrix_mul (int mat1[][c1], int mat2[][c2])
{
int mul[r1][c2];
printf ("Multiplication of given two matrices is:\n");
for (int i = 0; i < r1; i++)
{
for (int j = 0; j < c2; j++)
{
mul[i][j] = 0;
for (int k = 0; k < r2; k++)
{
mul[i][j] += mat1[i][k] * mat2[k][j];
}
printf ("%d\t", mul[i][j]);
}
printf ("\n");
}
}

int main ()
{
int mat1[r1][c1] = { {0, 1, 2}, {3, 4, 5} };
int mat2[r2][c2] = { {1, 2}, {3, 4}, {5, 6} };
int mul[r1][c2], i, j, k;

printf ("matrix 1 is :\n");


for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
printf ("%d ", mat1[i][j]);
if (j == 3 - 1)
{
printf ("\n\n");
}
}
}
printf ("matrix 2 is :\n");
for (i = 0; i < r2; i++)
{
for (j = 0; j < c2; j++)
{
printf ("%d ", mat2[i][j]);
if (j == 2 - 1)
{
printf ("\n\n");
}
}
}

Matrix_mul (mat1, mat2);


return 0;
}

Output:

matrix 1 is :

0 1 2

3 4 5

matrix 2 is :

1 2

3 4

5 6

The product of the two matrices is:

13 16

40 52
Experiment No. 9

Aim:- 9a) Write a C program to use function to insert a sub-string in to given main string
from a given Position.

Theory:

String:

The way a group of integers can be stored in an integer array, similarly a group of characters can
be stored in a character array. Character arrays are many a time also called strings. Many
languages internally treat strings as character arrays, but somehow conceal this fact from the
programmer. Character arrays or strings are used by programming languages to manipulate text,
such as words and sentences. A string constant is a one-dimensional array of characters
terminated by a null ( ’\0’ ). For example,

char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;

Each character in the array occupies 1 byte of memory and the last character is always ’\0’. What
character is this? It looks like two characters, but it is actually only one character, with the \
indicating that what follows it is something special. ’\0’ is called a null character. Note that ’\0’
and ’0’ are not same. ASCII value of ’\0’ is 0, whereas ASCII value of ’0’ is 48. Figure 15.1
shows the way a character array is stored in memory. Note that the elements of the character
array are stored in contiguous memory locations. The terminating null (’\0’) is important,
because it is the only way the functions that work with a string can know where the string ends.
In fact, a string not terminated by a ’\0’ is not really a string, but merely a collection of
characters.

Figure: String
C String Declaration Syntax
Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic
syntax for declaring a string.
char string_name[size];
In the above syntax string_name is any name given to the string variable and size is used to
define the length of the string, i.e the number of characters strings will store.

Program: Write a C program to use function to insert a sub-string in to given main


string from a given position.

i) To insert a sub-string in to a given main string from a given position.

Algorithm:
Step 1:
Start
Step 2:
read main string and sub string
Step 3:
find the length of main string(r)
Step 4:
find length of sub string(n)
Step 5:
copy main string into sub string
Step 6:
read the position to insert the sub string(p)
Step 7:
copy sub string into main string from position p - 1
Step 8:
copy temporary string into main string from position p +
n - 1
Step 9: print the strings
Step 10: Stop
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
int l1, l2, n, i;
clrscr();
puts("Enter the string 1\n");
gets(str1);
l1 = strlen(str1);
puts("Enter the string 2\n");
gets(str2);
l2 =
(str2);
printf("Enter the position where the string is to be
inserted\n");
scanf("%d", &n);
for(i = n; i < l1; i++)
{
str1[i + l2] = str1[i];
}
for(i = 0; i < l2; i++)
{
str1[n + i] = str2[i];
}
str2[l2 + 1] = '\0';
printf("After inserting the string is %s", str1);
getch();
}

Input & Output:


Enter the string 1
sachin
Enter the string 2
tendulkar
Enter the position where the string is to be inserted
4
After inserting the string is sachtendulkarin
#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[50];
int l1, l2, n, i;
printf("Enter the main string: ");
scanf("%s", str1);
printf("Enter the sub-string: ");
scanf("%s", str2);
printf("Enter the position where the item has to be inserted: ");
scanf("%d", &n);
l1 = strlen(str1);
l2 = strlen(str2);
for (i = l1; i >= n; i--) {
str1[i + l2] = str1[i];
}
for (i = 0; i < l2; i++) {
str1[n + i] = str2[i];
}
printf("After inserting, the string is: %s\n", str1);
return 0;
}

b) Write a C program to swap the values of two variables using (i) Call by value (ii) Call by
reference

The two types of function calls—call by value and call by reference. Arguments can generally be
passed to functions in one of the two ways:
(a) sending the values of the arguments
(b) sending the addresses of the arguments

In the first method, the ‘value’ of each of the actual arguments in the calling function is copied
into corresponding formal arguments of the calling function.
In the second method (call by reference), the addresses of actual arguments in the calling
function are copied into the formal arguments of the called function. This means that, using these
addresses, we would have access to the actual arguments and hence we would be able to
manipulate them.

b) Write a C program to swap the values of two variables using


d) (i) Call by value (ii) Call by reference

#include <stdio.h>
void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}

int main()
{
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(x,y);
printf("Values after swap: x = %d, y = %d", x,y);
}

Output:

Values before swap: x = 10, y = 11


Values after swap: x = 10, y = 11

#include <stdio.h>
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
int main(){
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(&x,&y);
printf("Values after swap: x = %d, y = %d", x,y);
}

Output:

Values before swap: x = 10, y = 11


Values after swap: x = 11, y = 10
Experiment No. 10

Aim:
10a) Write a C program using user-defined functions to determine whether the given string
is palindrome or not.

Flowchart

#include <stdio.h>
#include <string.h>
int main()
{
char str[] = { "abbba" };
// Start from first and
// last character of str
int l = 0;
int h = strlen(str) - 1;
// Keep comparing characters
// while they are same
while (h > l) {
if (str[l++] != str[h--]) {
printf("%s is not a palindrome\n", str);
return 0;
// will return from here
}
}

printf("%s is a palindrome\n", str);


return 0;
}

Output:

abbba is a palindrome

b) Write a C program that displays the position or index in the main string S where the sub
string T begins, or - 1 if S doesnot contain T.
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[30], t[20];
char *found;
clrscr();
/* Entering the main string */
puts("Enter the first string: ");
gets(s);
/* Entering the string whose position or index to be displayed */
puts("Enter the string to be searched: ");
gets(t);
/*Searching string t in string s */
found=strstr(s,t);
if(found)
printf("Second String is found in the First String at %d position.\n",found-s);
else
printf("-1");
getch();
}
Output:
Enter the first string:
sridhar siricilla
Enter the string to be searched:
siri
Second String is found in the First String at 8 position.

11a) Write C program to count the number of lines, words and characters in a given text.

#include<stdio.h>
int main()
{
// declare variables
char str[200];
int line, word, ch;
// initialize count variables with zero
line = word = ch = 0;
// read multiline string
printf("Enter string terminated with ~ :\n");
scanf("%[^~]", str);
// check every character
for(int i=0; str[i]!='\0'; i++)
{
// if it is new line then
// one line and one word completed
if(str[i]=='\n')
{
line++;
word++;
}
// else it is a character
else
{
// if character is space or tab
// then one word is also completed
if(str[i]==' '||str[i]=='\t')
{
word++;
ch++;
}

// it was not '\n', sapace or tab


// it is a normal character
else {
ch++;
}
}
}
// display count values
printf("\nCharacter counts = %d\n", ch);
printf("Word counts = %d\n", word);
printf("Line counts = %d\n", line);

return 0;
}
Output:

Enter string terminated with ~ :


Hi ,
Come here
Get learned coding
~Character counts = 31
Word counts = 7
Line counts = 3

b) Write a C program to find the sum of integer array elements using pointers.

#include <stdio.h>

#include <malloc.h>

void main(){

int i, n, sum = 0;

int *ptr;
printf("Enter size of array :

");

scanf("%d", &n);

ptr = (int *) malloc(n * sizeof(int));

printf("Enter elements in the List

");

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

scanf("%d", ptr + i);

//calculate sum of elements

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

sum = sum + *(ptr + i);


}

printf("Sum of all elements in an array is = %d

", sum);

return 0;

Output

When the above program is executed, it produces the following result


Enter size of array:

Enter elements in the List

12
13

14

15

16

Sum of all elements in an array is = 7

12 a) Write a C Program to Calculate Total and Percentage marks of a student using


structure.2

#include <stdio.h>

#include <conio.h>

struct student

int rl;

char nm[20];
int m1;

int m2;

int m3;

int t;

float per;

};

void main()

struct student a;

clrscr();

printf(" Enter RollNo, Name amd three sub marks\n");

scanf("%d%s%d%d%d", &a.rl, &a.nm, &a.m1, &a.m2, &a.m3);


a.t = a.m1 + a.m2 + a.m3;

a.per = a.t / 3.0;

printf("rollno=%d\n", a.rl);

printf("Name=%sk\n", a.nm);

printf("m1=%d\n", a.m1);

printf("m2=%d\n", a.m2);

printf("m3=%d\n", a.m3);

printf("total=%d\n", a.t);

printf("per=%f\n", a.per);

getch();

Enter RollNo, Name and three sub marks


12 rama 30 40 50

rollno=12

Name=rama

m1=30

m2=40

m3=50

total=120

per=40.000000

You might also like