PPS Lab
PPS Lab
JNTUH - R23
PREPARED BY
Dr. Afreen Bari,
Baseer Fatima & Kausar Jahan
SYLLABUS
CS108ES - PROGRAMMING FOR PROBLEM SOLVING LABORATORY
B.Tech. I Year I Sem. L T P C 0 0 2 1
Course Objectives:
The students will learn the following:
● To work with an IDE to create, edit, compile, run and debug programs
● To analyze the various steps in program development.
● To develop programs to solve basic problems by understanding basic concepts in C like operators, control
statements etc.
● To develop modular, reusable and readable C Programs using the concepts like functions, arrays etc.
● To Write programs using the Dynamic Memory Allocation concept.
● To create, read from and write to text and binary files
Course Outcomes:
The candidate is expected to be able to:
● Formulate the algorithms for simple problems
● Translate given algorithms to a working and correct program
● Correct syntax errors as reported by the compilers
● Identify and correct logical errors encountered during execution
● Represent and manipulate data with arrays, strings and structures
● Use pointers of different types
● Create, read and write to and from simple text and binary files
● Modularize the code with functions so that they can be reused
Practice sessions:
a. Write a simple program that prints the results of all the operators available in C (including pre/post increment
, bitwise and/or/not , etc.). Read required operand values from standard input.
b. Write a simple program that converts one given data type to another using auto conversion and casting. Take
the values from standard input.
a. Write a program for finding the max and min from the three numbers.
b. Write the program for the simple, compound interest.
c. Write a program that declares Class awarded for a given percentage of marks, where mark
<40%= Failed, 40% to <60% = Second class, 60% to <70%=First class, >= 70% = Distinction.
Read percentage from standard input.
d. Write a program that prints a multiplication table for a given number and the number of rows in
the table. For example, for a number 5 and rows = 3, the output should be:
5x1=5
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 1
5 x 2 = 10
5 x 3 = 15
e. Write a program that shows the binary equivalent of a given positive number between 0 to 255.
Expression Evaluation:
a. A building has 10 floors with a floor height of 3 meters each. A ball is dropped from the top of
the building. Find the time taken by the ball to reach each floor. (Use the formula s = ut+(1/2)at^2
where u and a are the initial velocity in m/sec (= 0) and acceleration in m/sec^2 (= 9.8 m/s^2)).
b. Write a C program, which takes two integer operands and one operator from the user, performs
the operation and then prints the result. (Consider the operators +,-,*, /, % and use Switch
Statement)
c. Write a program that finds if a given number is a prime number
d. Write a C program to find the sum of individual digits of a positive integer and test given number
is palindrome.
e. A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0
and 1. Subsequent terms are found by adding the preceding two terms in the sequence. Write
a C program to generate the first n terms of the sequence.
f. Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.
g. Write a C program to find the roots of a Quadratic equation.
h. Write a C program to calculate the following, where x is a fractional value of Equation i. 1-x/2 +x^2/4-x^3/6
i. Write a C program to read in two numbers, x and n, and then compute the sum of this geometric
progression: 1+x+x^2+x^3+.............+x^n. For example: if n is 3 and x is 5, then the program
computes 1+5+25+125.
a. Write a C program to find the minimum, maximum and average in an array of integers.
b. Write a function to compute mean, variance, Standard Deviation, sorting of n elements in a
single dimension array.
c. Write a C program that uses functions to perform the following:
a) Addition of Two Matrices
b) Multiplication of Two Matrices
c) Transpose of a matrix with memory dynamically allocated for the new matrix as row and column
counts may not be the same.
d) Write C programs that use both recursive and non-recursive functions
e) To find the factorial of a given integer.
f) To find the GCD (greatest common divisor) of two given integers.
g) To find x^n
h) Write a program for reading elements using a pointer into an array and display the values using the
array.
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 2
i) Write a program for display values reverse order from an array using a pointer.
j) Write a program through a pointer variable to sum of n elements from an array.
Files:
Strings:
a. Write a C program to convert a Roman numeral ranging from I to L to its decimal equivalent.
b. Write a C program that converts a number ranging from 1 to 50 to Roman equivalent
c. Write a C program that uses functions to perform the following operations:
d. To insert a sub-string into a given main string from a given position.
e. To delete n Characters from a given position in a given string.
f. Write a C program to determine if the given string is a palindrome or not (Spelled same in both
directions with or without a meaning like madam, civic, noon, abcba, etc.)
g. Write a C program that displays the position of a character ch in the string S or – 1 if S doesn‘t
contain ch.
h. Write a C program to count the lines, words and characters in a given text.
Miscellaneous:
a. Write a menu driven C program that allows a user to enter n numbers and then choose between
finding the smallest, largest, sum, or average. The menu and all the choices are to be functions.
Use a switch statement to determine what action to take. Display an error message if an invalid
choice is entered.
b. Write a C program to construct a pyramid of numbers as follows:
1
12
123
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 3
*
**
***
1
23
456
1
22
333
4444
*
**
***
**
*
A. Write a C program that uses non recursive function to search for a Key value in a given list of integers
using linear search method.
B. Write a C program that uses a non recursive function to search for a Key value in a given sorted list of
integers using binary search method.
C. Write a C program that implements the Bubble sort method to sort a given list of integers in ascending
order.
D. Write a C program that sorts the given array of integers using selection sort in descending order
E. Write a C program that sorts the given array of integers using insertion sort in ascending order
F. Write a C program that sorts a given array of names
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 4
PROGRAMS
Practice sessions:
a. Write a simple program that prints the results of all the operators available in C (including pre/post
increment , bitwise and/or/not , etc.). Read required operand values from standard input.
This program will demonstrate the usage of arithmetic, relational, logical, bitwise, and assignment operators, as
well as pre/post-increment and pre/post-decrement operators. It will read two integer operands from the
standard input and perform operations using these operands.
#include <stdio.h>
int main() {
int a, b;
// Arithmetic Operators
printf("\nArithmetic Operators:\n");
printf("%d + %d = %d\n", a, b, a + b);
printf("%d - %d = %d\n", a, b, a - b);
printf("%d * %d = %d\n", a, b, a * b);
printf("%d / %d = %d\n", a, b, (b != 0) ? a / b : 0); // Handle division by zero
printf("%d %% %d = %d\n", a, b, (b != 0) ? a % b : 0); // Handle division by zero
// Relational Operators
printf("\nRelational Operators:\n");
printf("%d == %d: %d\n", a, b, a == b);
printf("%d != %d: %d\n", a, b, a != b);
printf("%d > %d: %d\n", a, b, a > b);
printf("%d < %d: %d\n", a, b, a < b);
printf("%d >= %d: %d\n", a, b, a >= b);
printf("%d <= %d: %d\n", a, b, a <= b);
// Logical Operators
printf("\nLogical Operators:\n");
printf("%d && %d: %d\n", a, b, a && b);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 5
printf("%d || %d: %d\n", a, b, a || b);
printf("!%d: %d\n", a, !a);
// Bitwise Operators
printf("\nBitwise Operators:\n");
printf("%d & %d = %d\n", a, b, a & b);
printf("%d | %d = %d\n", a, b, a | b);
printf("%d ^ %d = %d\n", a, b, a ^ b);
printf("~%d = %d\n", a, ~a);
printf("%d << 1 = %d\n", a, a << 1);
printf("%d >> 1 = %d\n", a, a >> 1);
// Increment/Decrement Operators
printf("\nIncrement/Decrement Operators:\n");
printf("Pre-increment: ++a = %d\n", ++a);
printf("Post-increment: a++ = %d\n", a++);
printf("After post-increment, a = %d\n", a);
printf("Pre-decrement: --b = %d\n", --b);
printf("Post-decrement: b-- = %d\n", b--);
printf("After post-decrement, b = %d\n", b);
// Assignment Operators
printf("\nAssignment Operators:\n");
a = 10;
b = 5;
a += b; // a = a + b
printf("a += b: %d\n", a);
a -= b; // a = a - b
printf("a -= b: %d\n", a);
a *= b; // a = a * b
printf("a *= b: %d\n", a);
a /= b; // a = a / b
printf("a /= b: %d\n", a);
a %= b; // a = a % b
printf("a %%= b: %d\n", a);
return 0;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 6
Output:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 7
b. Write a simple program that converts one given data type to another using auto conversion and
casting. Take the values from standard input.
This program will demonstrate implicit type conversion (auto conversion) and explicit type casting. It will read
an integer and a float value, perform some operations, and show the results of type conversions.
#include <stdio.h>
int main() {
int intValue;
float floatValue;
double doubleValue;
// Explicit Casting
int castedIntValue = (int)floatValue; // float to int
printf("\nExplicit Casting:\n");
printf("Casted floatValue to int: %d\n", castedIntValue);
return 0;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 8
Output:
#include <stdio.h>
int main() {
int num1, num2, num3, max, min;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Finding the maximum
max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);
// Finding the minimum
min = (num1 < num2) ? ((num1 < num3) ? num1 : num3) : ((num2 < num3) ? num2 : num3);
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
return 0;
}
Output:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 9
b. Write the program for the simple, compound interest.
#include <stdio.h>
#include <math.h>
int main() {
float principal, rate, time, simpleInterest, compoundInterest;
// Simple Interest
simpleInterest = (principal * rate * time) / 100;
printf("Simple Interest = %.2f\n", simpleInterest);
// Compound Interest
compoundInterest = principal * pow((1 + rate / 100), time) - principal;
printf("Compound Interest = %.2f\n", compoundInterest);
return 0;
}
Output:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 10
c. Write a program that declares Class awarded for a given percentage of marks, where mark <40%=
Failed, 40% to <60% = Second class, 60% to <70%=First class, >= 70% = Distinction.Read percentage
from standard input.
#include <stdio.h>
int main() {
float percentage;
return 0;
}
Output:
d. Write a program that prints a multiplication table for a given number and the number of rows in the
table. For example, for a number 5 and rows = 3, the output should be: 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15
#include <stdio.h>
int main() {
int num, rows;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 11
printf("Enter the number for which you want the multiplication table: ");
scanf("%d", &num);
printf("Enter the number of rows: ");
scanf("%d", &rows);
return 0;
}
Output:
e. Write a program that shows the binary equivalent of a given positive number between 0 to 255.
#include <stdio.h>
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 12
printf("Number out of range. Please enter a number between 0 and 255.\n");
} else {
printf("Binary equivalent of %d is: ", num);
printBinary(num);
}
return 0;
}
Output:
Expression Evaluation:
a. A building has 10 floors with a floor height of 3 meters each. A ball is dropped from the top of the
building. Find the time taken by the ball to reach each floor. (Use the formula s = ut+(1/2)at^2where u
and a are the initial velocity in m/sec (= 0) and acceleration in m/sec^2 (= 9.8 m/s^2)).
#include <stdio.h>
#include <math.h>
int main() {
float height, time;
float acceleration = 9.8; // in m/s^2
int floor;
return 0;
}
Output:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 13
*****************************End of Program & Output*************************
b. Write a C program, which takes two integer operands and one operator from the user, performs the
operation and then prints the result. (Consider the operators +,-,*, /, % and use Switch Statement)
#include <stdio.h>
int main() {
int num1, num2;
char operator;
int result;
switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %d\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %d\n", result);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 14
break;
case '*':
result = num1 * num2;
printf("Result: %d\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %d\n", result);
} else {
printf("Error: Division by zero.\n");
}
break;
case '%':
if (num2 != 0) {
result = num1 % num2;
printf("Result: %d\n", result);
} else {
printf("Error: Division by zero.\n");
}
break;
default:
printf("Error: Invalid operator.\n");
}
return 0;
}
Output:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 15
*****************************End of Program & Output*************************
#include <stdio.h>
int main() {
int num, i, isPrime = 1;
if (num <= 1) {
isPrime = 0;
} else {
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
}
if (isPrime)
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 16
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
Output:
d. Write a C program to find the sum of individual digits of a positive integer and test given number is
palindrome.
#include <stdio.h>
int main() {
int num, originalNum, reversedNum = 0, remainder, sum = 0;
originalNum = num;
while (num != 0) {
remainder = num % 10;
sum += remainder;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 17
printf("Sum of digits: %d\n", sum);
if (originalNum == reversedNum)
printf("%d is a palindrome.\n", originalNum);
else
printf("%d is not a palindrome.\n", originalNum);
return 0;
}
Output:
e. A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and 1.
Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program to
generate the first n terms of the sequence.
#include <stdio.h>
int main() {
int n, i;
long long t1 = 0, t2 = 1, nextTerm;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 18
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Output:
f. Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by
the user.
#include <stdio.h>
int main() {
int n, i, j, isPrime;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 19
}
}
if (isPrime == 1) {
printf("%d ", i);
}
}
return 0;
}
Output:
int main() {
float a, b, c, discriminant, root1, root2, realPart, imagPart;
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and different.\n");
printf("Root 1 = %.2f\nRoot 2 = %.2f\n", root1, root2);
} else if (discriminant == 0) {
root1 = -b / (2 * a);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 20
printf("Roots are real and the same.\n");
printf("Root 1 = Root 2 = %.2f\n", root1);
} else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and different.\n");
printf("Root 1 = %.2f + %.2fi\n", realPart, imagPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imagPart);
}
return 0;
}
Output:
h. Write a C program to calculate the following, where x is a fractional value. i. 1-x/2 +x^2/4- x^3/6
#include <stdio.h>
#include <math.h>
int main() {
float x, result;
return 0;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 21
Output:
i. Write a C program to read in two numbers, x and n, and then compute the sum of this geometric
progression: 1+x+x^2+x^3+ ........ +x^n. For example: if n is 3 and x is 5, then the program computes
1+5+25+125.
#include <stdio.h>
#include <math.h>
int main() {
int x, n, i;
int sum = 0;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 22
Arrays, Pointers and Functions:
a. Write a C program to find the minimum, maximum and average in an array of integers.
#include <stdio.h>
int main() {
int n, i, max, min;
int sum = 0;
float avg;
int arr[n];
avg = (float)sum / n;
return 0;
}
Output:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 23
*****************************End of Program & Output*************************
b. Write a function to compute mean, variance, Standard Deviation, sorting of n elements in a single
dimension array.
#include <stdio.h>
#include <math.h>
void computeStatistics(int arr[], int n, float *mean, float *variance, float *stdDev) {
int sum = 0;
float sumVariance = 0;
*mean = (float)sum / n;
*variance = sumVariance / n;
*stdDev = sqrt(*variance);
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 24
for (int 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;
}
}
}
}
int main() {
int n;
float mean, variance, stdDev;
int arr[n];
return 0;
}
OUTPUT:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 25
*****************************End of Program & Output*************************
#include <stdio.h>
void add_matrices(int row, int col, int mat1[row][col], int mat2[row][col], int result[row][col]) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
int main() {
int row, col;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 26
printf("Enter number of rows and columns: ");
scanf("%d %d", &row, &col);
int mat1[row][col], mat2[row][col], result[row][col];
printf("Enter elements of matrix 1:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &mat1[i][j]);
}
}
printf("Sum of matrices:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 27
b) Multiplication of Two Matrices
#include <stdio.h>
void multiply_matrices(int row1, int col1, int mat1[row1][col1], int row2, int col2, int mat2[row2][col2], int
result[row1][col2]) {
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
result[i][j] = 0;
for (int k = 0; k < col1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
int main() {
int row1, col1, row2, col2;
if (col1 != row2) {
printf("Matrix multiplication is not possible.\n");
return 1;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 28
}
}
printf("Product of matrices:\n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT:
c) Transpose of a matrix with memory dynamically allocated for the new matrix as row and column
counts may not be the same.
#include <stdio.h>
#include <stdlib.h>
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 29
for (int j = 0; j < row; j++) {
result[i][j] = mat[j][i];
}
}
}
int main() {
int row, col;
int mat[row][col];
int **transpose = (int **)malloc(col * sizeof(int *));
for (int i = 0; i < col; i++) {
transpose[i] = (int *)malloc(row * sizeof(int));
}
return 0;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 30
OUTPUT:
d)Write C programs that use both recursive and non-recursive functions[ Factorial Function (Recursive
and Non-Recursive)]
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 31
return 0;
}
OUTPUT:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 32
return 0;
}
OUTPUT:
#include <stdio.h>
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 33
printf("Recursive GCD of %d and %d: %d\n", a, b, gcd_recursive(a, b));
return 0;
}
OUTPUT:
g) To find x^n
#include <stdio.h>
#include <math.h>
int main() {
double x;
int n;
return 0;
}
OUTPUT:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 34
*****************************End of Program & Output*************************
h) Write a program for reading elements using a pointer into an array and display the values using the
array.
#include <stdio.h>
int main() {
int n;
int arr[n];
int *ptr = arr;
// Read elements
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", ptr + i);
}
// Display elements
printf("Elements:\n");
for (int i = 0; i < n; i++) {
printf("%d ", *(ptr + i));
}
printf("\n");
return 0;
}
OUTPUT:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 35
*****************************End of Program & Output*************************
i) Write a program for display values reverse order from an array using a pointer.
#include <stdio.h>
int main() {
int n;
int arr[n];
int *ptr = arr;
// Read elements
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", ptr + i);
}
return 0;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 36
OUTPUT:
#include <stdio.h>
int main() {
int n;
int arr[n];
int *ptr = arr;
// Read elements
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", ptr + i);
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 37
printf("Sum of elements: %d\n", sum);
return 0;
}
OUTPUT:
Files:
a. Write a C program to display the contents of a file to standard output device
#include <stdio.h>
int main() {
FILE *file;
char filename[100], ch;
fclose(file);
return 0;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 38
}
OUTPUT:
b. Write a C program which copies one file to another, replacing all lowercase characters with their
uppercase equivalents.
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *sourceFile, *destFile;
char sourceFilename[100], destFilename[100], ch;
fclose(sourceFile);
fclose(destFile);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 39
return 0;
}
Output:
c. Write a C program to count the number of times a character occurs in a text file. The file name and the
character are supplied as command line arguments.
#include <stdio.h>
fclose(file);
printf("The character '%c' occurs %d times in the file.\n", character, count);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 40
return 0;
}
Output:
d. Write a C program that does the following: It should first create a binary file and store 10 integers,
where the file name and 10 values are given in the command line. (hint: convert the strings using atoi
function) Now the program asks for an index and a value from the user and the value at that index
should be changed to the new value in the file. (hint: use fseek function) The program should then read
all 10 values and print them back.
#include <stdio.h>
#include <stdlib.h>
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 41
if (index < 0 || index >= 10) {
printf("Error: Index out of bounds\n");
return 1;
}
printf("Updated values:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", values[i]);
}
printf("\n");
return 0;
}
Output:
e. Write a C program to merge two files into a third file (i.e., the contents of the first file followedby those
of the second are put in the third file).
#include <stdio.h>
int main() {
FILE *file1, *file2, *file3;
char file1Name[100], file2Name[100], file3Name[100], ch;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 42
scanf("%s", file1Name);
printf("Enter the second filename: ");
scanf("%s", file2Name);
printf("Enter the third filename: ");
scanf("%s", file3Name);
fclose(file1);
fclose(file2);
fclose(file3);
return 0;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 43
}
Output:
a. Write a C program to convert a Roman numeral ranging from I to L to its decimal Equivalent.
#include <stdio.h>
int main() {
char roman[100];
int decimal = 0;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 44
return 0;
}
OUTPUT:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 45
while (num >= 4) {
printf("IV");
num -= 4;
}
while (num >= 1) {
printf("I");
num -= 1;
}
printf("\n");
}
int main() {
int num;
return 0;
}
OUTPUT:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 46
c) Write a C program to determine if the given string is a palindrome or not (Spelled
same in bothdirections with or without a meaning like madam, civic, noon, abcba,
etc.)
d) Write a C program that displays the position of a character ch in the string S or – 1
if S doesn‘t contain ch.
e) Write a C program to count the lines, words and characters in a given text.
a. To insert a sub-string into a given main string from a given position.
#include <stdio.h>
#include <string.h>
int main() {
char mainStr[100], subStr[50];
int position;
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 47
return 0;
}
Output :
#include <stdio.h>
#include <string.h>
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 48
Output:
int main() {
char str[100];
if (isPalindrome(str)) {
printf("The string is a palindrome.\n");
} else {
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 49
printf("The string is not a palindrome.\n");
}
return 0;
}
Output :
int main() {
char str[100], ch;
// Input the string
printf("Enter the string: ");
fgets(str, sizeof(str), stdin);
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 50
scanf("%c", &ch);
return 0;
}
Output:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 51
Explanation:
e) Write a C program to count the lines, words and characters in a given text.
#include <stdio.h>
int main() {
char c;
int lines = 0, words = 0, characters = 0;
int inWord = 0; // Flag to check if we're inside a word
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 52
while ((c = getchar()) != EOF) {
// Count characters
characters++;
// Count lines
if (c == '\n') {
lines++;
}
// Count words
if (c == ' ' || c == '\n' || c == '\t') {
inWord = 0; // We're outside a word
} else if (inWord == 0) {
inWord = 1; // We're inside a word
words++;
}
}
return 0;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 53
Explanation:
1. Variables:
○ lines: Counts the number of lines in the text.
○ words: Counts the number of words in the text.
○ characters: Counts the total number of characters in the text.
○ inWord: A flag to determine whether the current position is inside a word or not.
2. Character Input:
○ The program reads the input one character at a time using getchar() until it reaches the
end-of-file (EOF) marker.
○ EOF can be triggered by pressing Ctrl+D (Linux/Mac) or Ctrl+Z (Windows) after typing in
the text.
3. Counting:
○ Characters: Every character, including spaces and newlines, is counted.
○ Words: A word is considered to be a sequence of non-whitespace characters. The program uses
the inWord flag to track whether the current position is inside a word.
○ Lines: Every newline character ('\n') counts as a new line.
4. Edge Cases:
○ The program handles multiple spaces or tabs between words correctly.
○ If there’s no trailing newline, the program adds 1 to the line count.
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 54
Miscellaneous
a. Write a menu driven C program that allows a user to enter n numbers and then choose between
finding the smallest, largest, sum, or average. The menu and all the choices are to be functions.Use a
switch statement to determine what action to take. Display an error message if an invalid choice is
entered. [Menu-Driven Program for Finding Smallest, Largest, Sum, or Average]
#include <stdio.h>
// Function to find the smallest number
int findSmallest(int arr[], int n) {
int smallest = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}
return smallest;
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 55
}
int main() {
int n, choice;
int arr[n];
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 56
break;
}
return 0;
}
Output :
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 57
Explanation:
1. Functions:
○ findSmallest: Loops through the array and finds the smallest element.
○ findLargest: Loops through the array and finds the largest element.
○ findSum: Loops through the array and sums the elements.
○ findAverage: Uses the findSum function to calculate the total sum, and then divides it
by n to find the average.
2. Menu:
○ The user is presented with a menu of four choices: finding the smallest, largest, sum, or
average.
○ The program uses a switch statement to handle the user's choice and calls the
appropriate function.
○ If the user enters an invalid choice, the program prints an error message.
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 58
*
[Constructing Pyramids of Numbers]
#include <stdio.h>
int main() {
int n = 5; // You can change n to generate more or fewer rows
return 0;
}
Output :
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 59
Explanation:
This program generates a specific pattern involving numbers and stars. It prints the first set of numbers
followed by stars, and then the second part continues with more numbers and repeated numbers followed
by stars.
The program you requested constructs a pyramid-like structure using numbers and stars. Let’s break it
down into two main parts:
In the first part of the program, for each row iii, the following occurs:
In the second part of the program, for each row iii, the following occurs:
Code Walkthrough:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 60
1. First loop (lines 7-14):
○ This loop generates the first part of the pattern, where numbers from 1 to i are followed
by i stars.
2. Second loop (lines 16-27):
○ This loop generates the second part of the pattern, where numbers from i to 2i are
followed by the number i repeated i times, and then followed by i stars.
#include <stdio.h>
int main() {
int n, key;
int arr[n];
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 61
// Perform linear search
int result = linearSearch(arr, n, key);
return 0;
}
Output :
Explanation:
1. The function linearSearch takes the array arr, its size n, and the key to search as inputs.
2. It loops through the array, checking if the current element is equal to the key. If found, it returns
the index; otherwise, it returns -1 if the key is not present in the array.
3. The main function handles input/output operations, asks for the number of elements, reads the
array, and the key, then calls the linearSearch function to perform the search.
#include <stdio.h>
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 62
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;
if (arr[mid] == key) {
return mid; // Key found, return the index
} else if (arr[mid] < key) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Key not found
}
int main() {
int n, key;
int arr[n];
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 63
} else {
printf("Key %d found at index %d.\n", key, result);
}
return 0;
}
Output :
Explanation:
1. Binary Search Algorithm: This algorithm works on a sorted list and searches for the key by
dividing the array into two halves repeatedly. It checks the middle element and, based on whether
the key is smaller or larger than the middle, continues the search in either the left or right half of
the array.
2. Function binarySearch:
○ It takes the sorted array arr, its size n, and the key as inputs.
○ low and high represent the current search range, and mid represents the middle index.
○ If the middle element matches the key, the index is returned. If the middle element is
smaller than the key, the search continues in the right half. If larger, it continues in the left
half.
3. main function: Handles input/output operations, reads the array in sorted order, and calls the
binarySearch function to perform the search.
c. Write a C program that implements the Bubble sort method to sort a given list of integers in
#include <stdio.h>
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 64
// Function to perform Bubble Sort
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
// Swap if the current element is greater than the next element
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int n;
int arr[n];
return 0;
}
Output :
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 65
Explanation:
1. Bubble Sort Algorithm: This sorting algorithm repeatedly steps through the list, compares
adjacent elements, and swaps them if they are in the wrong order. The pass through the list is
repeated until the list is sorted.
2. Function bubbleSort:
○ It takes the array arr and its size n as inputs.
○ Two nested loops are used: the outer loop for each pass, and the inner loop to compare
adjacent elements. Elements are swapped if they are in the wrong order.
3. main function: Handles input/output operations, reads the array, and calls the bubbleSort
function to sort it in ascending order.
#include <stdio.h>
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 66
arr[i] = temp;
}
}
int main() {
int n;
int arr[n];
return 0;
}
Output :
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 67
Explanation:
1. Selection Sort Algorithm: This algorithm works by repeatedly finding the largest (in this case,
since we want descending order) element from the unsorted part of the array and placing it at the
beginning.
2. Function selectionSortDescending:
○ It takes the array arr and its size n as inputs.
○ The outer loop iterates through each element of the array, and the inner loop finds the
largest element in the remaining unsorted portion of the array.
○ The largest element is then swapped with the current element at index i.
3. main function: Handles input/output operations, reads the array, and calls the
selectionSortDescending function to sort the array in descending order.
// Move elements that are greater than key to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key; // Place key in its correct position
}
}
int main() {
int n;
int arr[n];
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 68
// Input elements of the array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
return 0;
}
Output :
Explanation:
1. Insertion Sort Algorithm: This algorithm builds a sorted list one element at a time. It picks an
element (the "key") and compares it with elements in the sorted part, shifting elements greater
than the key to the right until the correct position is found for the key.
2. Function insertionSort:
○ It takes the array arr and its size n as inputs.
○ The outer loop iterates over the array starting from the second element.
○ The inner loop shifts elements greater than the key to the right to make space for inserting
the key in the correct position.
3. main function: Handles input/output operations, reads the array, and calls the insertionSort
function to sort the array in ascending order.
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 69
*****************************End of Program & Output*************************
f. Write a C program that sorts a given array of names [Sorting an Array of Names (Alphabetical
Order)]
#include <stdio.h>
#include <string.h>
int main() {
int n;
char names[MAX][LEN];
// Input names
printf("Enter %d names:\n", n);
for (int i = 0; i < n; i++) {
scanf("%s", names[i]);
}
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 70
// Call the bubbleSortNames function
bubbleSortNames(names, n);
return 0;
}
Output :
Explanation:
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 71
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 72