0% found this document useful (0 votes)
27 views73 pages

PPS Lab

The document is a lab manual for the CS108ES Programming for Problem Solving course at JNTUH, detailing course objectives, outcomes, and a variety of programming exercises in C. It covers topics such as operators, control statements, functions, arrays, pointers, file handling, and string manipulation, with specific practice sessions and example programs provided. The manual is prepared by Dr. Afreen Bari, Baseer Fatima, and Kausar Jahan.

Uploaded by

ajiya1368
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views73 pages

PPS Lab

The document is a lab manual for the CS108ES Programming for Problem Solving course at JNTUH, detailing course objectives, outcomes, and a variety of programming exercises in C. It covers topics such as operators, control statements, functions, arrays, pointers, file handling, and string manipulation, with specific practice sessions and example programs provided. The manual is prepared by Dr. Afreen Bari, Baseer Fatima, and Kausar Jahan.

Uploaded by

ajiya1368
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

PPS LAB MANUAL

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.

Simple numeric problems:

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.

Arrays, Pointers and Functions:

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:

a. Write a C program to display the contents of a file to standard output devices.


b. Write a C program which copies one file to another, replacing all lowercase characters with
their uppercase equivalents.
c. Write a C program to count the number of times a character occurs in a text file. The file name
and the characters are supplied as command line arguments.
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.
e. Write a C program to merge two files into a third file (i.e., the contents of the first file followed
by those of the second are put in the third file).

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
*
**
***
**
*

Sorting and Searching:

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.

a. Program to Print Results of All Operators

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;

// Read input values


printf("Enter two integers: ");
scanf("%d %d", &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:

*****************************End of Program & 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.

b. Program to Convert Data Types Using Auto Conversion and Casting

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;

// Read values from input


printf("Enter an integer: ");
scanf("%d", &intValue);
printf("Enter a float value: ");
scanf("%f", &floatValue);

// Implicit Conversion (Auto Conversion)


doubleValue = intValue + floatValue; // int and float are auto-converted to double
printf("\nImplicit Conversion:\n");
printf("intValue + floatValue = %f (double)\n", doubleValue);

// Explicit Casting
int castedIntValue = (int)floatValue; // float to int
printf("\nExplicit Casting:\n");
printf("Casted floatValue to int: %d\n", castedIntValue);

// More examples of explicit casting


float castedFloatValue = (float)intValue; // int to float
printf("Casted intValue to float: %f\n", castedFloatValue);

// Casting double to int


int doubleToInt = (int)doubleValue;
printf("Casted doubleValue to int: %d\n", doubleToInt);

return 0;
}

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 8
Output:

*****************************End of Program & Output*************************

Simple numeric problems:


a. Write a program for finding the max and min from the three numbers.

#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:

*****************************End of Program & 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;

printf("Enter principal amount: ");


scanf("%f", &principal);
printf("Enter annual interest rate (in percentage): ");
scanf("%f", &rate);
printf("Enter time (in years): ");
scanf("%f", &time);

// 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:

*****************************End of Program & 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;

printf("Enter the percentage of marks: ");


scanf("%f", &percentage);

if (percentage < 40) {


printf("Class: Failed\n");
} else if (percentage >= 40 && percentage < 60) {
printf("Class: Second Class\n");
} else if (percentage >= 60 && percentage < 70) {
printf("Class: First Class\n");
} else {
printf("Class: Distinction\n");
}

return 0;
}

Output:

*****************************End of Program & 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);

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


printf("%d x %d = %d\n", num, i, num * i);
}

return 0;
}
Output:

*****************************End of Program & Output*************************

e. Write a program that shows the binary equivalent of a given positive number between 0 to 255.

#include <stdio.h>

