0% found this document useful (0 votes)
85 views

CPPS_2025_Lab_Manual

The document is a laboratory manual for the C Programming for Problem Solving course (24EN1202) at Dayananda Sagar University for the academic year 2024-2025. It outlines the vision, mission, program educational objectives, outcomes, and specific outcomes for the Computer Science and Engineering department, along with a list of programming exercises and instructions for using the Linux operating system and tools. The manual emphasizes the importance of practical skills in programming and encourages students to develop their own algorithms and code solutions.

Uploaded by

bbatman0256
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

CPPS_2025_Lab_Manual

The document is a laboratory manual for the C Programming for Problem Solving course (24EN1202) at Dayananda Sagar University for the academic year 2024-2025. It outlines the vision, mission, program educational objectives, outcomes, and specific outcomes for the Computer Science and Engineering department, along with a list of programming exercises and instructions for using the Linux operating system and tools. The manual emphasizes the importance of practical skills in programming and encourages students to develop their own algorithms and code solutions.

Uploaded by

bbatman0256
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

DAYANANDA SAGAR UNIVERSITY

SCHOOL OF ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

C PROGRAMMING FOR PROBLEM SOLVING


COURSE CODE: 24EN1202
LABORATORY MANUAL

Department of Computer Science and Engineering


Dayananda Sagar University 1
DAYANANDA SAGAR UNIVERSITY

SCHOOL OF ENGINEERING

Lab Manual
C PROGRAMMING FOR PROBLEM SOLVING
24EN1202
COMPUTER SCIENCE & ENGINEERING

2024-2025

Department of Computer Science and Engineering


Dayananda Sagar University 2
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

C Programming for Problem Solving


Course Code: 24EN1202

NAME:
………………………………………………………

USN:
…………………………………………………………

Department of Computer Science and Engineering


Dayananda Sagar University 3
Vision
To be a Centre of excellence in education, research & training, innovation &
entrepreneurship and to produce citizens with exceptional leadership qualities to serve
national and global needs.

Mission
To achieve our objectives in an environment that enhances creativity, innovation and
scholarly pursuits while adhering to our vision.

Values
• The values that drive DSU and support its vision:

The Pursuit of Excellence


• A commitment to strive continuously to improve ourselves and our systems with the
aim of becoming the best in our field.

Fairness
• A commitment to objectivity and impartiality, to earn the trust and respect of society.

Leadership
• A commitment to lead responsively and creatively in educational and research
processes.

Integrity and Transparency


• A commitment to be ethical, sincere and transparent in all activities and to treat
all individuals with dignity and respect.

Department of Computer Science and Engineering


Dayananda Sagar University 4
Vision & Mission of the Department

Vision
To be recognized as a department of eminence in Computer Science and Engineering focusing on
sustainability, inclusive technologies, and societal needs.

Mission

The Department of Computer Science and Engineering is committed to:

§ M1: Impart quality technical education by designing and delivering contemporary Computer
Science Engineering curricula while emphasizing leadership, ethics, values, and integrity.

§ M2: Transform professionals into technically competent through industry-academia collaboration


and innovation ecosystem.

§ M3: Prepare Computer Science and Engineering graduates to meet ever-growing societal needs.

Department of Computer Science and Engineering


