0% found this document useful (0 votes)
10 views41 pages

23escs11 Lab Manual

The document is a laboratory manual for the 'Principles of Programming Using C' course at Dayananda Sagar Academy of Technology and Management for the academic year 2023-2024. It outlines the vision, mission, quality policy, objectives, and goals of the institute, along with a detailed list of programming experiments and evaluation methods for students. The manual includes specific programming tasks such as creating a simple calculator, computing roots of quadratic equations, and implementing various algorithms in C.

Uploaded by

Mahesh Kini
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)
10 views41 pages

23escs11 Lab Manual

The document is a laboratory manual for the 'Principles of Programming Using C' course at Dayananda Sagar Academy of Technology and Management for the academic year 2023-2024. It outlines the vision, mission, quality policy, objectives, and goals of the institute, along with a detailed list of programming experiments and evaluation methods for students. The manual includes specific programming tasks such as creating a simple calculator, computing roots of quadratic equations, and implementing various algorithms in C.

Uploaded by

Mahesh Kini
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/ 41

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY

AND MANAGEMENT
Udayapura, Kanakapura Road, Opp. Art of Living, Bangalore – 560082
(Affliated to VTU, Belagavi, Approved by AICTE, New Delhi, Accredited by NBA, New Delhi)
(Autonomous to VTU)

2023-2024
Principals of Programming Using C
Laboratory Manual
(23ESCS11)

Compiled by:
Asst. Prof. Shreenidhi B S

Dr. M Ravishankar
Principal, DSATM
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &
MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New
Delhi, Accredited by NBA for 3 years, New Delhi)

VISION OF THE INSTITUTE

To strive at creating the institution a center of highest caliber of learning, so as to create an


overall intellectual atmosphere with each deriving strength from the other to be the best of
engineers, scientists and mathematicians.

MISSION OF THE INSTITUTE


• To serve its region, state, the nation and globally by preparing students to make meaningful
contributions in an increasing complex global society.
• To encourage, reflection on and evaluation of emerging needs and priorities with state of art
infrastructure.
• To support research and services establishing enhancements in technical, health, economic,
human and cultural development.
• To establish inter disciplinary center of excellence.
• To increase the number of Doctorate holders to promote research culture on campus.
QUALITY POLICY

"We, at "Dayananda Sagar Academy of Technology and Management" are committed to


continually improve and deliver competitive quality technical education to the at most
satisfaction of student, their parents and potential employer."

OBJECTIVES & GOALS

1. Creating an academic environment to develop the younger generation and providing quality
professional engineering education at an affordable cost.
2. Create necessary infrastructure on a continuous basis the professional education with the changing
needs of society.
3. Optimum utilization of the infrastructure and resources to achieve excellence in the
engineering courses.
4. Monitor continuously the growth in technology parts of the world and address all aspects of
development of human resource (both from academic and supporting staff) and students to be in
tune with state of the art technology and engineering practices.
5. Facilitate greater Industry, Institute, and Interaction so as to empower the students with practical
knowledge.
6. Institute various quality assurance systems.
7. Adopting learning beyond curriculum process.
8. Initiate systems of learning which are based on enable students to acquire skills relevant to their
career.
9. To continuous monitor, asses evaluate the various academic programs adopting outcome-based
education.
COMPUTER PROGRAMMING LABORATORY
Outcome-Based Education (OBE) and Choice Based Credit System (CBCS)
(Effective from the academic year 2023 – 24)

Course Code 23ESCS11 CIE Marks 50


Teaching Hours/Week (L: T:P: S) 2:0:2:0 SEE Marks 50
Total Hours of Pedagogy -- Total Marks 100
Credits 03 Exam Hours 03

List of problems for which students should develop the program and execute in the
Laboratory

Sl. No. Experiments/Programs Page No.


