0% found this document useful (0 votes)
258 views47 pages

Lab Mannual

This document outlines the vision, mission, quality policy, objectives, and goals of Dayananda Sagar Academy of Technology and Management. It also provides details of the Principles of Programming Using C laboratory course, including the list of programming problems students should complete, evaluation criteria, and notes on course structure. The course aims to teach programming fundamentals using C and integrate practical work with theory. Students will be evaluated both continuously and through a final exam, with marks given for lab reports, program execution, viva voce, and tests.
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)
258 views47 pages

Lab Mannual

This document outlines the vision, mission, quality policy, objectives, and goals of Dayananda Sagar Academy of Technology and Management. It also provides details of the Principles of Programming Using C laboratory course, including the list of programming problems students should complete, evaluation criteria, and notes on course structure. The course aims to teach programming fundamentals using C and integrate practical work with theory. Students will be evaluated both continuously and through a final exam, with marks given for lab reports, program execution, viva voce, and tests.
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

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. C. Kavitha Dr. M Ravishankar


HOD, Principal, DSATM
CSE, 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;
printf("Choose operation to perform (+,-,*,/,%%): ");
scanf(" %c", &ch);

printf("Enter first number: ");


scanf("%d", &num1);

DSATM, Bangalore-82 Page 2


C PROGRAMMING LAB 23ESCS11

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/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 & dis4nct & 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 Print root1=real+img


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=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+i1.414
The second root root2=-1.000-i1.414
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>
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]);
}
for(i=0;i<m;i++)
{

DSATM, Bangalore-82 Page 11


C PROGRAMMING LAB 23ESCS11

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
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), 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 currentOilLevel, double topUpAmount)
{
double costPerMl = 5.0 + 0.125 * 5.0;
double requiredOil = 300.0;
double extraOil = topUpAmount - (requiredOil - currentOilLevel);
return extraOil * costPerMl;
}

int main()
{
double carWashCharge = 500.0;
double oilLevel, topUpAmount, 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 amount to top up (in ml): ");
scanf("%lf", &topUpAmount);
}
else
{

DSATM, Bangalore-82 Page 14


C PROGRAMMING LAB 23ESCS11

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

// 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 amount to top up (in ml): 55
Total Amount: +00000578.1250000
RUN-2
Enter current oil level in the engine (in ml): 450
Total Amount: +00001393.7500000

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:
#include <stdio.h>
int num1, num2;
// Function to swap two numbers using call by reference
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

int main()
{
// 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 16


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, read 12
hours and spend 1.5 hours a day for eating. Calculate how many minutes have you
spent as of this date 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).
PROGRAM:
#include <stdio.h>
// Function to convert date to days
int convertToDays(int day, int month, int year)
{
return day + (month - 1) * 30 + (year - 1) * 365;
}
int main()
{
// Variables
int todayDay, todayMonth, todayYear;
int birthDay, birthMonth, birthYear;
int sleepHours = 8;
float eatHours = 1.5;
int readHours = 12;
float totalMinutes,todayDays,birthDays;
double yearsSpentReading;

// Read today's date


printf("Enter today's date (dd-mm-yyyy): ");
scanf("%d-%d-%d", &todayDay, &todayMonth, &todayYear);

// Read date of birth


printf("Enter your date of birth (dd-mm-yyyy): ");
scanf("%d-%d-%d", &birthDay, &birthMonth, &birthYear);

// Calculate days spent


todayDays = convertToDays(todayDay, todayMonth, todayYear);
birthDays = convertToDays(birthDay, birthMonth, birthYear);

// Calculate total minutes spent on sleeping and eating


totalMinutes = (todayDays - birthDays) * (sleepHours + eatHours) * 60;

// Calculate number of years spent on reading


yearsSpentReading = (todayDays - birthDays) * readHours / 24.0 / 365.0;

DSATM, Bangalore-82 Page 17


C PROGRAMMING LAB 23ESCS11

// Display results
printf("Total minutes spent on sleeping and eating: %.2f minutes\n", totalMinutes);
printf("Number of years spent on reading: %.2lf years\n", yearsSpentReading);
}
OUTPUT:
Enter today's date (dd-mm-yyyy): 28-11-2023
Enter your date of birth (dd-mm-yyyy): 13-06-1989
Total minutes spent on sleeping and eating: 6790500 minutes
Number of years spent on reading: 17.23 years

DSATM, Bangalore-82 Page 18


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 19


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 20


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 21


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 22


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; i < length / 2; i++)