Dayananda Sagar University 5
Program Educational Objectives (PEO's)

• PEO1. Apply appropriate theory, practices and tools in the design,


implementation, maintenance and evaluation of computing in the
workplace or in higher education.

• PEO2. Exhibit professional skills in solving challenging problems in their


career and advance to leadership roles.

• PEO3. Become effective innovator , researcher , and entrepreneur to


provide technical solutions for socio-economic challenges.

Program Outcome (PO's)

• PO1. Engineering knowledge: Apply the knowledge of mathematics,


science, engineering fundamentals, and an engineering specialization
to the solution of complex engineering problems.

• PO2. Problem analysis: Identify, formulate, review research literature,


and analyze complex engineering problems reaching substantiated
conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
• PO3. Design/development of solutions: Design solutions for complex
engineering problems and design system components or processes that
meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental
considerations.

Department of Computer Science and Engineering


Dayananda Sagar University 6
• PO4. Conduct investigations of complex problems: Use research-
based knowledge and research methods including design of
experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
• PO5. Modern tool usage: Create, select, and apply appropriate
techniques, resources, and modern engineering and IT tools including
prediction and modeling to complex engineering activities with an
understanding of the limitations.
• PO6. The engineer and society: Apply reasoning informed by the
contextual knowledge to assess societal, health, safety, legal and
cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
• PO7. Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable
development.
• PO8. Ethics: Apply ethical principles and commit to professional ethics
and responsibilities and norms of the engineering practice.
• PO9. Individual and team work: Function effectively as an individual,
and as a member or leader in diverse teams, and in multidisciplinary
settings.
• PO10. Communication: Communicate effectively on complex
engineering activities with the engineering community and with society
at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and
receive clear instructions.

Department of Computer Science and Engineering


Dayananda Sagar University 7
• PO11. Project management and finance: Demonstrate knowledge
and understanding of the engineering and management principles and
apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
• PO12. Life-long learning: Recognize the need for and have the
preparation and ability to engage in independent and life-long learning
in the broadest context of technological change.

Program Specific Outcomes (PSO's)

• PSO1. Design and Integrate software and hardware systems by


following standard software engineering principles in the areas related
to IOT , Cloud, Networks, Security, Embedded Systems, and Artificial
Intelligence of varying complexity.
• PSO2. Design and Implement application software systems by
applying the concepts of Programming languages, Machine Learning,
Mobile Computing, and Data Science that meet the automation
requirements of society and Industry.

Department of Computer Science and Engineering


Dayananda Sagar University 8
DAYANANDA SAGAR UNIVERSITY

Laboratory Certificate
This is to certify that Mr./Ms bearing University Seat number
(USN) has satisfactorily completed the experiments in
above practical subject prescribed by the University for the 2nd semester B.Tech
program in the C Programming for Problem Solving(24EN1202) Laboratory of this
university during the year 2024-2025.

Date:

Signature of the Faculty In-charge MARKS

Maximum Obtained

Signature of the Chairman

Department of Computer Science and Engineering


Dayananda Sagar University 9
Laboratory Environment
• This course will use Ubuntu distribution of Linux as the Operating System
for all the exercises
• The tool chain used will be GNU ‘gcc’ suite of tools
• Editor recommended is ‘gedit’ which is available in these systems
• ‘terminal’ program is used to run ‘gcc’ and the executable code

Basic Instructions to use the tools


1. If the system is not powered on, please turn the system ON by pressing the power button on the PC.
2. Check if the monitor needs to be turned on as well
3. If presented with a boot time option, please select ‘Ubuntu’ in the list
4. Once Ubuntu has booted up, click on the program selection icon on the bottom left of the screen (a
small square with dots).
5. Type ‘terminal’ in the search bar at the top
6. The icon for the ‘terminal’ program will appear below, and click the same to start the terminal
program
7. The terminal program will typically be a black coloured window with a prompt to type commands.
8. Type ‘gedit <prog_name.c>’ on the terminal window.
9. This will open the gedit window, which can be used to type the program. Note that the name of the
file you specified (prog_name.c) will appear on the top of the window. If there is a ‘*’ character
before the file name, it indicates that the file has not been saved yet. Please remember to save the
file once you have finished typing the program.
10. You can close the ‘gedit’ window to get back to the terminal prompt.
11. Type ‘gcc <prog_name.c>’ and press enter.
12. If there are no errors/warnings, you will see the command prompt again. Else, ‘gcc’ will print the
errors and warnings with line numbers to help you fix the errors.
13. If there are errors/warnings, fix them and re-run ‘gcc’ till you get a clean compile.
14. ‘gcc’ by default will save the executable code in a file by name ‘a.out’.
15. To run your program and check the output, please type ‘./a.out’ and press enter. This will make the
OS run the code and you can check the output.
16. If the code does not give the desired output, or fails with some errors, repeat the edit-compile-test
cycle by going back and editing the program using ‘gedit’.

For example, if you want to name the file as lab1.c, the following are the commands

gedit lab1.c
gcc lab1.c
./a.out

Department of Computer Science and Engineering


Dayananda Sagar University 10
List of C Programming Problem statements

PN Problem statement Date Marks Sign


a. Write a C program to read two whole numbers, store them in
1 variables, and display their values with variable names. Then,
swap their contents and print the updated values.

b. Write a C program to compute simple interest using user-input


values for the principal amount, interest rate, and term. Display
the calculated interest amount.

c. Write a C program to calculate and display the factorial of a


number entered by the user.
Write a C program to generate the roots of a quadratic equation.
2 The various parameters for the quadratic equation are to be
received as inputs from the user.
3 a. Write a C program to read a number and check whether the
entered number is a palindrome.

b. Write a C program to calculate the ‘n’th power of a given


number ‘x’. Take both ‘n’ and ‘x’ as inputs from the user.
a. Write a C program to generate the ‘Fibonacci’ series for ‘n’
4 positions, take ‘n’ as an input from the user.

b. Write a C program that takes two numbers ‘x’ and ‘y’ as input
and calculates the Greatest Common Divisor (GCD) of them and
displays the result.
Write a C program that takes two numbers, x and y, as input and
5 stores them in separate variables. The program should then read a
single character representing an operator (+, -, *, or /). It should
perform the corresponding arithmetic operation (x op y), display
the result, and then wait for another operator input. If the user
enters 'q' instead of one of the four operators, the program should
terminate.
a. Write a C program that reads a string from the user and prints
the length of the string. Program must implement the logic to
calculate the length and not use a library function.
6
b. Write a C program that reads two strings, joins them into
another variable, and prints the concatenated result. Use static
memory allocation with a fixed size.

c. Write a C program that takes a string as input from the user,


reverses it, and then prints the reversed string.

Department of Computer Science and Engineering


Dayananda Sagar University 11
Write a program that reads ‘n’ numbers and stores them in an
7 array in the same order as entered. First, it prints the numbers in
their original order. Then, it sorts the array in ascending order and
prints the sorted numbers.
Write a program that searches for a specific number in a pre-
8 initialized array. The number to be searched is taken as input from
the user, and the program prints an appropriate message
indicating whether the number is found or not.
Write a program that uses a function to swap two numbers. The
9 function takes as input the pointers to the two variables that
contain the values to be swapped.
Write a program that can parse a simple arithmetic expression of
type (x op y op z). The program can make use of all the available
10 string manipulation functions to parse the string efficiently. The
arithmetic expression is given as an input by the user. ‘x’, ‘y’, ‘z’
are all integers. ‘op’ can be one of ‘+’, ‘-‘, ‘*’,
‘/’.

OPEN ENDED EXPERIMENTS


Write a C program to show the Roman number representation of a
1. given number.
Write a C program to implement the Tower of Hanoi problem
using recursion. The program should prompt the user to enter the
number of disks and then display the sequence of moves required
2. to transfer all disks from the source peg to the destination peg
using an auxiliary peg, following the rules of the Tower of
Hanoi.
Write a menu-driven C program to perform the following
operations on strings:
• Read a string.
• Display the string.
• Merge two strings.
• Copy n characters starting from the mth position.
• Calculate the length of the string.
• Count the number of uppercase
3. letters, lowercase letters, numbers,
and special characters in the string.
• Count the number of words, lines, and characters in the
string.
• Replace all occurrences of comma (’,’) with semicolon
(’;’) in the string.
• Exit the program.

Write a C program to implement a Library


Management System that allows users to:
4.
• Add new books with details like Title, Author, ISBN, and
Department of Computer Science and Engineering
Dayananda Sagar University 12
Availability Status.
• Search for a book by Title or Author.
• Issue a book (update availability status).
• Return a book.
• Display the list of all books.
• Exit the system.

Department of Computer Science and Engineering


Dayananda Sagar University 13
Sample Programs for reference

This section gives a sample implementation for the suggested lab exercises, and this

does not mean that the programs must implemented only in this manner. Students

must be encouraged to come up with the algorithm for each of the problems on their

own, and try writing the code, get it reviewed by the faculty in the lab and then try

executing the same. Faculty are requested to encourage the students to try writing

programs on their own, and to go through the process of compiling, fixing the

compilation errors, and then running and fixing any run-time errors, logical errors

on their own.

Sample programs are listed starting from the following page.

Department of Computer Science and Engineering


Dayananda Sagar University 14
1a. Write a C program to read two whole numbers, store them in variables, and
display their values with variable names. Then, swap their contents and print the
updated values.

Description:
This program takes two whole numbers as input from the user and stores them in variables a and b.
It first displays their values along with their variable names. Then, it swaps the contents of a and b
using a temporary variable and prints the updated values after swapping.

Example:

Input:

Enter two numbers: 5 10

Output:

Before swapping: a = 5, b = 10

After swapping: a = 10, b = 5

Algorithm:
Step 1: Start

Step 2: Declare three integer variables a, b, and temp

Step 3: Prompt the user to enter two whole numbers

Step 4: Read the input values and store them in a and b

Step 5: Display the values of a and b before swapping

Step 6: Perform the swapping:


• Assign a to temp (temporary storage)
• Assign b to a
• Assign temp to b

Step 7: Display the values of a and b after swapping

Step 8: Stop

Department of Computer Science and Engineering


Dayananda Sagar University 15
Source Code:

#include <stdio.h>
int main()
{
int x,
y; int
temp;

printf("Enter Value of x: ");


scanf("%d", &x);

printf("\nEnter Value of y: ");


scanf("%d", &y);

printf ("\nBefore Swapping: x = %d, y = %d", x, y);

/* swap using a temporary variable */


temp = x;
x = y;
y = temp;

printf ("\nAfter Swapping: x = %d, y = %d", x, y);


return 0;
}

Sample Output:

Enter Value of x: 23

Enter Value of y: 44

Before Swapping: x = 23, y = 44

After Swapping: x = 44, y = 23

Department of Computer Science and Engineering


Dayananda Sagar University 16
1b. Write a C program to compute simple interest using user-input values for
the principal amount, interest rate, and term. Display the calculated interest
amount.
Description:
This program calculates the simple interest based on user-input values for the principal amount,
interest rate, and time. It takes these inputs, applies the simple interest formula, and then displays
the computed interest amount. The formula used for calculation is:

Simple Interest = (Principal * Rate * Time ) / 100

Example:

Input:

Enter Principal Amount: 1000

Enter Interest Rate: 5

Enter Time Period (in years): 2

Output:

Simple Interest = 100.00

Algorithm:
Step 1: Start

Step 2: Declare three variables principal, rate, time, and one variable interest

Step 3: Prompt the user to enter the principal amount

Step 4: Read and store the principal amount in principal

Step 5: Prompt the user to enter the interest rate

Step 6: Read and store the interest rate in rate

Step 7: Prompt the user to enter the time period (in years)

Step 8: Read and store the time period in time

Step 9: Compute simple interest using the formula: Simple Interest = (Principal * Rate * Time ) / 100
Department of Computer Science and Engineering
Dayananda Sagar University 17
Step 10: Display the calculated simple interest

Step 11: Stop

Source Code:

#include <stdio.h>
int main()
{
float principal, term, rate, simpleinterest;

/* Input principal, rate and term */

printf("Enter principal (amount): ");


scanf("%f", &principal);
printf("Enter term: ");
scanf("%f", &term);
printf("Enter rate: ");
scanf("%f", &rate);

/* Calculate simple interest */


simpleinterest = (principal * term * rate) / 100;
/* Print the Simple Interest */
printf("Simple Interest = %f\n", simpleinterest);
return 0;
}

Sample Output:

Enter principal (amount): 100


Enter term: 2
Enter rate: 9
Simple Interest = 18.000000

Department of Computer Science and Engineering


Dayananda Sagar University 18
1c. Write a C program to calculate and display the factorial of a number entered
by the user.

Description:
This program calculates the factorial of a number entered by the user. The factorial of a non-negative
integer n is the product of all positive integers from 1 to n, represented as:
n! = n * (n-1) * (n-2) * …* 1
For example:
• 5! = 5 × 4 × 3 × 2 × 1 = 120
• 0! is defined as 1
Algorithm:
Step 1: Start

Step 2: Declare an integer variable n to store the user input and another variable factorial
initialized to 1

Step 3: Prompt the user to enter a number

Step 4: Read and store the number in n

Step 5: If n is 0 or 1, set factorial = 1 (since 0! = 1! = 1) and go to Step 8

Step 6: Use a loop to multiply numbers from 1 to n and update factorial


• For i = 1 to n, multiply factorial = factorial * i

Step 7: After the loop ends, factorial contains the result

Step 8: Display the factorial of n

Step 9: Stop

Source Code:

#include <stdio.h>
int main()
{
int n, i;
long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
/* shows error if the user enters a negative integer
*/ if (n < 0) {
printf(“Error: Factorial of a negative number does not exist\n”);
}
Department of Computer Science and Engineering
Dayananda Sagar University 19
else if(n==0 || n==1)
printf(“Factorial of %d = %ld\n", n, fact);
else {
for (i = 1; i <= n; i++)
{ fact = fact * i;
}
printf("Factorial of %d = %ld\n", n, fact);
}
return 0;
}

Sample Output:

Enter an integer: 10
Factorial of 10 = 3628800

Department of Computer Science and Engineering


Dayananda Sagar University 20
2. Write a C program to generate the roots of a quadratic equation. The
various parameters for the quadratic equation are to be received as
inputs from the user.

Description:
This program calculates the roots of a quadratic equation of the form:
ax2+bx+c=0
where a, b, and c are coefficients entered by the user. The roots of the equation are found
using the quadratic formula:

The program follows these steps:


• Reads values of a, b, and c from the user.
• Computes the discriminant (D = b^2 - 4ac).
• Determines the nature of the roots based on the discriminant:
• If D > 0, the equation has two distinct real roots.
• If D = 0, the equation has one real and equal root.
• If D < 0, the equation has complex roots.
• Displays the calculated roots accordingly.
Example:
Case 1: Two Real Roots
Input:
Enter coefficients a, b, c: 1 -3 2
Output:
Roots are 2.00 and 1.00
Case 2: One Repeated Root
Input:
Enter coefficients a, b, c: 1 -2 1
Output:
Root is 1.00
Case 3: Complex Roots
Input:
Enter coefficients a, b, c: 1 2 5
Output:
Roots are -1.00 + 2.00i and -1.00 - 2.00i

Department of Computer Science and Engineering


Dayananda Sagar University 21
Algorithm:
Step 1: Start

Step 2: Declare variables a, b, c (coefficients of the quadratic equation), discriminant, root1, root2,
realPart, and imaginaryPart.

Step 3: Prompt the user to enter the values of a, b, and c.

Step 4: Read and store the values of a, b, and c.

Step 5: Compute the discriminant using the formula:

D = b^2 - 4ac

Step 6: Check the value of the discriminant (D):


• If D > 0 (Two distinct real roots):
Compute root1 and root2 using:

Display root1 and root2.


• If D == 0 (One repeated real root):
Compute the single root using:

Display root1.
• If D < 0 (Complex roots):
Compute the real and imaginary parts:

• Step 7: Stop

Department of Computer Science and Engineering


Dayananda Sagar University 22
Source Code:

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

int main()
{
float
a,b,c,real,imag;
float
root1,root2,d;
printf("Enter the values of Coefficient a, b, c in a single line
with space in between:\n");
scanf("%f%f%f",&a,&b,&c);

d=((b*b)-(4*a*c)); /* Calculate the Determinant ‘d’ */


if(d==0)
{
printf("The roots are real and
equal\n"); root1=root2=((-
b)/(2*a)); printf("root1=root2 is
%.3f\n",root1);
}
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("root1 is %.3f \n root2 is %.3f \n",root1,root2);
}
else
{
printf("The roots are real and
imaginary\n"); real=(-b)/(2*a);
imag=sqrt(fabs(d))/(2*a);
printf("root1 is %.3f+i%.3f \n",real,imag);
printf("root2 is %.3f-i%.3f \n",real,imag);
}
}
Sample Output:
Enter the values of Coefficient a, b, c in a single line with space in between:
1 6 9
The roots are real and equal
root1=root2 is -3.000

Enter the values of Coefficient a, b, c in a single line with space in between:


1 2 4
The roots are real and imaginary
Root1 = -1 + i1.732
Root2 = -1 – i1.732 23
3a. Write a C program to read a number and check whether the entered number is a
palindrome.

Description:

This program checks whether a given number is a palindrome. A palindrome is a number that remains
the same when its digits are reversed.

Example:

Case 1: Palindrome Number

Input: Enter a number: 121


Output: 121 is a palindrome.

Case 2: Not a Palindrome

Input: Enter a number: 123


Output: 123 is not a palindrome.

Algorithm:
Step 1: Start

Step 2: Declare integer variables num, originalNum, reversedNum, and remainder.

Step 3: Prompt the user to enter a number.

Step 4: Read and store the number in num.

Step 5: Store the original number in originalNum for comparison later.

Step 6: Initialize reversedNum to 0.

Step 7: Reverse the number using a loop:


• While num is not 0:
• Extract the last digit using remainder = num % 10.
• Append the digit to reversedNum using reversedNum = reversedNum * 10 + remainder.
• Remove the last digit from num using num = num / 10.

Step 8: Compare originalNum with reversedNum:


• If they are equal, print "The number is a palindrome."
• Else, print "The number is not a palindrome."

Step 9: Stop
Department of Computer Science and Engineering
Dayananda Sagar University 24
Source Code:
#include <stdio.h>
int main()
{
int n, rev = 0, rem, num;

printf("Enter an integer: ");


scanf("%d", &n);

num = n;

/* reversed integer is stored in ‘rev’ variable */

while (n != 0) {
rem = n % 10;
rev = rev * 10 +
rem; n = n / 10;
}

/* It is a palindrome if original and reversed are equal

*/ if (num == rev) {
printf("%d is a palindrome\n", num);
}
else {
printf("%d is not a palindrome\n", num);
}
return 0;
}

Sample Output:

Enter an integer: 123321


123321 is a palindrome

Enter an integer: 1234


1234 is not a palindrome

Department of Computer Science and Engineering


Dayananda Sagar University 25
3b. Write a C program to calculate the ‘n’th power of a given number ‘x’. Take
both ‘n’ and ‘x’ as inputs from the user.

Description:

This program calculates the nth power of a given number x. The power of a number is defined as:

result = xn

• The user inputs the base number x and the exponent n.

• The program calculates xⁿ using a loop (without using the pow() function).

• It displays the computed result.

Example:

23 = 2 * 2 * 2 = 8

Algorithm:

Step 1: Start

Step 2: Declare integer variables x, n, result, and i.

Step 3: Prompt the user to enter the base number (x) and the exponent (n).

Step 4: Read and store the values of x and n.

Step 5: Initialize result = 1.

Step 6: Use a loop to multiply result by x, n times:


• For i = 1 to n:
• Multiply result = result * x.

Step 7: Display the final result as x^n .

Step 8: Stop

Source Code:
#include <stdio.h>
int main() {
int base, n, i, result = 1;

// Taking inputs from the user

Department of Computer Science and Engineering


Dayananda Sagar University 26
printf("Enter the base: ");
scanf("%d", &base);
printf("Enter the exponent (n): ");
scanf("%d", &n);

// Calculating power manually


for (i = 0; i < n; i++) {
result = result * base;
}

// Displaying the result


printf("%d raised to the power %d is: %d\n", base, n, result);

return 0;
}

Sample Output:

Enter the base: 2


Enter the exponent: 8
2 raised to the power 24 is: 256

Enter the base: 3


Enter the exponent: 4
3 raised to the power 4 is: 81

Department of Computer Science and Engineering


Dayananda Sagar University 27
4a. Write a C program to generate the ‘Fibonacci’ series for ‘n’ positions, take

‘n’ as an input from the user.


Description:
This program generates the Fibonacci series up to n terms, where n is provided by the user. The
Fibonacci series is a sequence of numbers where each number is the sum of the two preceding
ones, starting from 0 and 1.
Fibonacci Series Formula:
F(n) = F(n-1) + F(n-2)
where,
• F(0) = 0
• F(1) = 1
• F(2) = F(0) + F(1) = 0 + 1 = 1
• F(3) = F(1) + F(2) = 1 + 1 = 2
• and so on…
Example:
Enter the position in Fibonacci series (n): 5
The nth number in the Fibonacci series is: 3

Algorithm:
Step 1: Start

Step 2: Declare integer variables n, first = 0, second = 1, next, and i.

Step 3: Prompt the user to enter the number of terms (n).

Step 4: Read and store the value of n.

Step 5: Print the first two Fibonacci numbers (first and second).

Step 6: Use a loop to generate the remaining Fibonacci numbers:


• For i = 3 to n:
• Compute next = first + second.
• Print next.
• Update first = second.
• Update second = next.

Step 7: Stop

Department of Computer Science and Engineering


Dayananda Sagar University 28
Source Code:

#include <stdio.h>
int main()
{
int i,term1=0,term2=1,n,fib;

printf("Enter the position in Fibonacci series (n):\n");


scanf("%d",&n);

if( n <= 0) {
printf("Enter a number greater than 0\n");
return 0;
}
else if( n == 1) {
fib = 0;
}
else if ( n == 2 ) {
fib = 1;
}
else {
for (int i = 2; i < n; i++)
{
fib = term1 + term2;
term1 = term2;
term2 = fib;
}
}
printf("The nth number in the Fibonacci series is:%d\n",fib);
return 0;
}

Sample Output:

Enter the position in Fibonacci series (n):


5
The nth number in the Fibonacci series is: 3

Enter the position in Fibonacci series (n):


12
The nth number in the Fibonacci series is: 89

Department of Computer Science and Engineering


Dayananda Sagar University 29
4b. Write a C program that takes two numbers ‘x’ and ‘y’ as input and
calculates the Greatest Common Divisor (GCD) of them and displays the
result.

Description:

This program calculates the Greatest Common Divisor (GCD) of two numbers x and y using
Euclid’s Algorithm. The GCD is the largest number that divides both x and y exactly.

Euclid’s Algorithm for GCD:

1. If y = 0 , then GCD(x, y) = x.

2. Otherwise, replace x with y and y with x \mod y , and repeat the process until y becomes 0.

3. The final value of x is the GCD.

Example:

GCD of 48 and 18 is 6

Algorithm:
Step 1: Start

Step 2: Declare integer variables x and y.

Step 3: Prompt the user to enter two numbers (x and y).

Step 4: Read and store the values of x and y.

Step 5: Apply Euclid’s Algorithm:


• Repeat until y becomes 0:
• Compute remainder = x % y.
• Assign x = y.
• Assign y = remainder.

Step 6: When y becomes 0, x holds the GCD.

Step 7: Print the GCD.

Department of Computer Science and Engineering


Dayananda Sagar University 30
Source Code:

#include <stdio.h>

int main() {
int x, y, temp;

// Taking input from the user


printf("Enter two numbers: ");
scanf("%d %d", &x, &y);

// Calculating GCD using Euclidean algorithm


while (y != 0) {
temp
= y;
y = x
% y;
x =
temp;
}

// Displaying the result


printf("GCD is: %d\n", x);

return 0;
}

Sample Output:

Enter two numbers 13 39


GCD is : 13

Enter two numbers 6 9


GCD is : 3

Department of Computer Science and Engineering


Dayananda Sagar University 31
5. Write a C program that takes two numbers, x and y, as input and stores them
in separate variables. The program should then read a single character
representing an operator (+, -, *, or /). It should perform the corresponding
arithmetic operation (x op y), display the result, and then wait for another
operator input. If the user enters 'q' instead of one of the four operators, the
program should terminate.
Description:

This program allows the user to perform arithmetic operations on two numbers x and y. The
program follows these steps:

• The user enters two numbers, x and y.

• The program then repeatedly asks the user to enter an operator (+, -, *, or /).

• It performs the corresponding arithmetic operation (x op y) and displays the result.

• The program continues to take operator inputs and perform calculations.

• If the user enters ‘q’, the program terminates.

This program uses a loop and switch-case structure to handle multiple operations until the user
decides to quit.

Algorithm:
Step 1: Start

Step 2: Declare variables x, y, operator, and result.

Step 3: Prompt the user to enter two numbers (x and y).

Step 4: Read and store the values of x and y.

Step 5: Repeat until the user enters ‘q’:


• Prompt the user to enter an operator (+, -, *, /) or 'q' to quit.
• Read the operator.
• Using a switch-case or if-else:
• If operator == '+', compute result = x + y and display the result.
• If operator == '-', compute result = x - y and display the result.
• If operator == '*', compute result = x * y and display the result.
• If operator == '/', check if y is not zero:
• If y ≠ 0, compute result = x / y and display the result.
Department of Computer Science and Engineering
Dayananda Sagar University 32
• Otherwise, print an error message for division by zero.
• If operator == 'q', exit the loop.
• Otherwise, display an “Invalid operator” message.

Step 6: Print “Program terminated” when the loop ends.

Step 7: Stop.

Source Code:

#include <stdio.h>

int main() {
int x, y, result;
char op;

// Taking input for numbers


printf("Enter two numbers: ");
scanf("%d %d", &x, &y);

while (1) {
// Taking input for operator
printf("Enter an operator (+, -, *, /) or 'q' to quit: ");
scanf(" %c", &op);

// Check for exit condition


if (op == 'q') {
printf("Exiting program.\n");
break;
}

// Perform arithmetic operation using switch


switch (op) {
case '+':
result = x + y;
printf("Result: %d + %d = %d\n", x, y, result);
break;
case '-':
result = x - y;
printf("Result: %d - %d = %d\n", x, y, result);
break;
case '*':
result = x * y;
printf("Result: %d * %d = %d\n", x, y, result);
Department of Computer Science and Engineering
Dayananda Sagar University 33
break;
case '/':
if (y != 0) {
result = x / y;
printf("Result: %d / %d = %d\n", x, y, result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operator. Please enter +, -, *, /, or 'q'
to quit.\n");
}
}

return 0;
}

Sample Output:

Enter two numbers: 9 3


Enter an operator (+, -, *, /) or q to quit
+
Result: 9 + 3 = 12
Enter an operator (+, -, *, /) or q to quit
-
Result: 9 - 3 = 6
Enter an operator (+, -, *, /) or q to quit
*
Result: 9 * 3 = 27
Enter an operator (+, -, *, /) or q to quit
/
Result: 9 / 3 = 3
Enter an operator (+, -, *, /) or q to quit
q
Exiting program.

Department of Computer Science and Engineering


Dayananda Sagar University 34
6a. Write a C program that reads a string from the user and prints the length of
the string. Program must implement the logic to calculate the length and not
use a library function.
Description:
This program reads a string input from the user and calculates its length without using any built-in
string functions like strlen().
• The program takes a string as input and stores it in an array.
• It iterates through the string character by character until it reaches the null terminator
('\0'), which marks the end of the string.
• A counter variable keeps track of the number of characters in the string.
• Finally, the program displays the length of the string.
Example: Enter a string: Hello
Length of the string: 5

Algorithm:
Step 1: Start

Step 2: Declare a character array str to store the string and an integer variable length to keep count.

Step 3: Prompt the user to enter a string.

Step 4: Read the input string and store it in str.

Step 5: Initialize length = 0.

Step 6: Loop through the string until the null terminator ('\0') is encountered:
• Increment length for each character in the string.

Step 7: Once the loop ends, length contains the total number of characters in the string.

Step 8: Print the value of length.

Step 9: Stop.

Source Code:

#include <stdio.h>

int main() {
char str[100];
int length = 0, i = 0;
Department of Computer Science and Engineering
Dayananda Sagar University 36
// Taking input from the user
printf("Enter a string: ");
scanf("%s", str);

// Calculating string length manually


while (str[i] != '\0') {
length++;
i++;
}

// Displaying the length of the string


printf("Length of the string: %d\n", length);

return 0;
}

Sample Output:

Enter a string:
Engineering

Length of the string: 11

Enter a string:
Hello

Length of the string: 5

Department of Computer Science and Engineering


Dayananda Sagar University 37
6b. Write a C program that reads two strings, joins them into another variable,

and prints the concatenated result. Use static memory allocation with a fixed
size.

Description:
This program reads two strings from the user and concatenates them manually without using the
built-in strcat() function.

• The program stores both strings in separate character arrays using static memory
allocation with a fixed size.

• It then copies the first string into a third array (for the concatenated result).

• After that, it appends the second string character by character to the third array.

• Finally, the program prints the concatenated string.

Example:

Enter first string: Hello

Enter second string: World

Concatenated string: HelloWorld

Algorithm:
Step 1: Start

Step 2: Declare three character arrays:


• str1 to store the first string
• str2 to store the second string
• result to store the concatenated string (with a fixed size)

Step 3: Prompt the user to enter the first string and store it in str1.

Step 4: Prompt the user to enter the second string and store it in str2.

Step 5: Initialize an index variable i = 0 and copy characters of str1 into result using a loop until
'\0' is encountered.

Step 6: Initialize another index variable j = 0 and append characters of str2 into result starting
from where str1 ended.

Step 7: After copying both strings, append a null terminator ('\0') at the end of result to mark the
end of the string.

Step 8: Print the concatenated string stored in result.


Department of Computer Science and Engineering
Dayananda Sagar University 28
Step 9: Stop.

Source Code:
#include <stdio.h>

int main() {
char str1[50], str2[50], result[100];
int i = 0, j = 0;

// Taking input for two strings


printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);

// Copying first string into result


while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
// Appending second string to result
while (str2[j] != '\0') {
result[i] = str2[j];
i++;
j++;
}
result[i] = '\0'; // Null terminate the concatenated string

// Displaying the concatenated result


printf("Concatenated string: %s\n", result);

return 0;
}

Sample Output:
Enter first string: Hello
Enter second string: World
Concatenated String: HelloWorld

Department of Computer Science and Engineering


Dayananda Sagar University 29
6c. Write a C program that takes a string as input from the user, reverses it in place, and then
prints the reversed string.

Description:
This program reads a string from the user and reverses it in place without using any built-in string
functions like strrev().

• The program stores the string in a character array with a fixed size.

• It then uses a two-pointer approach:

• One pointer starts at the beginning (left), and the other at the end (right).

• The characters at these positions are swapped iteratively until they meet in the middle.

• Finally, the program prints the reversed string.

Example:

Enter a string: hello

Reversed string: olleh

Algorithm:
Step 1: Start

Step 2: Declare a character array str to store the string and two integer variables left and right.

Step 3: Prompt the user to enter a string and store it in str.

Step 4: Initialize left = 0 (pointing to the first character) and right = length of the string - 1
(pointing to the last character).

Step 5: Loop until left is less than right


• Swap str[left] and str[right]
• Increment left and decrement right

Step 6: When left meets right, the string is fully reversed.

Step 7: Print the reversed string.

Step 8: Stop.

Source Code:
#include <stdio.h>
#include <string.h>

int main() {
Department of Computer Science and Engineering
Dayananda Sagar University 30
char str[100];
int i, len;
char temp;

// Taking input from the user


printf("Enter a string: ");
scanf("%s", str);

len = strlen(str); // Get string length

// In-place reversal
for (i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}

// Displaying the reversed string


printf("Reversed string: %s\n", str);

return 0;
}

Sample Output:

Enter a string: Hello


Reversed string: olleH

Enter a string: Malayalam


Reversed string: malayalaM

Department of Computer Science and Engineering


Dayananda Sagar University 31
7. Write a program that reads ‘n’ numbers and stores them in an array in the
same order as entered. First, it prints the numbers in their original order.
Then, it sorts the array in ascending order and prints the sorted numbers.

Description:

This program reads ‘n’ numbers from the user and stores them in an array in the same order they
were entered.
• First, the program prints the numbers in their original order to show how they were entered.
• Then, it sorts the array in ascending order using a simple sorting algorithm (like Bubble Sort or
Selection Sort).
• Finally, the program prints the sorted array to show the numbers in increasing order.

Example:
Enter the number of elements: 5
Enter the numbers: 8 3 7 1 5
Sorted array: 1 3 5 7 8
Algorithm:

Step 1: Start

Step 2: Declare an integer array arr[n] and variables n, i, j, temp.

Step 3: Prompt the user to enter the number of elements (n) and store it in n.

Step 4: Use a loop to read n numbers from the user and store them in the array arr.

Step 5: Print the original array (numbers in the order entered).

Step 6: Sort the array in ascending order using a simple sorting algorithm:
• Use a loop with index i from 0 to n-1.
• Inside this loop, use another loop with index j from i+1 to n.
• If arr[i] > arr[j], swap arr[i] and arr[j].

Step 7: Print the sorted array.

Step 8: Stop.

Department of Computer Science and Engineering


Dayananda Sagar University 32
Source Code:

#include <stdio.h>

int main() {
int n, i, j, temp;

// Taking input for the number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n];

// Reading n numbers into the


array printf("Enter %d
numbers: ", n); for (i = 0; i
< n; i++) {
scanf("%d", &arr[i]);
}

// Printing the original


array printf("Original
order: "); for (i = 0; i
< n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Sorting the array in ascending order (Bubble


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

// Printing the sorted


array printf("Sorted
order: "); for (i = 0;
i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Department of Computer Science and Engineering


Dayananda Sagar University 33
Sample Output:

Enter the number of elements: 5


Enter 5 numbers: 23
2
1
4
6
Original order: 23 2 1 4 6
Sorted order: 1 2 4 6 23

Department of Computer Science and Engineering


Dayananda Sagar University 34
8. Write a program that searches for a specific number in a pre-initialized
array. The number to be searched is taken as input from the user, and the
program prints an appropriate message indicating whether the number is
found or not.

Description:

This program searches for a specific number in a pre-initialized array.


• The array is already defined with some numbers.
• The user enters the number to be searched.
• The program scans the array using a simple linear search technique.
• If the number is found, it displays a success message along with its position.
• If the number is not found, it prints a failure message.

Example:
arr[] = {10, 25, 30, 45, 50}
Enter the number to search: 30
Number 30 found at position 3.

Algorithm:

Step 1: Start

Step 2: Declare an integer array arr[] with pre-initialized values and variables n, i, found = 0.

Step 3: Display the contents of the array for reference.

Step 4: Prompt the user to enter the number to search (n) and store it in n.

Step 5: Perform a linear search:


• Use a loop to traverse the array from index i = 0 to the last index.
• If arr[i] == n, set found = 1 and print the position (i+1 for 1-based index).
• Exit the loop.

Step 6: If found is still 0, print “Number not found in the array.”

Step 7: Stop.

Department of Computer Science and Engineering


Dayananda Sagar University 36
Source Code:

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; // Pre-
initialized array
int size = sizeof(arr) / sizeof(arr[0]); // Calculate array size
int num, i, found = 0;

// Taking input from the user


printf("Enter a number to search: ");
scanf("%d", &num);

// Linear search algorithm


for (i = 0; i < size; i++) {
if (arr[i] == num) {
found = 1;
printf("Number %d is found at index %d.\n", num, i);
break;
}
}
// Printing the result if not found
if (!found) {
printf("Number %d is not found in the array.\n", num);
}

return 0;
}

Sample Output:

Enter a number to search: 70

Number 70 is found at index 6

Enter a number to search: 5

Number 5 is not found in the array

Department of Computer Science and Engineering


Dayananda Sagar University 37
9. Write a program that uses a function to swap two numbers. The function
takes as input the pointers to the two variables that contain the values to be
swapped.

Description:

This program demonstrates how to swap two numbers using a function with pointers in C.

• The user enters two numbers.

• A function swap() is used to swap their values.

• The function takes pointers to the two numbers as arguments.

• Using pointer dereferencing, the values are swapped inside the function.

• After returning from the function, the swapped values are displayed.

Example:

Enter two numbers: 5 10

After swapping: 10 5

Algorithm:

Step 1: Start

Step 2: Declare two integer variables a and b to store the user-input values.

Step 3: Prompt the user to enter two numbers and store them in a and b.

Step 4: Define a function swap(int *x, int *y) that:


• Takes pointers to a and b as arguments.
• Uses a temporary variable to swap their values.
• Updates the values in the original memory locations using pointer dereferencing.

Step 5: Call swap(&a, &b) to pass the addresses of a and b.

Step 6: Print the values of a and b after swapping.

Step 7: Stop.

Department of Computer Science and Engineering


Dayananda Sagar University 38
Source code:

#include <stdio.h>

void swap(int *p, int *q);

int main()
{
int x, y;

printf("Enter the value of x:");


scanf("%d", &x);

printf("Enter the value of y:");


scanf("%d",&y);

printf("Before Swapping\nx = %d\ny = %d\n", x,

y); swap(&x, &y);

printf("After Swapping\nx = %d\ny = %d\n", x, y);

return 0;
}

void swap(int *p, int *q)


{
int temp;

temp = *p;
*p = *q;
*q = temp;
}

Sample Output:

Enter the value of x:201


Enter the value of y:123
Before Swapping
x = 201
y = 123
After Swapping
x = 123
y = 201

Department of Computer Science and Engineering


Dayananda Sagar University 39
10. Write a program that can parse a simple arithmetic expression of type (x op
y op z). The program can make use of all the available string manipulation
functions to parse the string efficiently. The arithmetic expression is given as
an input by the user. ‘x’, ‘y’, ‘z’ are all integers. ‘op’ can be one of ‘+’, ‘- ‘, ‘*’,
‘/’. (the syntax for the expression has the space character between any operand
and operator)

Description:
This program parses and evaluates a simple arithmetic expression of the form:
x op y op z
where:
• x, y, and z are integers.
• op is an operator (+, -, *, or /).
• The expression contains spaces between numbers and operators.
Example:
Enter an expression: 5 + 3 * 2
Result: 11

Algorithm:
Step 1: Start

Step 2: Declare a string variable to store the user-input expression.

Step 3: Prompt the user to enter an arithmetic expression in the format x op y op z (with spaces
between numbers and operators).

Step 4: Read the input string.

Step 5: Parse the string to extract:


• The first integer (x)
• The first operator (op1)
• The second integer (y)
• The second operator (op2)
• The third integer (z)

Step 6: Perform the calculations based on operator precedence:


• If op2 is * or /, evaluate y op2 z first, then compute x op1 result.
• Otherwise, compute x op1 y first, then apply op2 to z.
Department of Computer Science and Engineering
Dayananda Sagar University 40
Step 7: Display the final result.

Step 8: Stop.

Source Code:

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

int main() {
int x, y, z, result;
char op1, op2;

// Taking input from the user


printf("Enter an arithmetic expression (x op y op z): ");
scanf("%d %c %d %c %d", &x, &op1, &y, &op2, &z);

// Performing the first


operation switch(op1) {
case '+': result = x + y;
break; case '-': result = x
- y; break; case '*':
result = x * y; break;
case '/': result = (y != 0) ? x / y : 0; break;
default: printf("Invalid operator!\n"); return 1;
}

// Performing the second


operation switch(op2) {
case '+': result += z;
break; case '-': result
-= z; break; case '*':
result *= z; break;
case '/': result = (z != 0) ? result / z : 0;
break; default: printf("Invalid operator!\n");
return 1;
}

// Printing the result


printf("Result: %d\n", result);
return 0;
}

Department of Computer Science and Engineering


Dayananda Sagar University 41
Sample Output:

Enter an arithmetic expression of the form (x op y op z): 1 + 2 + 3

Result : 6

Enter an arithmetic expression of the form (x op y op z): 2 * 5 / 2

Result : 5

Enter an arithmetic expression of the form (x op y op z): 201 / 2 * 6

Result : 600

Department of Computer Science and Engineering


Dayananda Sagar University 42
OPEN ENDED EXPERIMENTS

1. Write a C program to show the Roman number representation of a given


number.

#include <stdio.h>
int main()
{
int number;
int ones, tens, hundreds, thousand;
printf("\n Enter any number (1-3000): ");
scanf("%d", &number);

if (number==0||number>3000)
printf ("\n INVALID NUMBER");
thousand = number/1000;
hundreds = ((number/100)%10) ;
tens = ((number/10)%10) ;
ones = ((number/1)%10) ;

if (thousand == 1)
printf("M");
else if (thousand == 2)
printf("MM");
else if (thousand == 3)
printf("MMM");

if (hundreds == 1)
printf("C");
else if (hundreds == 2)
printf("CC");
else if (hundreds == 3)
printf("CCC");
else if (hundreds == 4)
printf("CD");
else if (hundreds == 5)
printf("D");
else if (hundreds == 6)
printf("DC");
else if (hundreds == 7)
printf("DCC");
else if (hundreds == 8)
printf("DCCC");
else if (hundreds == 9)
printf("CM");

Department of Computer Science and Engineering


Dayananda Sagar University 43
if (tens ==1)
printf("X");
else if (tens == 2)
printf("XX");
else if (tens == 3)
printf ("XXX");
else if (tens == 4)
printf("XL");
else if (tens ==5)
printf("L");
else if (tens == 6)
printf ("LX");
else if (tens == 7)
printf ("LXX");
else if (tens ==8)
printf ("LXXX");
else if (tens == 9)
printf ("XC");

if (ones ==1)
printf("I");
else if (ones == 2)
printf("II");
else if (ones == 3)
printf ("III");
else if (ones == 4)
printf("IV");
else if (ones ==5)
printf("V");
else if (ones == 6)
printf ("VI");
else if (ones == 7)
printf ("VII");
else if (ones ==8)
printf ("VIII");
else if (ones == 9)
printf ("IX");

return 0;
}

Sample Output:

Enter any number (1-3000): 139


CXXXIX

Department of Computer Science and Engineering


Dayananda Sagar University 44
2. Write a C program to implement the Tower of Hanoi problem using recursion. The
program should prompt the user to enter the number of disks and then display the
sequence of moves required to transfer all disks from the source peg to the destination
peg using an auxiliary peg, following the rules of the Tower of Hanoi.

#include <stdio.h>

// Function to solve Tower of Hanoi

void towerOfHanoi(int n, char source, char auxiliary, char destination) {

if (n == 1) {

printf("Move disk 1 from %c to %c\n", source, destination);

return;

// Move n-1 disks from source to auxiliary using destination as buffer

towerOfHanoi(n - 1, source, destination, auxiliary);

// Move the nth disk from source to destination

printf("Move disk %d from %c to %c\n", n, source, destination);

// Move the n-1 disks from auxiliary to destination using source as buffer

towerOfHanoi(n - 1, auxiliary, source, destination);

int main() {

int n;

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

scanf("%d", &n);

// Call the function with initial parameters (A, B, C are rod names)

towerOfHanoi(n, 'A', 'B', 'C');

return 0;

Department of Computer Science and Engineering


Dayananda Sagar University 45
Enter the number of disks: 3
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Department of Computer Science and Engineering


Dayananda Sagar University 46
3. Write a menu-driven C program to perform the following operations on strings:
1. Read a string.
2. Display the string.
3. Merge two strings.
4. Copy n characters starting from the mth position.
5. Calculate the length of the string.
6. Count the number of uppercase letters, lowercase letters, numbers, and special
characters in the string.
7. Count the number of words, lines, and characters in the string.
8. Replace all occurrences of comma (’,’) with semicolon (’;’) in the string.
9. Exit the program.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX 1000

void readString(char str[]) {


printf("Enter a string: ");
getchar(); // To consume newline character
fgets(str, MAX, stdin);
str[strcspn(str, "\n")] = 0; // Remove newline character
}

void displayString(char str[]) {


printf("Stored String: %s\n", str);
}

void mergeStrings(char str1[], char str2[]) {


char merged[MAX * 2];
strcpy(merged, str1);
strcat(merged, str2);
printf("Merged String: %s\n", merged);
}

void copyNCharacters(char str[], int m, int n) {


char copy[MAX];
strncpy(copy, &str[m], n);
copy[n] = '\0';
printf("Copied substring: %s\n", copy);
}

void stringLength(char str[]) {


printf("Length of the string: %ld\n", strlen(str));
Department of Computer Science and Engineering
Dayananda Sagar University 47
}

void countCharacterTypes(char str[]) {


int upper = 0, lower = 0, digit = 0, special = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) upper++;
else if (islower(str[i])) lower++;
else if (isdigit(str[i])) digit++;
else special++;
}
printf("Uppercase: %d, Lowercase: %d, Numbers: %d, Special: %d\n", upper, lower,
digit, special);
}

void countWordsLinesCharacters(char str[]) {


int words = 0, lines = 1, characters = 0;
for (int i = 0; str[i] != '\0'; i++) {
characters++;
if (str[i] == ' ' || str[i] == '\n') words++;
if (str[i] == '\n') lines++;
}
printf("Words: %d, Lines: %d, Characters: %d\n", words + 1, lines, characters);
}

void replaceCommaWithSemicolon(char str[]) {


for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ',') str[i] = ';';
}
printf("Modified String: %s\n", str);
}

int main() {
char str1[MAX] = "", str2[MAX] = "";
int choice, m, n;

do {
printf("\nMenu:\n");
printf("1. Read a string\n2. Display the string\n3. Merge two strings\n");
printf("4. Copy n characters from m position\n5. Calculate length\n");
printf("6. Count uppercase, lowercase, numbers, and special characters\n");
printf("7. Count words, lines, and characters\n8. Replace ',' with ';'\n9. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

Department of Computer Science and Engineering


Dayananda Sagar University 48
switch (choice) {
case 1:
readString(str1);
break;
case 2:
displayString(str1);
break;
case 3:
printf("Enter second string: ");
getchar(); // To consume newline character
fgets(str2, MAX, stdin);
str2[strcspn(str2, "\n")] = 0;
mergeStrings(str1, str2);
break;
case 4:
printf("Enter m and n: ");
scanf("%d %d", &m, &n);
copyNCharacters(str1, m, n);
break;
case 5:
stringLength(str1);
break;
case 6:
countCharacterTypes(str1);
break;
case 7:
countWordsLinesCharacters(str1);
break;
case 8:
replaceCommaWithSemicolon(str1);
break;
case 9:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 9);

return 0;
}

Department of Computer Science and Engineering


Dayananda Sagar University 49
Menu:
1. Read a string
2. Display the string
3. Merge two strings
4. Copy n characters from m position
5. Calculate length
6. Count uppercase, lowercase, numbers, and special
characters
7. Count words, lines, and characters
8. Replace ',' with ';'
9. Exit
Enter your choice: 1
Enter a string: hello

Menu:
1. Read a string
2. Display the string
3. Merge two strings
4. Copy n characters from m position
5. Calculate length
6. Count uppercase, lowercase, numbers, and special
characters
7. Count words, lines, and characters
8. Replace ',' with ';'
9. Exit
Enter your choice: 2
Stored String: hello

Menu:
1. Read a string
2. Display the string
3. Merge two strings
4. Copy n characters from m position
5. Calculate length
6. Count uppercase, lowercase, numbers, and special
characters
7. Count words, lines, and characters
8. Replace ',' with ';'
9. Exit
Enter your choice: 3
Enter second string: python
Merged String: hellopython

Department of Computer Science and Engineering


Dayananda Sagar University 50
4. Write a C program to implement a Library Management System that allows users to:
• Add new books with details like Title, Author, ISBN, and Availability Status.
• Search for a book by Title or Author.
• Issue a book (update availability status).
• Return a book.
• Display the list of all books.
• Exit the system.

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

#define MAX_BOOKS 100

typedef struct {
char title[100];
char author[100];
char isbn[20];
int available;
} Book;

Book library[MAX_BOOKS];
int bookCount = 0;

void addBook() {
if (bookCount >= MAX_BOOKS) {
printf("Library is full! Cannot add more books.\n");
return;
}
printf("Enter book title: ");
getchar();
fgets(library[bookCount].title, 100, stdin);
library[bookCount].title[strcspn(library[bookCount].title, "\n")] = 0;

printf("Enter author name: ");


fgets(library[bookCount].author, 100, stdin);
library[bookCount].author[strcspn(library[bookCount].author, "\n")] = 0;

printf("Enter ISBN: ");


fgets(library[bookCount].isbn, 20, stdin);
library[bookCount].isbn[strcspn(library[bookCount].isbn, "\n")] = 0;

library[bookCount].available = 1;

Department of Computer Science and Engineering


Dayananda Sagar University 51
bookCount++;
printf("Book added successfully!\n");
}

void displayBooks() {
if (bookCount == 0) {
printf("No books in the library.\n");
return;
}
printf("\nLibrary Books:\n");
for (int i = 0; i < bookCount; i++) {
printf("Title: %s, Author: %s, ISBN: %s, Available: %s\n",
library[i].title, library[i].author, library[i].isbn,
library[i].available ? "Yes" : "No");
}
}

void issueBook() {
char isbn[20];
printf("Enter ISBN of the book to issue: ");
getchar();
fgets(isbn, 20, stdin);
isbn[strcspn(isbn, "\n")] = 0;

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


if (strcmp(library[i].isbn, isbn) == 0) {
if (library[i].available) {
library[i].available = 0;
printf("Book issued successfully!\n");
} else {
printf("Book is already issued!\n");
}
return;
}
}
printf("Book not found!\n");
}

void returnBook() {
char isbn[20];
printf("Enter ISBN of the book to return: ");
getchar();
fgets(isbn, 20, stdin);
isbn[strcspn(isbn, "\n")] = 0;
Department of Computer Science and Engineering
Dayananda Sagar University 52
for (int i = 0; i < bookCount; i++) {
if (strcmp(library[i].isbn, isbn) == 0) {
if (!library[i].available) {
library[i].available = 1;
printf("Book returned successfully!\n");
} else {
printf("Book was not issued!\n");
}
return;
}
}
printf("Book not found!\n");
}

int main() {
int choice;
do {
printf("\nLibrary Management System\n");
printf("1. Add a book\n");
printf("2. Display all books\n");
printf("3. Issue a book\n");
printf("4. Return a book\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
addBook();
break;
case 2:
displayBooks();
break;
case 3:
issueBook();
break;
case 4:
returnBook();
break;
case 5:
printf("Exiting...\n");
break;
default:
Department of Computer Science and Engineering
Dayananda Sagar University 53
printf("Invalid choice! Please try again.\n");
}
} while (choice != 5);

return 0;
}

Sample Output:
Library Management System
1. Add a book
2. Display all books
3. Issue a book
4. Return a book
5. Exit
Enter your choice: 1
Enter book title: C programming
Enter author name: Reema Thareja
Enter ISBN: 93-547-980
Book added successfully!

Library Management System


1. Add a book
2. Display all books
3. Issue a book
4. Return a book
5. Exit
Enter your choice: 1
Enter book title: Operating systems
Enter author name: Tanenbaum
Enter ISBN: 987-087-234
Book added successfully!

Library Management System


1. Add a book
2. Display all books
3. Issue a book
4. Return a book
5. Exit
Enter your choice: 2

Library Books:
Title: C programming, Author: Reema Thareja, ISBN: 93-547-980, Available: Yes
Title: Operating systems, Author: Tanenbaum, ISBN: 987-087-234, Available: Yes

****** End of Document ******


Department of Computer Science and Engineering
Dayananda Sagar University 54

You might also like