1 Write a C program to implement a Simple Calculator. 1
a) Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate
2 messages. 4
b) Write a C program to print Pyramid of stars patterns using Looping
Implement Matrix multiplication and validate the rules of multiplication using C Program.
3 10
Write a C program for the following condition using Functions, Assume a Car servicing
Center. Every service request by the Car Service Center the given charges are levied along
with taxes.
a. Car water wash - Rs. 500 + 10% tax
b. Oil in the Engine must be at least 300 ml. If it goes below 300 ml
(Ask the user to input the current level of oil in the engine),
4 14
top up is done by the agency (the value of top up is given by the user so that level is at least
300 ml). Cost of 1 ml is Rs. 5 + 12.5% tax.
1. Define suitable variables to capture the above 2 parameters and corresponding taxes
2. Compute the total amount to be paid.
3. Display the total with 17 places which includes 7 places for fraction. The integer part of
the total must be prefixed with 0’s and a sign, if required.
Write a program in C using functions to swap two numbers using global variables concept
5 16
and call by reference concept.
Implement a C program to read the values from the user today’s date and your Date of birth
in the format dd-mm-yyyy. Consider your sleeping time 8 hours a day, read 12 hours and
spend 1.5 hours a day for eating. Calculate how many minutes have you spent as of this date
6 17
for Sleeping and Eating.
The number of years you have spent for reading as of this date (amount of time spent for
reading in years).
a) Write functions to implement string operations such as compare, concatenate, and find
7 string length. Use the parameter passing techniques. 19
b) Implement a C Program to check String is a Palindrome or Not
8 Write a C Program to Implement linear search and binary search. 24
9 Write a C Program to Implement Bubble Sort. 29
Write a C program to read employee information (Name, Designation, Salary) from the user
10 32
and write it to a file.
Write a C Program to input even & odd elements of an array in two separate arrays. The
11 program first finds the odd and even elements of the array. Then the odd elements of an array 34
are stored in one array and even elements of an array is stored in another array
Write a C program to define a structure to represent a cricketer's information (name, runs,
12 average). Read the data corresponding to N Cricketer's in a structure array. The space for the 36
array of structures should be determined at run-time by user input.
Open ended Programs
1 Develop a ‘C’ program to calculate the gravitational pull between two objects.
2 Demonstrate a simple units convertor for distance, temperature, and liquid volume.
3 Calculate the displacement for an automobile using pointers.
4 Demonstrate the use of an array of pointers.

CIE for Principles of Programming Using C (Integrated Professional Core Course (IPCC)):
This Course refers to professional theory core course integrated with practical. Credit for this course can be 03
and its Teaching Learning hours (L : T : P: PJ) can be considered as (2 : 0 : 2 : 0).
15 marks for the conduction of practical experiment and preparation of the Laboratory record, and 10 marks for
the test to be conducted after the completion of all the laboratory sessions.
On completion of every program in the laboratory, the student shall be evaluated including viva-voce and marks
shall be awarded on the same day.
Each program report can be evaluated for 15 marks (Write-up – 3 marks, Execution – 8 marks .and Viva – 4
marks)
The Laboratory test (duration 2 hours / 3 hours) after completion of all the programs shall be conducted for 50
marks and scaled down to 10 marks.
The theory part of the IPCC shall be evaluated both by CIE and SEE. The practical part shall be evaluated by
only CIE (no SEE). However, questions from the practical part of IPCC shall be included in the SEE question
paper. This course is common to all branches of first year B.E/B.Tech. 2023-24 regulation.
Note: L- Theory Lecture, T- Tutorial, P-Practical, PJ-Project, IPCC: Integrated Professional Core Course, CIE:
Continuous Internal Evaluation, SEE: Semester End Examination.
.
C PROGRAMMING LAB 23ESCS11

PROGRAM-1
Write a C program to implement a Simple Calculator
Procedure: This program takes an arithmetic operator +,-,*,/,% and two operands from the
user and performs the calculation on the two operands depending upon the operator entered by
the user.
Input: An operator and two operands.
Expected Output: Performs calculation and display result depending upon the operator.
ALGORITHM

Algorithm Calculator
Step 1: Start
Step 2: Read num1 and num2
Step 3: Enter the operator
Step 4: Evaluate operator wit case statements
Step 4.1: case ‘+’ : result = num1+num2
goto step 6
Print result
Step 4.2: case ‘-’ : result = num1-num2
goto step 6
Print result
Step 4.3: case ‘*’ : result = num1*num2
goto step 6
Print result
Step 4.4: case ‘/’ : result = (float)num1/(float)num2
goto step 6
Print result
Step 4.5: case ‘%’ : result = num1%num2
goto step 6
Print result
Step 5: Enter operator is invalid then
Print “Invalid Operation”
Step 6: Print result
Step 7: Stop

DSATM, Bangalore-82 Page 1


C PROGRAMMING LAB 23ESCS11

FLOWCHART

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1, num2;
float result=0;
char ch;

DSATM, Bangalore-82 Page 2


C PROGRAMMING LAB 23ESCS11

printf("Choose operation to perform (+,-,*,/,%): ");


scanf(" %c", &ch);

printf("Enter first number: ");


scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);

switch(ch)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*': result=num1*num2;
break;
case '/':result=(float)num1/(float)num2;
break;
case '%': result=num1%num2;
break;
default: printf("Invalid operation.\n");
exit(0);
}
printf("Result: %d %c %d = %f\n",num1,ch,num2,result); //display output on screen