void printBinary(int num) {


for (int i = 7; i >= 0; i--) {
printf("%d", (num >> i) & 1);
}
printf("\n");
}
int main() {
int num;
printf("Enter a number between 0 and 255: ");
scanf("%d", &num);

if (num < 0 || num > 255) {

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:

*****************************End of Program & 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;

for (floor = 10; floor >= 1; floor--) {


height = floor * 3; // each floor is 3 meters
time = sqrt((2 * height) / acceleration);
printf("Time to reach floor %d: %.2f seconds\n", floor, time);
}

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;

printf("Enter two integers: ");


scanf("%d %d", &num1, &num2);
printf("Enter an operator (+, -, *, /, %%): ");
scanf(" %c", &operator);

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*************************

c. Write a program that finds if a given number is a prime number

#include <stdio.h>

int main() {
int num, i, isPrime = 1;

printf("Enter a positive integer: ");


scanf("%d", &num);

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:

*****************************End of Program & 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;

printf("Enter a positive integer: ");


scanf("%d", &num);

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:

*****************************End of Program & 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;

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


scanf("%d", &n);

printf("Fibonacci Sequence: ");

for (i = 1; i <= n; ++i) {


printf("%lld, ", t1);

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 18
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}

return 0;
}
Output:

*****************************End of Program & 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;

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


scanf("%d", &n);

printf("Prime numbers between 1 and %d are: ", n);

for (i = 2; i <= n; i++) {


isPrime = 1;
for (j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = 0;
break;

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 19
}
}
if (isPrime == 1) {
printf("%d ", i);
}
}

return 0;
}
Output:

*****************************End of Program & Output*************************

g. Write a C program to find the roots of a Quadratic equation


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

int main() {
float a, b, c, discriminant, root1, root2, realPart, imagPart;

printf("Enter coefficients a, b and c: ");


scanf("%f %f %f", &a, &b, &c);

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:

*****************************End of Program & 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;

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


scanf("%f", &x);

result = 1 - (x / 2) + (pow(x, 2) / 4) - (pow(x, 3) / 6);

printf("Result: %.2f\n", result);

return 0;
}

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 21
Output:

*****************************End of Program & 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;

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


scanf("%d", &x);
printf("Enter the value of n: ");
scanf("%d", &n);
for (i = 0; i <= n; i++) {
sum += pow(x, i);
}
printf("Sum of the geometric progression: %d\n", sum);
return 0;
}
Output:

*****************************End of Program & Output*************************

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;

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


scanf("%d", &n);

int arr[n];

printf("Enter %d integers: \n", n);


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

max = min = arr[0];

for (i = 0; i < n; i++) {


sum += arr[i];
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}

avg = (float)sum / n;

printf("Maximum: %d\n", max);


printf("Minimum: %d\n", min);
printf("Average: %.2f\n", avg);

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;

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


sum += arr[i];
}

*mean = (float)sum / n;

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


sumVariance += pow(arr[i] - *mean, 2);
}

*variance = sumVariance / n;
*stdDev = sqrt(*variance);
}

void sortArray(int arr[], int n) {


int temp;
for (int i = 0; i < n-1; i++) {

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;

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


scanf("%d", &n);

int arr[n];

printf("Enter %d integers: \n", n);


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

computeStatistics(arr, n, &mean, &variance, &stdDev);


sortArray(arr, n);

printf("Mean: %.2f\n", mean);


printf("Variance: %.2f\n", variance);
printf("Standard Deviation: %.2f\n", stdDev);

printf("Sorted Array: ");


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

return 0;
}
OUTPUT:

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 25
*****************************End of Program & Output*************************

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.
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.

a) Addition of Two Matrices

#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("Enter elements of matrix 2:\n");


for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &mat2[i][j]);
}
}

add_matrices(row, col, mat1, mat2, result);

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:

*****************************End of Program & 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;

printf("Enter rows and columns for matrix 1: ");


scanf("%d %d", &row1, &col1);
printf("Enter rows and columns for matrix 2: ");
scanf("%d %d", &row2, &col2);

if (col1 != row2) {
printf("Matrix multiplication is not possible.\n");
return 1;
}