{
if (str[i] != str[length - i - 1])
{
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 23


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 24


C PROGRAMMING LAB 23ESCS11

FLOWCHART

DSATM, Bangalore-82 Page 25


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 26


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 27


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 28


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 29


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 30


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 31


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_info.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: ");
scanf("%s", name);
printf("Enter employee designation: ");
scanf("%s", designation);
printf("Enter employee salary: ");
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: Software Developer
Enter employee salary: Employee information has been written to the file.

DSATM, Bangalore-82 Page 32


C PROGRAMMING LAB 23ESCS11

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 an
array are stored in one array and even elements of an array is 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


C PROGRAMMING LAB 23ESCS11

Appendix

Common ‘C’ Errors

The most common errors can be broadly classified as follows

1. Programming errors
These errors are generated when typographical errors are made by users.
2. Compiler errors
These errors are detected by the compiler that make the program un-compilable.
3. Linker error
These errors are generated when the executable of the program cannot be generated.
This may be due to wrong function prototyping, incorrect header files.
4. Execution error
These errors occur at the time of execution. Looping and arithmetic errors falls
under this category.
5. Logical errors
These errors solely depend on the logical thinking of the programmer and are easy to
detect if we follow the line of execution and determine why the program takes that
path of execution.

List of some common programming errors


1. Misuse of the Include Guard.
2. Switch statements without break.
3. Wrong usage of postfix and prefix operator (diff between i++ and ++i)
4. Undeclared and Uninitialized Variables and functions.
5. Trying to include "INCORRECT" header function.
6. Returning a value in a void function.
7. Confusing the name of an array with the contents of the first element.
8. ‘C’ string array Errors - Arr[10] = Arr[0] to Arr[9]. Trying to access Arr[10]
element.
9. Using "=" (assignment operator) instead of "= =" (comparison operators) scanf()
without '&'
and wrong format.(IN C)
10. Trying to divide a number by Zero.
11. Poor Loop Exiting comparisons will tend to either loop being not executed at all
or goes to
an infinite loop.
12. Not using string functions and treating the strings are integer. Say trying to compare string
by

(string1= = string2), rather than using strcmp command


13. ‘C’ String not terminated by '\0'- Null character
14. Mismatched "{" or IF-ELSE statements or for that matter any looping statement.
15. Missing “;” at the end of every statement except control statements and function
definition.

DSATM, Bangalore-82 Page 38


C PROGRAMMING LAB 23ESCS11

Some Examples of Common Mistakes


1. Forgetting to put a break in a switch statement
Remember that C does not break out of a switch statement if a case is encountered. For
example:
int x = 2;
switch(x)
{
case 2: printf("Two\n");
case 3: printf("Three\n");
}
prints output:
Two
Three
Put a break to break out of the switch:
int x = 2;
switch(x)
{
case 2: printf("Two\n");
break;
case 3: printf("Three\n");
break; /* not necessary, but good if additional cases are added later
*/
}
2. Using = instead of ==
C's = operator is used exclusively for assignment and returns the value assigned. The ==
operator is used exclusively for comparison and returns an integer value (0 for false, not
0 for true). Because of these return values, the C compiler often does not flag an error
when = is used when one really wanted an ==. For example:
int x = 5;
if ( x = 6 )
printf("x equals 6\n");
This code prints out x equals 6! Why? The assignment inside the if sets x to 6 and returns the value 6
to the if. Since 6 is not 0, this is interpreted as true.
One way to have the compiler find this type of error is to put any constants (or any r-value
expressions) on the left side. Then if an = is used, it will be an error:
if ( 6 = x)

DSATM, Bangalore-82 Page 39


C PROGRAMMING LAB 23ESCS11

3. scanf() errors
There are two types of common scanf() errors:
1. Forgetting to put an ampersand (&) on arguments
scanf() must have the address of the variable to store input into. This means
that often the ampersand address operator is required to compute the addresses.
Here's an example:
scanf("%d", &x); /* & required to pass address to scanf() */
scanf("%30s", st); /* NO & here, st itself points to variable! */
2. Using the wrong format for operand
C compilers do not check that the correct format is used for arguments
of a scanf() call. The most common errors are using the %f format for
doubles (which must use the %lf format) and mixing up %c and %s
for characters and strings.
4. Size of arrays
Arrays in C always start at index 0. This means that an array of 10 integers defined as:
int a[10];
has valid indices from 0 to 9 not 10! It is very common for students go one too far in an
array. This can lead to unpredictable behavior of the program.
5. Integer division
C uses the / operator for both real and integer division. It is important to understand how
C determines which it will do. If both operands are of an integal type, integer division is
used, else real division is used. For example:
double half = 1/2;
This code sets half to 0 not 0.5! Why? Because 1 and 2 are integer constants. To fix this,
change at least one of them to a real constant.
double half = 1.0/2;
If both operands are integer variables and real division is desired, cast one of the variables
to double (or float).
int x = 5, y = 2;
double d = ((double) x)/y;
6. Loop errors
In C, a loop repeats the very next statement after the loop statement. The code:
int x = 5;
while( x > 0 );
x--;

DSATM, Bangalore-82 Page 40


C PROGRAMMING LAB 23ESCS11

is an infinite loop. Why? The semicolon after the while defines the statement to repeat as
the null statement (which does nothing). Remove the semicolon and the loop works as
expected.
Another common loop error is to iterate one too many times or one too few.
Check loop conditions carefully!
7. Not using prototypes
Prototypes tell the compiler important features of a function: the return type and the
parameters of the function. If no prototype is given, the compiler assumes that the
function returns an int and can take any number of parameters of any type.
One important reason to use prototypes is to let the compiler check for errors
in the argument lists of function calls. However, a prototype must be used if the function
does not return an int. For example, the sqrt() function returns a double, not an int. The
following code:
double x = sqrt(2);
will not work correctly if a prototype:
double sqrt(double);
does not appear above it. Why? Without a prototype, the C compiler assumes that sqrt()
returns an int. Since the returned value is stored in a double variable, the compiler inserts
code to convert the value to a double. This conversion is not needed and will result in the
wrong value.
The solution to this problem is to include the correct C header file that contains
the sqrt() prototype, math.h. For functions you write, you must either place the prototype
at the top of the source file or create a header file and include it.
8. String Errors
1. Confusing character and string constants
C considers character and string constants as very different things. Character
constants are enclosed in single quotes and string constants are enclosed in
double quotes. String constants act as a pointer to the actually string. Consider
the following code:
char ch = 'A'; /* correct */
char ch = "A"; /* error */
The second line assigns the character variable ch to the address of a string
constant. This should generate a compiler error.

2. Comparing strings with ==


Never use the == operator to compare the value of strings! Strings are char
arrays. The name of a char array acts like a pointer to the string (just like other
types of arrays in C). So what? Consider the following code:
char st1[] = "abc";
char st2[] = "abc";

DSATM, Bangalore-82 Page 41


C PROGRAMMING LAB 23ESCS11

if ( st1 == st2 )
printf("Yes");
else
printf("No");
This code prints out No. Why? Because the == operator is comparing the
pointer values of st1 and st2, not the data pointed to by them. The correct way
to compare string values is to use the strcmp() library function. (Be sure to
include string.h) If the if statement above is replaced with the following:
if ( strcmp(st1,st2) == 0 )
printf("Yes");
else
printf("No");
The code will print out Yes. For similar reasons, don't use the other relational
operators (<,>, etc.) with strings either. Use strcmp() here too.

DSATM, Bangalore-82 Page 42


C PROGRAMMING LAB 23ESCS11

VIVA QUESTIONS
1. What is a Computer?
2. What is a compiler?
3. Differentiate object & executable file?
4. What is execution?
5. What is compilation?
6. What are the uses of Internet?
7. Explain different parts of the computer?
8. Define tracing, debugging?
9. What are the differences between RAM and ROM?
10. What are bits? What is a byte?
11. What is booting?
12. What is a source program?
13. Explain the structure of C program with an example.
14. Who is the father of “C” Computer?
15. Steps to execute a program?
16. Which are input & output statements?
17. Explain the different types of IF statements
18. Differentiate between break and continue
19. What are operators? List out different operators?
20. List out fundamental data types in C.
21. What do you mean by type conversions?
22. Why looping is necessary?
23. What is the syntax of a function declaration & function definition?
24. Define recursion & its application?
25. What is an array? How are they declared in ‘C’? What are the rules to be followed while
using arrays?
26. Explain the single and multi-dimensional arrays?
27. Explain the different categories of functions?
28. What is a string? What is a string manipulation library functions?
29. What are preprocessor directive?
30. List out different header files?
31. What is a parallel program?
32. What is the use of clrscr ()?
33. How to execute a parallel program?
34. What is searching & sorting? Logic of bubble sort, binary search?
35. What is divide & conquer methods?
36. What is memory allocation?
37. What is a pointer?
38. Explain format specifier, escape sequence?
39. Applications of arrays, looping, conditional statements?
40. Can we have main function within a main function?
41. Difference between object oriented & procedure oriented programs?
42. Logic of all programs?
43. Explain flowchart & algorithm?

DSATM, Bangalore-82 Page 43

You might also like