OUTPUT:
Choose operation to perform (+,-,*,/,%): +
Enter first number: 10
Enter second number: 20
Result: 10 + 20 = 30.000000

Choose operation to perform (+,-,*,/,%): $


Enter first number: 1
Enter second number: 3
Invalid operation.

DSATM, Bangalore-82 Page 3


C PROGRAMMING LAB 23ESCS11

PROGRAM-2
a) Compute the roots of a quadratic equation by accepting the coefficients. Print
appropriate messages.
Procedure: The equation in the form ax2+bx+c=0 is called quadratic equation. Read the
coefficients a,b,c and calculate discriminant. Based on the discriminant value, calculate roots
and print them with suitable messages.
Input: Three coefficients of quadratic equation ax2+bx+c=0: a, b, c
Expected Output: This program computes all possible roots for a given set of coefficients with
appropriate messages. The possible roots are: Real and Equal roots, Real and distinct roots,
imaginary roots.
ALGORITHM

Algorithm: Quadratic_Equation [This algorithm takes three coefficients as input and compute
the roots]
Step 1: [Start of the algorithm]
Start
Step 2: [Read the coefficients]
Read non zero coefficients a,b,c
Step 3: [calculate the discriminant]
db*b-4*a*c
Step 4: [check if roots are real and equal]
if (d=0)
x1-b/(2*a)
x2-b/ (2*a)
Print “Roots are equal”
Print x1, x2
Go to step 7
Step 5: [check if roots are real and distinct]
If(d>0)
x1(-b+sqrt (d)/ (2*a))
x2(-b-sqrt (d)/ (2*a))
Print “Roots are real and distinct”
Print x1,x2
Go to step 7
Step 6: [check if roots are imaginary]
If(d<0)
x1-b/(2*a)
x2sqrt (fabs(d))/(2*a)
Print “ The roots are complex”
Print “Root1  “, x1+ix2
Print “ Root2“, x1-ix2

Step 7: [terminate the algorithm]


Stop

DSATM, Bangalore-82 Page 4


C PROGRAMMING LAB 23ESCS11

FLOWCHART

START

Read a,b,c

is a=0 ? Is a=0 and Print


b=0? Invalid
roots

d←b*b-4*a*c

is d=0 ? is d>0 ?

Print Print roots Print Roots Print Roots real


Real & distinct & imaginary
Linear real & equal

root1=-b/ (2*a) root1=(b+sqrt(d))/(2*a) real=-b/(2*a)


root1=-c/b
root1=(-b-sqrt(d))/(2*a) img=sqrt(fabs(d))/(2*a)
root1=root2

Print root1=real+img
Print
Print root2=real- img
root1
root1 and
root2

STOP

PROGRAM:
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,d,rpart,ipart,root1,root2;
printf("Enter three co-efficient\n");
scanf("%f%f%f",&a,&b,&c);

if(a==0 && b==0)

DSATM, Bangalore-82 Page 5


C PROGRAMMING LAB 23ESCS11

{
printf(“Invalid inputs”);

}
else if(a==0)
{
printf(“Linear Equation\n”);
root1=-c\b;
printf(“Root=%f\n”,root1);
}
else
{
d=(b*b)-(4*a*c);
if(d==0)
{
printf("The roots real and equal\n");
root1= -b/(2*a);
root2=root1;
printf("The roots are root1=%.3f and root2=%.3f\n",root1,root2);
}
else if(d>0)
{
printf("The roots are real and distinct\n");
root1=(-b+sqrt(d))/(2*a);
root2=(-b-sqrt(d))/(2*a);
printf("The roots are root1=%.3f and root2=%.3f\n",root1,root2);
}
else
{
printf("The roots are imaginary\n");
rpart=-b/(2*a);
ipart=2*(sqrt(fabs(d))/(2*a));
printf("The first root root1=%.3f+i%.3f\n",rpart,ipart);
printf("The second root root2=%.3f-i%.3f\n",rpart,ipart);
}
}
}

OUTPUT:
.....................................................................
Run1:
Enter three co-efficient
1
2
3

DSATM, Bangalore-82 Page 6


C PROGRAMMING LAB 23ESCS11

The roots are imaginary


The first root root1=-1.000+i2.828
The second root root2=-1.000-i2.828
Run2:
Enter three co-efficients
1
5
2
The roots are real and distinct
The roots are root1=-0.438 and root2=-4.561
Run3:
Enter three co-efficients
1
2
1
The roots real and equal
The roots are root1=-1.000 and root2=-1.000

