CPPS_2025_Lab_Manual
CPPS_2025_Lab_Manual
SCHOOL OF ENGINEERING
SCHOOL OF ENGINEERING
Lab Manual
C PROGRAMMING FOR PROBLEM SOLVING
24EN1202
COMPUTER SCIENCE & ENGINEERING
2024-2025
NAME:
………………………………………………………
USN:
…………………………………………………………
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:
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.
Vision
To be recognized as a department of eminence in Computer Science and Engineering focusing on
sustainability, inclusive technologies, and societal needs.
Mission
§ M1: Impart quality technical education by designing and delivering contemporary Computer
Science Engineering curricula while emphasizing leadership, ethics, values, and integrity.
§ M3: Prepare Computer Science and Engineering graduates to meet ever-growing societal needs.
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:
Maximum Obtained
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
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.
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.
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:
Output:
Before swapping: a = 5, b = 10
Algorithm:
Step 1: Start
Step 8: Stop
#include <stdio.h>
int main()
{
int x,
y; int
temp;
Sample Output:
Enter Value of x: 23
Enter Value of y: 44
Example:
Input:
Output:
Algorithm:
Step 1: Start
Step 2: Declare three variables principal, rate, time, and one variable interest
Step 7: Prompt the user to enter the time period (in years)
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
Source Code:
#include <stdio.h>
int main()
{
float principal, term, rate, simpleinterest;
Sample Output:
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 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
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:
Step 2: Declare variables a, b, c (coefficients of the quadratic equation), discriminant, root1, root2,
realPart, and imaginaryPart.
D = b^2 - 4ac
Display root1.
• If D < 0 (Complex roots):
Compute the real and imaginary parts:
• Step 7: Stop
#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);
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:
Algorithm:
Step 1: Start
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;
num = n;
while (n != 0) {
rem = n % 10;
rev = rev * 10 +
rem; n = n / 10;
}
*/ if (num == rev) {
printf("%d is a palindrome\n", num);
}
else {
printf("%d is not a palindrome\n", num);
}
return 0;
}
Sample Output:
Description:
This program calculates the nth power of a given number x. The power of a number is defined as:
result = xn
• The program calculates xⁿ using a loop (without using the pow() function).
Example:
23 = 2 * 2 * 2 = 8
Algorithm:
Step 1: Start
Step 3: Prompt the user to enter the base number (x) and the exponent (n).
Step 8: Stop
Source Code:
#include <stdio.h>
int main() {
int base, n, i, result = 1;
return 0;
}
Sample Output:
Algorithm:
Step 1: Start
Step 5: Print the first two Fibonacci numbers (first and second).
Step 7: Stop
#include <stdio.h>
int main()
{
int i,term1=0,term2=1,n,fib;
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:
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.
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.
Example:
GCD of 48 and 18 is 6
Algorithm:
Step 1: Start
#include <stdio.h>
int main() {
int x, y, temp;
return 0;
}
Sample Output:
This program allows the user to perform arithmetic operations on two numbers x and y. The
program follows these steps:
• The program then repeatedly asks the user to enter an operator (+, -, *, or /).
This program uses a loop and switch-case structure to handle multiple operations until the user
decides to quit.
Algorithm:
Step 1: Start
Step 7: Stop.
Source Code:
#include <stdio.h>
int main() {
int x, y, result;
char op;
while (1) {
// Taking input for operator
printf("Enter an operator (+, -, *, /) or 'q' to quit: ");
scanf(" %c", &op);
return 0;
}
Sample Output:
Algorithm:
Step 1: Start
Step 2: Declare a character array str to store the string and an integer variable length to keep count.
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 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);
return 0;
}
Sample Output:
Enter a string:
Engineering
Enter a string:
Hello
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.
Example:
Algorithm:
Step 1: Start
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.
Source Code:
#include <stdio.h>
int main() {
char str1[50], str2[50], result[100];
int i = 0, j = 0;
return 0;
}
Sample Output:
Enter first string: Hello
Enter second string: World
Concatenated String: HelloWorld
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.
• 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.
Example:
Algorithm:
Step 1: Start
Step 2: Declare a character array str to store the string and two integer variables left and right.
Step 4: Initialize left = 0 (pointing to the first character) and right = length of the string - 1
(pointing to the last character).
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;
// In-place reversal
for (i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
return 0;
}
Sample Output:
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 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 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 8: Stop.
#include <stdio.h>
int main() {
int n, i, j, temp;
int arr[n];
return 0;
}
Description:
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 4: Prompt the user to enter the number to search (n) and store it in n.
Step 7: Stop.
#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;
return 0;
}
Sample Output:
Description:
This program demonstrates how to swap two numbers using a function with pointers in C.
• Using pointer dereferencing, the values are swapped inside the function.
• After returning from the function, the swapped values are displayed.
Example:
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 7: Stop.
#include <stdio.h>
int main()
{
int x, y;
return 0;
}
temp = *p;
*p = *q;
*q = temp;
}
Sample Output:
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 3: Prompt the user to enter an arithmetic expression in the format x op y op z (with spaces
between numbers and operators).
Step 8: Stop.
Source Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int x, y, z, result;
char op1, op2;
Result : 6
Result : 5
Result : 600
#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");
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:
#include <stdio.h>
if (n == 1) {
return;
// Move the n-1 disks from auxiliary to destination using source as buffer
int main() {
int n;
scanf("%d", &n);
// Call the function with initial parameters (A, B, C are rod names)
return 0;
#include <stdio.h>
#include <string.h>
#include <ctype.h>
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);
return 0;
}
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
#include <stdio.h>
#include <string.h>
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;
library[bookCount].available = 1;
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;
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 Books:
Title: C programming, Author: Reema Thareja, ISBN: 93-547-980, Available: Yes
Title: Operating systems, Author: Tanenbaum, ISBN: 987-087-234, Available: Yes