int mat1[row1][col1], mat2[row2][col2], result[row1][col2];

printf("Enter elements of matrix 1:\n");


for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
scanf("%d", &mat1[i][j]);
}
}

printf("Enter elements of matrix 2:\n");


for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
scanf("%d", &mat2[i][j]);

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 28
}
}

multiply_matrices(row1, col1, mat1, row2, col2, mat2, result);

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:

*****************************End of Program & 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>

void transpose_matrix(int row, int col, int mat[row][col], int **result) {


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

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;

printf("Enter number of rows and columns: ");


scanf("%d %d", &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));
}

printf("Enter elements of the matrix:\n");


for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &mat[i][j]);
}
}

transpose_matrix(row, col, mat, transpose);

printf("Transpose of the matrix:\n");


for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}

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


free(transpose[i]);
}
free(transpose);

return 0;
}

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 30
OUTPUT:

*****************************End of Program & Output*************************

d)Write C programs that use both recursive and non-recursive functions[ Factorial Function (Recursive
and Non-Recursive)]

#include <stdio.h>

// Non-recursive factorial function


unsigned long long factorial_non_recursive(int n) {
unsigned long long result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}

// Recursive factorial function


unsigned long long factorial_recursive(int n) {
if (n == 0) return 1;
return n * factorial_recursive(n - 1);
}

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

printf("Non-recursive factorial of %d: %llu\n", num, factorial_non_recursive(num));


printf("Recursive factorial of %d: %llu\n", num, factorial_recursive(num));

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 31
return 0;
}

OUTPUT:

*****************************End of Program & Output*************************


e) To find the factorial of a given integer.

#include <stdio.h>

// Non-recursive factorial function


unsigned long long factorial_non_recursive(int n) {
unsigned long long result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}

// Recursive factorial function


unsigned long long factorial_recursive(int n) {
if (n == 0) return 1;
return n * factorial_recursive(n - 1);
}

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

printf("Non-recursive factorial of %d: %llu\n", num, factorial_non_recursive(num));


printf("Recursive factorial of %d: %llu\n", num, factorial_recursive(num));

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 32
return 0;
}
OUTPUT:

*****************************End of Program & Output*************************

f) To find the GCD (greatest common divisor) of two given integers.

#include <stdio.h>

// Non-recursive GCD function


int gcd_non_recursive(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

// Recursive GCD function


int gcd_recursive(int a, int b) {
if (b == 0) return a;
return gcd_recursive(b, a % b);
}

int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);