DSATM, Bangalore-82 Page 7


C PROGRAMMING LAB 23ESCS11

2 b) Write a C program to print Pyramid of stars patterns using Looping.


Procedure: This program takes an integer as row input to print pyramid.
Input: An integer as number of rows.
Expected Output: prints pyramid.
Algorithm: Pyramid
Step 1: Start
Step 2: Read no. of rows
Step 3: for i-> 1 to row in steps of 1
print “ “
for j -> 1 to 2*i-1 in steps of 1
print *
Step 4: Stop

FLOWCHART:

DSATM, Bangalore-82 Page 8


C PROGRAMMING LAB 23ESCS11

PROGRAM:
#include <stdio.h>
int main()
{
int i, j, rows;

printf("Enter number of rows: ");


scanf("%d", &rows);

for (i = 1; i <= rows; ++i)


{
for (j = 1; j <= rows - i; ++j)
{
printf(" ");
}
for (j = 1; j <= 2 * i - 1; ++j)
{
printf("*");
}
printf("\n");
}

OUTPUT:
Enter number of rows: 5
*
***
*****
*******
*********

DSATM, Bangalore-82 Page 9


C PROGRAMMING LAB 23ESCS11

PROGRAM-3
Implement Matrix multiplication and validate the rules of multiplication using C
Program.
Procedure: Input m*n and p*q size of 2 matrices elements to compute matrix multiplication.
ALGORITHM

Algorithm: Matrix_Multipication

Step 1: [Start of the algorithm]


Start
Step 2: [Read the order of the matrix A]
Read m,n
Step 3: [Read the order of the matrix B]
Read p,q
Step 4: [To check for compatibility condition of matrix multiplication]
if(n!=p)
print “Matrix multiplication not possible”
go to step 11
Step 5: [Read the elements of matrix A]
Repeat through step 5 for i0 to m-1
Repeat for j0 to n-1
Read a[i][j]
Step 6: [Read the elements of matrix B]
Repeat through step 6 for j0 to q-1
Repeat for i0 to p-1
Read b[i][j]
Step 7: [Display the elements of matrix A]
Repeat through step 7 for i0 to p-1
Repeat for j0 to q-1
Print a[i][j]
Step 8: [Display the elements of matrix B]
Repeat through step 8 for i0 to p-1
Repeat for j0 to q-1
Print b[i][j]

DSATM, Bangalore-82 Page 10


C PROGRAMMING LAB 23ESCS11

Step 9: [Calculate the product of two given matrices]


Repeat through step 9 for i0 to m-1
Repeat for j0 to q-1
c[i][j]0
Repeat for k0 to n-1
c[i][j]c[i][j]+a[i][k]*b[k][j]
Step 10: [Print the resultant matrix]
Repeat step 10 for i0 to m-1
Repeat for j0 to n-1
Print c[i][j]
Step 11: [terminate the algorithm]
Stop

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

if(n!=p)
{
printf(“Matrix multiplication is not possible\n”);
}
else
{
printf("Enter the elements of matrix A \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf ("%d",&a[i][j]);
}
printf("Enter the elements of matrix B \n");
for(i=0;i<p;i++)
{
` for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
}

DSATM, Bangalore-82 Page 11


C PROGRAMMING LAB 23ESCS11

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

}
printf(‘A-matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}

printf("B- matrix is \n");


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

printf("The resultant matrix C is \n");


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

DSATM, Bangalore-82 Page 12


C PROGRAMMING LAB 23ESCS11

OUTPUT (PASS 1)
.....................................................................
Enter the size of matrix A
23
Enter the size of matrix B
45
Matrix multiplication is not possible

OUTPUT (PASS 2)
Enter the size of matrix A
22
Enter the size of matrix B
22
Enter the elements of Matrix A
1 1
1 1
Enter the elements of Matrix B
1 1
1 1

Matrix-A is
1 1
1 1
Matrix-B is
1 1
1 1
The resultant matrix c is

2 2
2 2

DSATM, Bangalore-82 Page 13


C PROGRAMMING LAB 23ESCS11

PROGRAM-4
Write a C program for the following condition using Functions, Assume a Car Servicing
Centre. For every service request to the Car Service Centre, the given charges are levied
along with taxes.
a. Car water wash - Rs. 500 + 10% tax
b. Oil in the Engine must be at least 300 ml. If it goes below 300 ml(Ask the user to
input the current level of oil in the engine), top-up is done by the agency (the value of
top-up is given by the user so that level is at least 300 ml). Cost of 1 ml is Rs. 5 + 12.5%
tax.
1. Define suitable variables to capture the above 2 parameters and corresponding taxes
2. Compute the total amount to be paid.
3. Display the total with 17 places which includes 7 places for fraction. The integer part
of the total must be prefixed with 0’s and a sign if required.

PROGRAM:
#include <stdio.h>
// Function to calculate the total cost for car water wash
double calculateCarWaterWashCost (double baseCharge)
{
double tax = 0.1 * baseCharge;
return baseCharge + tax;
}

// Function to calculate the total cost for oil top-up


double calculateOilTopUpCost (double topUpMl)
{
double costPerMl = 5.0 + 0.125 * 5.0;
return topUpMl * costPerMl;
}

int main( )
{
double carWashCharge = 500.0;
double oilLevel, topUpMl, totalCost;

// Input current oil level and top-up amount


printf("Enter current oil level in the engine (in ml): ");
scanf("%lf", &oilLevel);
if (oilLevel < 300)
{
printf("Enter the quantity to top up (in ml): ");
scanf("%lf", &topUpMl);
if((topUpMl+ oilLevel)<300)
printf(“Entered quantity should be atleast %d”,300-oilLevel);
}
else
{

DSATM, Bangalore-82 Page 14


C PROGRAMMING LAB 23ESCS11

topUpMl= 0;
}
// Calculate total cost for car water wash and oil top-up
double carWashTotal = calculateCarWaterWashCost(carWashCharge);
double oilTopUpTotal = calculateOilTopUpCost(topUpMl);

// Compute total cost


totalCost = carWashTotal + oilTopUpTotal;

// Display the total with 17 places


printf("Total Amount : %+017.7lf\n", totalCost);
}

OUTPUT:
RUN-1
Enter current oil level in the engine (in ml): 250
Enter the quntity to top up (in ml): 55
Total Amount: +00000859.3750000
RUN-2
Enter current oil level in the engine (in ml): 450
Total Amount: +00000550.0000000

DSATM, Bangalore-82 Page 15


C PROGRAMMING LAB 23ESCS11

PROGRAM-5
Write a program in C using functions to swap two numbers using global variables
concept and call by reference concept.
PROGRAM: Program to swap two numbers using global variables
#include <stdio.h>
int num1, num2;
void swap( )
{
int temp = num1;
num1 = num2;
num2 = temp;
}

int main()
{
int num1, num2;
// Input two numbers
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);

printf("Before swapping: First number = %d, Second number = %d\n", num1, num2);

// Call the swap function


swap( );

printf("After swapping: First number = %d, Second number = %d\n", num1, num2);

OUTPUT:
Enter first number: 10
Enter second number: 20
Before swapping: First number = 10, Second number = 20
After swapping: First number = 20, Second number = 10

DSATM, Bangalore-82 Page 16


C PROGRAMMING LAB 23ESCS11

PROGRAM: Program to swap two numbers using call by reference


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

int main()
{
int num1, num2;
// Input two numbers
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);

printf("Before swapping: First number = %d, Second number = %d\n", num1, num2);

// Call the swap function


swap(&num1, &num2);

printf("After swapping: First number = %d, Second number = %d\n", num1, num2);

OUTPUT:
Enter first number: 10
Enter second number: 20
Before swapping: First number = 10, Second number = 20
After swapping: First number = 20, Second number = 10

DSATM, Bangalore-82 Page 17


C PROGRAMMING LAB 23ESCS11

PROGRAM - 6
Implement a C program to read the values from the user today’s date and your Date of
birth in the format dd-mm-yyyy. Consider your sleeping time 8 hours a day, reading 12
hours and spending 1.5 hours a day for eating. Calculate how many minutes have you
spent as of this date for Sleeping and Eating.
Calculate the number of years you have spent reading as of this date (amount of time
spent for reading in years).
PROGRAM:
#include <stdio.h>
#include <stdlib.h>

int main() {
// Variables to store the input dates
int today_day, today_month, today_year;
int birth_day, birth_month, birth_year;

// Variables for time spent on sleeping, reading, and eating


float sleeping_hours = 8;
float reading_hours = 12;
float eating_hours = 1.5;
float minutes_per_hour = 60;
// Prompt for today's date
printf("Enter today's date (dd-mm-yyyy): ");
scanf("%d-%d-%d", &today_day, &today_month, &today_year);
// Prompt for date of birth
printf("Enter your date of birth (dd-mm-yyyy): ");
scanf("%d-%d-%d", &birth_day, &birth_month, &birth_year);

// Calculate the age in years


int age_years = today_year - birth_year;

DSATM, Bangalore-82 Page 18


C PROGRAMMING LAB 23ESCS11

if (today_month < birth_month || (today_month == birth_month && today_day <


birth_day)) {
age_years--;
}
// Calculate the total minutes spent on sleeping and eating
int total_minutes_sleep_eat = age_years * 365 * (sleeping_hours + eating_hours) *
minutes_per_hour;
// Calculate the number of years spent on reading
float years_reading =(reading_hours/ hours_per_day)*age_years;
// Output the results
printf("As of today's date, you have spent %d minutes on sleeping and eating combined.\n",
total_minutes_sleep_eat);
printf("As of today's date, you have spent %.2f years on reading.\n", years_reading);
return 0;
}

DSATM, Bangalore-82 Page 19


C PROGRAMMING LAB 23ESCS11

PROGRAM-7
7 a) Write functions to implement string operations such as compare, concatenate, and
find string length. Use the parameter passing techniques.

ALGORITHM

Algorithm strings
Step 1: Start
Step 2: read string s1 & s2
Step 3: [call function strlength()]
i.e length =strlength
Step 4: Display length 1 and length 2
Step 5: [call function compare string]
if(compare_ string(s1,s2)==0)
print” equal strings”
else
print”unequl strings”
Step 6: call function concatenate
if(concatenate(s1,s2))
Step 7: print”concatenate string”
Step 8: Stop

Algorithm String_length()
Step 1: Start
Step 2: repeate step 2 through while(s1[i]!=’\0’)
i++
return i
end while
Step 3: Stop

Algorithm String_compare()
Step 1: Start
Step 2: repeatr step 2 trough while(s1[i]==s2[i])
if(s[i]==’\0’|| s2[i]==’\0’)
break
i++
end while

Step 3: if(s[i]==’\0’ && s2[i]==’\0’)


return 0
else
return 1
Step 4: Stop

Algorithm String_concatenate()
Step 1: Start
Step 2: Initilize i=0
Step 3: repeate step 3 through while (s1[i]!=’\0’)
i++
end while

DSATM, Bangalore-82 Page 20


C PROGRAMMING LAB 23ESCS11

Step 4: initialize j=0


Step 5: repeate step 5 through while(s2[i]1=’\0’)
s1[i]=s2[j]
i++ j++
end while
Step 6: s1[i]=’\0’
Step 7: Stop

PROGRAM
#include <stdio.h>
int compare_strings(char [], char []);
void concatenate(char [], char []);
int string_length(char []);

int main()
{
char s1[100], s2[100];
printf("Input a string1\n");
gets(s1);
printf("Input a string2\n");
gets(s2);

int length1 = string_length(s1);


int length2 = string_length(s2);
printf("Length of %s = %d\n", s1, length1);
printf("Length of %s = %d\n", s2, length2);
if (compare_strings(s1, s2) == 0)
printf("Equal strings.\n");
else
printf("Unequal strings.\n");
concatenate(s1, s2);
printf("String obtained on concatenation: \"%s\"\n", s1);
}

int string_length(char s1[])


{
int i = 0;
while (s1[i] != '\0')
i++;
return i;
}

int compare_strings(char s1[], char s2[])


{
int i = 0;
while (s1[i] == s2[i])
{
if (s1[i] == '\0' || s2[i] == '\0')
break;
i++;

DSATM, Bangalore-82 Page 21


C PROGRAMMING LAB 23ESCS11

}
if (s1[i] == '\0' && s2[i] == '\0')
return 0;
else
return 1;
}

void concatenate(char s1[], char s2[])


{
int i, j;
i = 0;
while (s1[i] != '\0')
{
i++;
}
j = 0;
while (s2[j] != '\0')
{
s1[i] = s2[j];
j++;
i++;
}
s1[i] = '\0';
}

OUTPUT:
Input string1
dsatm
Input string2
dsi
Length of string1: 5
Length of string2: 3
Unequal string
String obtained on concatenation: dstamdsi

DSATM, Bangalore-82 Page 22


C PROGRAMMING LAB 23ESCS11

7 b) Implement a C Program to check String is a Palindrome or Not.

Algorithm: Palindrome
Step 1: Accept the input string from the user
Step 2: Determine the length of the string
Step 3: 3Use a loop to compare characters from the beginning and end of the string.
Step 4: If the characters at corresponding positions do not match, mark the string as not a
palindrome and exit the loop.
Step 5: If the loop completes without finding any non-matching characters, mark the string as
a palindrome
Step 6: Print the result based on whether the string is a palindrome or not.

FLOWCHART

DSATM, Bangalore-82 Page 23


C PROGRAMMING LAB 23ESCS11

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

int main()
{
char str[100];
int i, length;
int isPalindrome = 1;

printf("Enter a string: ");


scanf("%s", str);

length = strlen(str);

for (i = 0,j=length-1; i < length / 2; i++,j--)


{
if (str[i] != str[j])
{
isPalindrome = 0;
break;
}
}
if (isPalindrome)
{
printf("%s is a palindrome.\n", str);
}
else
{
printf("%s is not a palindrome.\n", str);
}
}

OUTPUT:
Run-1:
Enter a string: dsatm
dsatm is not a palindrome.

Run-2:
Enter a string: malayalam
malayalam is a palindrome.

DSATM, Bangalore-82 Page 24


C PROGRAMMING LAB 23ESCS11

PROGRAM-8
Write a C Program to Implement linear search and binary search.
Procedure: Input N array elements and to find whether element is present or not.
Input: Array elements.
Expected Output: Successful search or unsuccessful search.

ALOGRITHM

Algorithm binary_search
Step 1: Start
Step 2: Read n
Step 3: Repeat for i=0 to n-1
Read a[i]
Step 4: read key
Step 5: Initialize low =0 high = n-1
Step 6: Repeat through step 6 while (low <= high)
mid = (low+ high)/2
if(key==a[mid])
found=1
else if(key>a[mid])
low=mid+1
else
high=mid-1
end while
Step 7: if(found ==1)
print “Item found”
else
print” Item not found”
Step 8: Stop

DSATM, Bangalore-82 Page 25


C PROGRAMMING LAB 23ESCS11

FLOWCHART

DSATM, Bangalore-82 Page 26


C PROGRAMMING LAB 23ESCS11

PROGRAM:-Binary Search

#include<stdio.h>
int main()
{
int i,n,a[10],mid,low,high,key, found=0;
printf("\n Enter the number of elements:\n");
scanf("%d", &n);
printf("Enter the array element in the ascending order\n");
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\n Enter the key element to be searched\n");
scanf("%d", &key);

low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
found=1;
break;
}
else if(key>a[mid])
low=mid+1;
else
high=mid-1;
}
if(found ==1)
printf(“Item found in position : %d”,mid+1);
else
printf("\n Item not found\n");
}

OUTPUT:
RUN 1:
Enter the number of elements:
5
Enter the array element in the ascending order
10
20
30
40
50

DSATM, Bangalore-82 Page 27


C PROGRAMMING LAB 23ESCS11

Enter the key element to be searched


30
Item found in position: 3
RUN 2:
Enter the number of elements:
5
Enter the array element in the ascending order
10
20
30
40
50
Enter the key element to be searched
70
Item not found

PROGRAM:- Linear Search


#include<stdio.h>
int main()
{
int i,n,a[10],key,found=0;
printf("\n Enter the number of elements:\n");
scanf("%d", &n);
printf("Enter the array element in the ascending order\n");
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\n Enter the key element to be searched\n");
scanf("%d", &key);
for (i = 0; i < n; i++)
{
if (key== a[i])
{
found=1;
break;
}
}
if(found ==1)
printf("Item found in position : %d",i+1);
else
printf("\n Item not found\n");
}

DSATM, Bangalore-82 Page 28


C PROGRAMMING LAB 23ESCS11

OUTPUT:
Enter the number of elements:
5
Enter the array element in the ascending order
11
66
33
88
23
Enter the key element to be searched
88
Item found in position : 4

DSATM, Bangalore-82 Page 29


C PROGRAMMING LAB 23ESCS11

PROGRAM-9
Write a C Program to Implement Bubble Sort.
ALGORITHM
Algorithm: Bubble sort
Step 1: [Start of the algorithm]
Start
Step 2: [Read the size of the array]
read n
Step 3: [Read the array elements]
Repeat for i=0 to n-1
read a[i]
Step 4: [Print the given array]
Repeat for i=0 to n-1
print a[i]
Step 5: Repeat through step 5 for i1 to n-1
Repeat for j0 to n-i
if(a[j]>a[j+1])
tempa[j]
a[j] a[j+1]
a[j+1]temp
Step 5: [Print the sorted array]
Repeat for i 0 to n-1
print a[i]
Step 6 :[terminate the algorithm]
Stop

DSATM, Bangalore-82 Page 30


C PROGRAMMING LAB 23ESCS11

FLOWCHART

PROGRAM:
#include<stdio.h>
int main()
{
int a[100],n,i,j,temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the %d elements of array\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("The Input array is\n");


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

DSATM, Bangalore-82 Page 31


C PROGRAMMING LAB 23ESCS11

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

printf("\nThe sorted array is\n");


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

OUTPUT:
Enter the number of elements
4
Enter 4 elements of array
87
100
20
3

The input array is

87 100 20 3

The sorted array is

3 20 87 100

DSATM, Bangalore-82 Page 32


C PROGRAMMING LAB 23ESCS11

PROGRAM-10
Write a C program to read employee information (Name, Designation, Salary) from the
user and write it to a file.
PROGRAM:
#include <stdio.h>
int main()
{
FILE *file;
char name[50], designation[100], filename[10];
float salary;

printf("Enter the name of the file to save employee information (e.g., employee.txt): ");
scanf("%s", filename);

// Open the specified file for writing


file = fopen(filename, "w");
if (file == NULL)
{
printf("Unable to open the file.\n");
return 1;
}
printf("Enter employee name, designation and salary: ");
scanf("%s", name);
scanf("%s", designation);
scanf("%f", &salary);

// Write employee details to the file


fprintf(file, "Name: %s\n Designation: %s\n Salary: %.2f\n", name, designation, salary);

printf("Employee information has been written to the file.\n");

// Close the file


fclose(file);

OUTPUT:
Enter the name of the file to save employee information (e.g., employee_info.txt): cse.txt
Enter employee name: Arun
Enter employee designation: Developer
Enter employee salary: 10000
Employee information has been written to the file.
Text file:

DSATM, Bangalore-82 Page 33


C PROGRAMMING LAB 23ESCS11

PROGRAM-11
Write a C Program to input even & odd elements of an array in two separate arrays. The
program first finds the odd and even elements of the array. Then the odd elements of the
array are stored in one array and even elements of the array are stored in another array.
PROGRAM:
#include <stdio.h>
int main()
{
int n, i, j = 0, k = 0;
int a[50], even[50], odd[50];

printf("Enter the size of the array: ");


scanf("%d", &n);

printf("Enter the elements of the array: ");


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

// Finding odd and even elements and storing them in separate arrays
for (i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
{
even[j] = a[i];
j++;
}
else
{
odd[k] = a[i];
k++;
}
}

// Printing the even elements


printf("Even elements: ");
for (i = 0; i < j; i++)
{
printf("%d ", even[i]);
}
printf("\n");

// Printing the odd elements


printf("Odd elements: ");
for (i = 0; i < k; i++)
{
printf("%d ", odd[i]);
}

DSATM, Bangalore-82 Page 34


C PROGRAMMING LAB 23ESCS11

printf("\n");
}

OUTPUT:

Enter the size of the array: 5


Enter the elements of the array:
1
2
3
4
5
Even elements: 2 4
Odd elements: 1 3 5

DSATM, Bangalore-82 Page 35


C PROGRAMMING LAB 23ESCS11

PROGRAM-12
Write a C program to define a structure to represent a cricketer's information (name,
runs, average). Read the data corresponding to N Cricketer's in a structure array. The
space for the array of structures should be determined at run-time by user input.

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

struct Cricketer
{
char name[50];
int runs;
float average;
};

int main()
{
int n;
printf("Enter the number of cricketers: ");
scanf("%d", &n);

struct Cricketer *cricketers = (struct Cricketer *)malloc(n * sizeof(struct Cricketer));


if (cricketers == NULL)
{
printf("Memory allocation failed. Exiting...\n");
return 1;
}
for (int i = 0; i < n; i++)
{
printf("Enter details for Cricketer #%d:\n", i+1);

printf("Name: ");
scanf("%s", cricketers[i].name);

printf("Runs: ");
scanf("%d", &cricketers[i].runs);

printf("Average: ");
scanf("%f", &cricketers[i].average);
}

printf("Cricketer Information:\n");
for (int i = 0; i < n; i++)
{
printf("Cricketer #%d\n", i+1);
printf("Name: %s\n", cricketers[i].name);
printf("Runs: %d\n", cricketers[i].runs);

DSATM, Bangalore-82 Page 36


C PROGRAMMING LAB 23ESCS11

printf("Average: %.2f\n", cricketers[i].average);


}
free(cricketers);
}

OUTPUT:
Enter the number of cricketers: 2
Enter details for Cricketer #1:
Name: Sachin
Runs: 10500
Average: 154
Enter details for Cricketer #2:
Name: Kohli
Runs: 10000
Average: 132
Cricketer Information:
Cricketer #1
Name: Sachin
Runs: 10500
Average: 154.00
Cricketer #2
Name: Kohli
Runs: 10000
Average: 132.00

DSATM, Bangalore-82 Page 37

You might also like