printf("Non-recursive GCD of %d and %d: %d\n", a, b, gcd_non_recursive(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:

*****************************End of Program & Output*************************

g) To find x^n

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

double power(double base, int exp) {


return pow(base, exp);
}

int main() {
double x;
int n;

printf("Enter base x and exponent n: ");


scanf("%lf %d", &x, &n);

printf("%.2lf^%d = %.2lf\n", x, n, power(x, 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;

printf("Enter number of elements: ");


scanf("%d", &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;

printf("Enter number of elements: ");


scanf("%d", &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 in reverse order


printf("Elements in reverse order:\n");
for (int i = n - 1; i >= 0; i--) {
printf("%d ", *(ptr + i));
}
printf("\n");

return 0;
}

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 36
OUTPUT:

*****************************End of Program & Output*************************


j) Write a program through a pointer variable to sum of n elements from an array.

#include <stdio.h>

int sum_array(int *arr, int n) {


int sum = 0;
for (int i = 0; i < n; i++) {
sum += *(arr + i);
}
return sum;
}

int main() {
int n;

printf("Enter number of elements: ");


scanf("%d", &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);
}

int sum = sum_array(ptr, n);

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 37
printf("Sum of elements: %d\n", sum);

return 0;
}

OUTPUT:

*****************************End of Program & 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;

printf("Enter the filename: ");


scanf("%s", filename);

file = fopen(filename, "r");


if (file == NULL) {
printf("Error: Could not open file %s\n", filename);
return 1;
}

while ((ch = fgetc(file)) != EOF) {


putchar(ch);
}

fclose(file);
return 0;

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 38
}
OUTPUT:

*****************************End of Program & 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;

printf("Enter the source filename: ");


scanf("%s", sourceFilename);
printf("Enter the destination filename: ");
scanf("%s", destFilename);

sourceFile = fopen(sourceFilename, "r");


if (sourceFile == NULL) {
printf("Error: Could not open file %s\n", sourceFilename);
return 1;
}

destFile = fopen(destFilename, "w");


if (destFile == NULL) {
printf("Error: Could not create file %s\n", destFilename);
fclose(sourceFile);
return 1;
}

while ((ch = fgetc(sourceFile)) != EOF) {


fputc(toupper(ch), destFile);
}

fclose(sourceFile);
fclose(destFile);

printf("File copied successfully.\n");

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 39
return 0;
}

Output:

*****************************End of Program & 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>

int main(int argc, char *argv[]) {


if (argc != 3) {
printf("Usage: %s <filename> <character>\n", argv[0]);
return 1;
}

char *filename = argv[1];


char character = argv[2][0];
FILE *file;
char ch;
int count = 0;

file = fopen(filename, "r");


if (file == NULL) {
printf("Error: Could not open file %s\n", filename);
return 1;
}

while ((ch = fgetc(file)) != EOF) {


if (ch == character) {
count++;
}
}

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:

*****************************End of Program & 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>

int main(int argc, char *argv[]) {


if (argc != 12) {
printf("Usage: %s <filename> <10 integers>\n", argv[0]);
return 1;
}

char *filename = argv[1];


int values[10], index, newValue;
FILE *file;

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


values[i] = atoi(argv[i + 2]);
}

file = fopen(filename, "wb");


if (file == NULL) {
printf("Error: Could not create file %s\n", filename);
return 1;
}

fwrite(values, sizeof(int), 10, file);


fclose(file);

printf("Enter index (0-9) and new value: ");


scanf("%d %d", &index, &newValue);

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;
}

file = fopen(filename, "rb+");


if (file == NULL) {
printf("Error: Could not open file %s\n", filename);
return 1;
}

fseek(file, index * sizeof(int), SEEK_SET);


fwrite(&newValue, sizeof(int), 1, file);
fclose(file);

file = fopen(filename, "rb");


fread(values, sizeof(int), 10, file);
fclose(file);

printf("Updated values:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", values[i]);
}
printf("\n");

return 0;
}
Output:

*****************************End of Program & 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;

printf("Enter the first filename: ");

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);

file1 = fopen(file1Name, "r");


if (file1 == NULL) {
printf("Error: Could not open file %s\n", file1Name);
return 1;
}

file2 = fopen(file2Name, "r");


if (file2 == NULL) {
printf("Error: Could not open file %s\n", file2Name);
fclose(file1);
return 1;
}

file3 = fopen(file3Name, "w");


if (file3 == NULL) {
printf("Error: Could not create file %s\n", file3Name);
fclose(file1);
fclose(file2);
return 1;
}

while ((ch = fgetc(file1)) != EOF) {


fputc(ch, file3);
}

while ((ch = fgetc(file2)) != EOF) {


fputc(ch, file3);
}

fclose(file1);
fclose(file2);
fclose(file3);

printf("Files merged successfully.\n");

return 0;

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 43
}
Output:

*****************************End of Program & Output*************************


Strings:

a. Write a C program to convert a Roman numeral ranging from I to L to its decimal Equivalent.

#include <stdio.h>

int romanToDecimal(char roman) {


switch (roman) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
default: return -1;
}
}

int main() {
char roman[100];
int decimal = 0;

printf("Enter a Roman numeral (I to L): ");


scanf("%s", roman);

for (int i = 0; roman[i] != '\0'; i++) {


int value1 = romanToDecimal(roman[i]);
int value2 = romanToDecimal(roman[i + 1]);

if (value1 < value2) {


decimal -= value1;
} else {
decimal += value1;
}
}

printf("Decimal equivalent: %d\n", decimal);

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 44
return 0;
}
OUTPUT:

*****************************End of Program & Output*************************

b. Write a C program that converts a number ranging from 1 to 50 to Roman equivalent.


#include <stdio.h>

void decimalToRoman(int num) {


while (num >= 50) {
printf("L");
num -= 50;
}
while (num >= 40) {
printf("XL");
num -= 40;
}
while (num >= 10) {
printf("X");
num -= 10;
}
while (num >= 9) {
printf("IX");
num -= 9;
}
while (num >= 5) {
printf("V");
num -= 5;
}

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;

printf("Enter a number (1 to 50): ");


scanf("%d", &num);

if (num < 1 || num > 50) {


printf("Invalid input. Please enter a number between 1 and 50.\n");
} else {
printf("Roman numeral: ");
decimalToRoman(num);
}

return 0;
}

OUTPUT:

*****************************End of Program & Output*************************

c. Write a C program that uses functions to perform the following operations:


a) To insert a sub-string into a given main string from a given position.
b) To delete n Characters from a given position in a given string.

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>

void insertSubstring(char mainStr[], char subStr[], int position) {


int mainLen = strlen(mainStr);
int subLen = strlen(subStr);

for (int i = mainLen; i >= position; i--) {


mainStr[i + subLen] = mainStr[i];
}

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


mainStr[position + i] = subStr[i];
}
}

int main() {
char mainStr[100], subStr[50];
int position;

printf("Enter the main string: ");


gets(mainStr);

printf("Enter the sub-string: ");


gets(subStr);

printf("Enter the position: ");


scanf("%d", &position);

insertSubstring(mainStr, subStr, position);

printf("String after insertion: %s\n", mainStr);

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 47
return 0;
}

Output :

*****************************End of Program & Output*************************


b. To delete n Characters from a given position in a given string.

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

void deleteSubstring(char str[], int position, int n) {


int len = strlen(str);

if (position + n > len) {


n = len - position;
}

for (int i = position; i < len - n + 1; i++) {


str[i] = str[i + n];
}
}
int main() {
char str[100];
int position, n;
printf("Enter the string: ");
gets(str);
printf("Enter the position: ");
scanf("%d", &position);
printf("Enter the number of characters to delete: ");
scanf("%d", &n);
deleteSubstring(str, position, n);
printf("String after deletion: %s\n", str);
return 0;
}

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 48
Output:

*****************************End of Program & Output*************************


c. 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.)
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int isPalindrome(char str[]) {


int len = strlen(str);
int left = 0, right = len - 1;
while (left < right) {
while (left < right && !isalnum(str[left])) left++;
while (left < right && !isalnum(str[right])) right--;
if (tolower(str[left]) != tolower(str[right])) {
return 0;
}
left++;
right--;
}
return 1;
}

int main() {
char str[100];

printf("Enter the string: ");


gets(str);

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 :

*****************************End of Program & Output*************************


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.
#include <stdio.h>

int findCharacterPosition(char str[], char ch) {


int i = 0;

// Traverse the string to find the character


while (str[i] != '\0') {
if (str[i] == ch) {
return i + 1; // Return position (1-based index)
}
i++;
}
return -1; // Character not found
}

int main() {
char str[100], ch;
// Input the string
printf("Enter the string: ");
fgets(str, sizeof(str), stdin);

// Remove the trailing newline character, if present


size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
}
// Input the character to find
printf("Enter the character to find: ");

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 50
scanf("%c", &ch);

// Find the position of the character


int position = findCharacterPosition(str, ch);

// Output the result


if (position != -1) {
printf("The position of '%c' in the string is: %d\n", ch, position);
} else {
printf("Character '%c' not found in the string.\n", ch);
}

return 0;
}
Output:

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 51
Explanation:

1.​ Function findCharacterPosition:


○​ Takes the string str and character ch as input.
○​ Traverses the string until the character ch is found or the end of the string is reached.
○​ Returns the position of the character (1-based index) if found, otherwise returns -1.
2.​ main function:
○​ Reads the input string using fgets, which also reads the newline character, so it is
removed if present.
○​ Reads the character to search for using scanf.
○​ Calls findCharacterPosition to find the position of the character in the string.
○​ Displays the position or an error message if the character is not found.

*****************************End of Program & Output*************************

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

printf("Enter the text (press Ctrl+D or Ctrl+Z to end input):\n");

// Read characters until EOF is reached (Ctrl+D on Linux/Mac, Ctrl+Z on Windows)

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++;
}
}

// If there's no trailing newline, account for the last line


if (characters > 0 && c != '\n') {
lines++;
}

// Print the results


printf("\nLines: %d\n", lines);
printf("Words: %d\n", words);
printf("Characters: %d\n", characters);

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.

*****************************End of Program & Output*************************

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;
}

// Function to find the largest number


int findLargest(int arr[], int n) {
int largest = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}

// Function to find the sum of numbers


int findSum(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum;
}
// Function to find the average of numbers
float findAverage(int arr[], int n) {
int sum = findSum(arr, n);
return (float)sum / n;

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 55
}

int main() {
int n, choice;

// Asking user to input the number of elements


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

int arr[n];

// Input elements into the array


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

// Display the menu


printf("\nMenu:\n");
printf("1. Find Smallest\n");
printf("2. Find Largest\n");
printf("3. Find Sum\n");
printf("4. Find Average\n");
printf("Enter your choice: ");
scanf("%d", &choice);

// Switch statement to handle the menu choice


switch (choice) {
case 1:
printf("Smallest number: %d\n", findSmallest(arr, n));
break;
case 2:
printf("Largest number: %d\n", findLargest(arr, n));
break;
case 3:
printf("Sum of numbers: %d\n", findSum(arr, n));
break;
case 4:
printf("Average of numbers: %.2f\n", findAverage(arr, n));
break;
default:
printf("Error: Invalid choice!\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.

*****************************End of Program & Output*************************


b. Write a C program to construct a pyramid of numbers as follows:
1*11*
12**2322**
123***456333***
4444**

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

// First part of the pyramid


for (int i = 1; i <= n; i++) {
// Print first set of numbers
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
// Print stars
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}

// Second part of the pyramid


for (int i = 1; i <= n; i++) {
// Print second set of numbers
for (int j = i; j <= i * 2; j++) {
printf("%d ", j);
}
// Print repeated number pattern
for (int j = 1; j <= i; j++) {
printf("%d ", i);
}
// Print stars
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}

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 pattern can be adjusted by modifying the value of n.

The program you requested constructs a pyramid-like structure using numbers and stars. Let’s break it
down into two main parts:

Part 1: Pyramid of Numbers and Stars

In the first part of the program, for each row iii, the following occurs:

1.​ Numbers from 1 to i are printed.


2.​ Then, i stars (*) are printed.

Part 2: Extended Pyramid with Number Repetition

In the second part of the program, for each row iii, the following occurs:

1.​ Numbers from iii to 2i2i2i are printed.


2.​ Then, the number i is printed i times.
3.​ Finally, i stars (*) are printed.

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.

*****************************End of Program & Output*************************


Sorting & Searching:
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. (Linear Search)

#include <stdio.h>

// Function to perform linear search


int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return the index where key is found
}
}
return -1; // Return -1 if key is not found
}

int main() {
int n, key;

// Asking user to input the number of elements in the array


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

int arr[n];

// Input elements of the array


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

// Input the key to search for


printf("Enter the key to search: ");
scanf("%d", &key);

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 61
// Perform linear search
int result = linearSearch(arr, n, key);

// Output the result


if (result == -1) {
printf("Key %d not found in the array.\n", key);
} else {
printf("Key %d found at index %d.\n", key, result);
}

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.

*****************************End of Program & Output*************************


b. Write a C program that uses non recursive function to search for a Key value in a given
sorted list of integers using binary search method. [Binary Search]

#include <stdio.h>

// Function to perform binary search

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;

while (low <= high) {


int mid = (low + high) / 2;

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;

// Asking user to input the number of elements in the array


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

int arr[n];

// Input elements of the sorted array


printf("Enter %d integers in sorted order:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input the key to search for


printf("Enter the key to search: ");
scanf("%d", &key);

// Perform binary search


int result = binarySearch(arr, n, key);

// Output the result


if (result == -1) {
printf("Key %d not found in the array.\n", key);

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.

*****************************End of Program & Output*************************

c. Write a C program that implements the Bubble sort method to sort a given list of integers in

ascending order.(Bubble Sort)

#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;

// Asking user to input the number of elements in the array


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

int arr[n];

// Input elements of the array


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

// Call the bubbleSort function


bubbleSort(arr, n);

// Output the sorted array


printf("Sorted array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\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.

*****************************End of Program & Output*************************


d. Write a C program that sorts the given array of integers using selection sort in descending
Order [Selection Sort (Descending Order)]

#include <stdio.h>

// Function to perform Selection Sort in descending order


void selectionSortDescending(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
int max_idx = i;
for (int j = i+1; j < n; j++) {
// Find the maximum element in the unsorted part
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
// Swap the found maximum element with the first element
int temp = arr[max_idx];
arr[max_idx] = arr[i];

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 66
arr[i] = temp;
}
}

int main() {
int n;

// Asking user to input the number of elements in the array


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

int arr[n];

// Input elements of the array


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

// Call the selectionSortDescending function


selectionSortDescending(arr, n);

// Output the sorted array


printf("Sorted array in descending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\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.

*****************************End of Program & Output*************************


e. Write a C program that sorts the given array of integers using insertion sort in ascending
order[ Insertion Sort (Ascending Order)]
#include <stdio.h>

// Function to perform Insertion Sort in ascending order


void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;

// 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;

// Asking user to input the number of elements in the array


printf("Enter the number of elements in the array: ");
scanf("%d", &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]);
}

// Call the insertionSort function


insertionSort(arr, n);

// Output the sorted array


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

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>

#define MAX 100 // Maximum number of names


#define LEN 100 // Maximum length of each name

// Function to perform Bubble Sort on strings


void bubbleSortNames(char arr[][LEN], int n) {
char temp[LEN];

// Perform bubble sort on the array of names


for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
// Compare adjacent names and swap if they are in wrong order
if (strcmp(arr[j], arr[j+1]) > 0) {
strcpy(temp, arr[j]);
strcpy(arr[j], arr[j+1]);
strcpy(arr[j+1], temp);
}
}
}
}

int main() {
int n;

// Asking user to input the number of names


printf("Enter the number of names: ");
scanf("%d", &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);

// Output the sorted list of names


printf("\nNames sorted in alphabetical order:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", names[i]);
}

return 0;
}

Output :

Explanation:

1.​ Bubble Sort for Strings:


○​ We use the strcmp function to compare two strings lexicographically. If
strcmp(arr[j], arr[j+1]) > 0, it means arr[j] is greater than arr[j+1], so
we swap them using strcpy.
○​ This is done repeatedly until all the names are sorted in ascending alphabetical order.
2.​ Function bubbleSortNames:
○​ It takes a 2D array arr (for storing strings) and the number of strings n.
○​ The outer loop iterates over the array, and the inner loop compares adjacent names and
swaps them if needed.
3.​ main function: Handles input/output operations, reads the array of names, and calls the
bubbleSortNames function to sort them alphabetically.

*****************************End of Program & Output*************************

Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 71
Prepared by - Dr. Afreen Bari, Baseer Fatima & Kausar Jahan - SWCET 72

You might also like