Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

Date: 17/08/2023

Q1. Write a program to print the sum and product of digits of an integer.

Source code :
#include<stdio.h>
int sumofDigits(int x) //starting of sumofDigits() function
{
int r, sum;
for(sum = 0; x != 0; x /= 10)
{
r = x % 10;
sum += r;
}
return (sum);
} //end of sumofDigits() function
int proofDigits(int x) //starting of proofDigits() function
{
int r, pro;
for(pro = 1; x != 0; x /= 10)
{
r = x % 10;
pro *= r;
}
return (pro);
} //end of proofDigits() function
int main() //starting of main() function
{
int n;
printf("Enter an Integer number:");
scanf("%d", &n); //get the input of the integer number
printf("\nThe sum of digits of %d is: %d", n, sumofDigits(n));
//displaing the output
printf("\nThe product of digits of %d is: %d", n, proofDigits(n));
//display the output
return 0;
} //end of main() function

Output :
Enter an Integer number:145

The sum of digits of 145 is: 10


The product of digits of 145 is: 20

Discussion :
This C program aims to calculate the sum and product of the digits of a given integer. It consists of three
functions: sumofDigits, proofDigits, and main. The sumofDigits function uses a loop to extract each digit of
the input integer 'x' using modulo and division operations, adding them to a running sum. The function then
returns the calculated sum. Similarly, the proofDigits function calculates the product of the digits by
iteratively multiplying each digit and returning the final product. In the main function, the user is prompted
to input an integer, and the program then calls both sumofDigits and proofDigits functions to display the
sum and product of its digits, respectively. The program utilizes basic control structures, such as loops and
conditional statements, and standard input/output functions for user interaction. It provides a straightforward
example of modular programming to perform specific tasks related to digit manipulation in a given integer.
1
Date: 21/08/2023
Q2. Write a program to find whether a given number is prime or not. Use the same to generate the
prime number less than 100.

Source code :
#include<stdio.h>
int checkprime(int x) //starting of checkprime() function
{
int i;
if(x <= 1)
return 0; //not prime
for(i = 2; i <= x/2; i++)
if(x % i == 0)
return 0; //not prime
return 1; //prime
} //ending of chechprime() function
int main() //starting of main function
{
int num, i;
printf("Enter an Integer number:");
scanf("%d", &num); //take input from the user
if(checkprime(num))
printf("\nThe given number %d is a prime number.", num);
else
printf("\nThe given number %d is not a prime number.", num);
//end of prime number checking
printf("\nThe all prime numbers under 100 are:\n"); //starting of the
outher half
for(i = 2; i <= 100; i++)
if(checkprime(i))
printf("%3d", i);
return 0;
} //end of main() function

Output :
Enter an Integer number:13

The given number 13 is a prime number.


The all prime numbers under 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Discussion :
This C program is designed to determine whether a given integer is a prime number or not and then display a
list of prime numbers below 100. The program defines a function named `checkprime` that takes an integer
argument and returns 1 if the number is prime and 0 otherwise. Within the function, it first checks if the
input is less than or equal to 1, in which case it is considered not prime. Then, it iterates from 2 to half of the
input number, checking for any divisors. If a divisor is found, the function returns 0; otherwise, it returns 1,
indicating that the number is prime. In the `main` function, the user is prompted to enter an integer, and the
program uses the `checkprime` function to determine if it is prime, providing the corresponding output.
Additionally, the program prints all prime numbers below 100 by iterating through numbers from 2 to 100
and using the `checkprime` function to identify and display prime numbers. The program effectively
combines input validation, prime number checking, and prime number generation below a specified limit.

2
Date: 22/08/2023
Q3. Write a program to perform the following actions –
i. Print the even valued number from an array.
ii. Print the odd valued numbers from the array.
iii. Print the maximum and minimum element of array.

Source code :
#include<stdio.h>
void checkevenodd(int a[], int l) //starting of checkevenodd() function
{
int temp1, temp2, i, flag1 = 0, flag2 = 0;
for(i = 0; i < l; i++) //starting of first for loop
{
if(a[i] % 2 == 0)
flag1 = 1;
else
flag2 = 1;
} //ending of first for loop
if(flag1 == 1)
printf("\nThe even numbers of the array are:\n");
else
printf("\nThere are no even numbers in the array.");
for(i = 0; i < l; i++) //starting of second for loop
if(a[i] % 2 == 0)
printf("%3d", a[i]); //ending of second for loop
if(flag2 == 1)
printf("\nThe odd numbers of the array are:\n");
else
printf("\nThere are no odd numbers in the array.");
for(i = 0; i < l; i++) //starting of third for loop
if(a[i] % 2 != 0)
printf("%3d", a[i]); //ending of third for loop
} //end of checkevenodd() function
void checkmaxmin(int a[], int l) //starting of checkmaxmin() function
{
int max = a[0], min = a[0], i;
for(i = 0; i < l; i++) //starting of for loop
{
if(max < a[i])
max = a[i];
if(min > a[i])
min = a[i];
} //ending of for loop
printf("\n\nThe maximum value of the array is: %d", max);
printf("\nThe minimum value of the array is: %d", min);
} //ending of checkmaxmin() function
int main() //starting of main() function
{
int A[99], i, len;
printf("Enter the lenth of the array:");
scanf("%d", &len);//take input of the length of the array from the user
printf("Enter the array elements:\n");
for(i = 0; i < len; i++)
scanf("%d", &A[i]);//take input of the array elements from the user
checkevenodd(A, len);
checkmaxmin(A, len);
return 0;
3
} //ending of main() function

Output :
Enter the lenth of the array:5
Enter the array elements:
1 2 4 5 3

The even numbers of the array are:


2 4
The odd numbers of the array are:
1 5 3

The maximum value of the array is: 5


The minimum value of the array is: 1
Discussion :

This C program performs analysis on an array entered by the user. The program first prompts the user to
input the length of the array and then the array elements. It consists of two functions: `checkevenodd` and
`checkmaxmin`. The `checkevenodd` function determines and displays the even and odd numbers in the
array. It employs two flags, `flag1` and `flag2`, to track the presence of even and odd numbers, respectively.
The `checkmaxmin` function calculates and prints the maximum and minimum values within the array. The
main function initializes an array, takes user input for its length and elements, and then calls the two
functions to display even/odd numbers and maximum/minimum values. Overall, the program offers a
comprehensive analysis of the input array, showcasing its even and odd numbers as well as its maximum and
minimum values.

4
Date: 23/08/2023
Q4. Write a program to search an element from a given array. If the element is found then print
“found” Otherwise print “not found”.

Source code :
#include<stdio.h>
void founditem(int a[], int l, int itm) //starting of founditem() function
{
int i, flag = 0;
for(i = 0; i < l; i++)
if(itm == a[i]) //check weather the item is found or not
{
flag = 1;
break;
}
if(flag == 1)
printf("\nThe item is found.");
else
printf("\nThe item is not found.");
} //end of founditem() function
int main() //start of main() function
{
int A[99], len, i, item;
printf("Enter the range of the loop:");
scanf("%d", &len); //get input of the lenth from the user
printf("Enter the array elements:\n");
for(i = 0; i < len; i++)//get input of the array elements from the user
scanf("%d", &A[i]);
printf("Enter the item to found:");
scanf("%d", &item); //get input of the item from the user
//finding the item
founditem(A, len, item);
return 0;
}

Output :
Enter the range of the loop:5
Enter the array elements:
45 52 69 85 57
Enter the item to found:69

The item is found.


Discussion :
This C program is designed to search for a specified item within an array. The `founditem` function takes
three parameters: an integer array `a`, its length `l`, and the item to be found `itm`. The function iterates
through the array using a for loop, checking whether each element is equal to the target item. If a match is
found, the `flag` variable is set to 1, and the loop breaks. After the loop, the program checks the value of
`flag` to determine if the item was found or not. If `flag` is 1, it prints a message indicating that the item is
found; otherwise, it prints a message stating that the item is not found.

In the `main` function, the user is prompted to enter the range of the loop, array elements, and the item to be
found. The program then calls the `founditem` function with the provided array, its length, and the target
item as arguments. The result of the search is displayed to the user. Overall, this program provides a simple
and direct implementation of linear search within an array for a specified item.
5
Date: 28/08/2023
Q5. Write a program to merge two array and also remove the duplicates.

Source code :
#include<stdio.h>
//starting of murgeremoveduparray() function
int murgeremoveduparray(int a1[], int l1, int a2[], int l2)
{
int a3[99], i, j, k, n;
for(i = 0; i < l1; i++)
a3[i] = a1[i]; //copping firsst array to the new array
for(i = 0; i < l2; i++)
a3[l1 + i] = a2[i]; //adding second array to the new array
n = l1 + l2; //n is the new array's lentch
for(i = 0; i < n; i++) //starting of first for loop
{
for(j = i + 1; j < n; ) //starting of second for loop
{
if(a3[i] == a3[j]) //starting of if-else
{
//starting of third for loop
for(k = j; k < n - 1; k++)
a3[k] = a3[k + 1];
//ending of third for loop
n--; //decressing the length of the new array
}
else
j++; //ending of if-else
}
}
//display the ressult
printf("\nThe array after murge and deleting duplicate value is:\n");
for(i = 0; i < n; i++)
printf("%3d", a3[i]);
}
int main() //starting of main() funcction
{
int A[99], B[99], i, len1, len2;
printf("Enter the first arraes length:");
scanf("%d", &len1);//get input of the first array's length from the user
printf("Enter the first arraes elements:\n");
for(i = 0; i < len1; i++)
scanf("%d", &A[i]); //get the first array's elements from the user
printf("Enter the second arraes length:");
scanf("%d", &len2);//get input of the second array's length from the user
printf("Enter the second arraes elements:\n");
for(i = 0; i < len2; i++)
scanf("%d", &B[i]);//get the second array's elements from the user
murgeremoveduparray(A, len1, B, len2);
return 0;
} //ending of main() function

6
Output :
Enter the first arraes length:5
Enter the first arraes elements:
1 2 3 4 5
Enter the second arraes length:5
Enter the second arraes elements:
3 4 5 6 7

The array after murge and deleting duplicate value is:


1 2 3 4 5 6 7

Discussion :
This C program defines a function named `murgeremoveduparray` and a `main` function to merge two
arrays, remove duplicate elements, and display the resulting array. The `murgeremoveduparray` function
takes two arrays (`a1` and `a2`) along with their lengths (`l1` and `l2`) as parameters. It merges these arrays
into a new array `a3`, eliminating duplicate elements. The program utilizes nested loops to compare
elements in the merged array (`a3`) and removes duplicates by shifting subsequent elements to fill the gap.
The final merged and deduplicated array is then displayed. The `main` function prompts the user to input the
lengths and elements of two arrays (A and B) and calls the `murgeremoveduparray` function with these
arrays and their lengths as arguments. Overall, the program aims to efficiently merge two arrays while
eliminating any duplicate values and displays the resulting array to the user. Note that there are a couple of
typos in the program, such as "murgeremoveduparray" (possibly intended to be "merge_removedup_array")
and "lentch" (likely intended to be "length").

7
Date: 28/08/2023
Q6. Write a menu-driven program to perform following Matrix operations (2-D array
implementation):
a) Sum
b) Difference
c) Product
d) Transpose

Source code :
#include<stdio.h>
#define max_row 10
#define max_col 10

//a function to input a matrix eliments


void getmatrix(int matx[][max_col], int row, int col)
{
int i, j;
printf("\nEnter the elements of the matrix:\n");
for(i = 0; i < row; i++)
for(j = 0; j < col; j++)
scanf("%d", &matx[i][j]);
}
//a function to display a matrix
void putmatrix(int matx[][max_col], int row, int col)
{
int i, j;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
printf("%3d", matx[i][j]);
printf("\n");
}
}
//a function to add two matrix
void addmatrix(int matx1[][max_col], int matx2[][max_col], int resl[][max_col],
int row1, int col1, int row2, int col2)
{
int i, j, flag = 0;
if(row1 != row2 || col1 != col2)
printf("\nThe matrix can not being added.");
else
{
flag = 1;
for(i = 0; i < row1; i++)
for(j = 0; j < col1; j++)
resl[i][j] = matx1[i][j] + matx2[i][j];
}
if(flag == 1)
{
printf("\nThe matrix after addition:\n");
putmatrix(resl, row1, col1);
}
}
//a function to substract two matrix
void submatrix(int matx1[][max_col], int matx2[][max_col], int resl[][max_col],
int row1, int col1, int row2, int col2)
{
8
int i, j, flag = 0;
if(row1 != row2 || col1 != col2)
printf("\nThe matrix can not being subsctracted.");
else
{
flag = 1;
for(i = 0; i < row1; i++)
for(j = 0; j < col1; j++)
resl[i][j] = matx1[i][j] - matx2[i][j];
}
if(flag == 1)
{
printf("\nThe matrix after substraction:\n");
putmatrix(resl, row1, col1);
}
}
//a function to multiply two matrix
void promatrix(int matx1[][max_col], int matx2[][max_col], int resl[][max_col],
int row1, int col1, int row2, int col2)
{
int i, j, k, flag = 0;
if(col1 != row2)
printf("\nThe matrix can not being multiplied.");
else
{
flag = 1;
for(i = 0; i < row1; i++)
{
for(j = 0; j < col2; j++)
{
resl[i][j] = 0;
for(k = 0; k < col1; k++)
resl[i][j] += matx1[i][k] * matx2[k][j];
}
}
}
if(flag == 1)
{
printf("\nThe matrix after multification:\n");
putmatrix(resl, row1, col2);
}
}
//a function to transpose a matrix
void transposematrix(int matx[][max_col], int resl[][max_col], int row, int
col)
{
int i, j;
for(i = 0; i < col; i++)
for(j = 0; j < row; j++)
resl[i][j] = matx[j][i];
}
//starting of main function
int main()
{
int A[max_row][max_col], B[max_row][max_col], row1, col1, row2, col2,
resl[max_row][max_col];
char chos;
do
{
printf("\nEnter a for addition.");
printf("\nEnter b for substraction.");
9
printf("\nEnter c for multification.");
printf("\nEnter d for transpose.");
printf("\nEnter x to exit the program.");
printf("\nEnter your choise:");
scanf("%c", &chos);
switch(chos)
{
case 'a':
printf("\nEnter the number of row and colum of the first
matrix:");
scanf("%d%d", &row1, &col1);
getmatrix(A, row1, col1);
printf("\nThe first matrix is:\n");
putmatrix(A, row1, col1);
printf("\nEnter the number of row and colum of the second
matrix:");
scanf("%d%d", &row2, &col2);
getmatrix(B, row2, col2);
printf("\nThe second matrix is:\n");
putmatrix(B, row2, col2);
//adding two matrix
addmatrix(A, B, resl, row1, col1, row2, col2);
break;

case 'b':
printf("\nEnter the number of row and colum of the first
matrix:");
scanf("%d%d", &row1, &col1);
getmatrix(A, row1, col1);
printf("\nThe first matrix is:\n");
putmatrix(A, row1, col1);
printf("\nEnter the number of row and colum of the seconf
matrix:");
scanf("%d%d", &row2, &col2);
getmatrix(B, row2, col2);
printf("\nThe second matrix is:\n");
putmatrix(B, row2, col2);
//substracting two matrix
submatrix(A, B, resl, row1, col1, row2, col2);
break;

case 'c':
printf("\nEnter the number of row and colum of the first
matrix:");
scanf("%d%d", &row1, &col1);
getmatrix(A, row1, col1);
printf("\nThe first matrix is:\n");
putmatrix(A, row1, col1);
printf("\nEnter the number of row and colum of the second
matrix:");
scanf("%d%d", &row2, &col2);
getmatrix(B, row2, col2);
printf("\nThe second matrix is:\n");
putmatrix(B, row2, col2);
//multiplying two matrix
promatrix(A, B, resl, row1, col1, row2, col2);
break;
case 'd':
printf("\nEnte the number of row and colum of the
matrix:");
scanf("%d%d", &row1, &col1);
10
getmatrix(A, row1, col1);
printf("\nThe matrix is:\n");
putmatrix(A, row1, col1);
//transposing matrix
transposematrix(A, resl, row1, col1);
printf("\nThe matrix after transpose:\n");
putmatrix(resl, col1, row1);
break;
case 'x':
printf("\nExiting from the program.");
break;
default:
printf("\nWrong input. Try again.\n");
}
}while(chos != 'x');
return 0;
}
Output :
Enter a for addition.
Enter b for substraction.
Enter c for multification.
Enter d for transpose.
Enter x to exit the program.
Enter your choise:c

Enter the number of row and colum of the first matrix:2 3

Enter the elements of the matrix:


1 2 3 4 5 6

The first matrix is:


1 2 3
4 5 6

Enter the number of row and colum of the second matrix:3 2

Enter the elements of the matrix:


1 4 7 8 5 2

The second matrix is:


1 4
7 8
5 2

The matrix after multification:


30 26
69 68

Enter a for addition.


Enter b for substraction.
Enter c for multification.
Enter d for transpose.
Enter x to exit the program.
Enter your choise:
Wrong input. Try again.

Enter a for addition.


Enter b for substraction.
Enter c for multification.
Enter d for transpose.

11
Enter x to exit the program.
Enter your choise:
Wrong input. Try again.

Enter a for addition.


Enter b for substraction.
Enter c for multification.
Enter d for transpose.
Enter x to exit the program.
Enter your choise:x

Exiting from the program.


Discussion :

This C program is designed to perform various operations on matrices. It begins by defining a maximum
number of rows and columns using preprocessor directives. The program includes functions for matrix
input, display, addition, subtraction, multiplication, and transposition. The main function operates within a
do-while loop, allowing users to choose between matrix addition, subtraction, multiplication, transposition,
or exiting the program. Users input matrices and their dimensions, and the program performs the selected
operation, displaying the result if applicable. The code is well-structured, with modular functions for each
operation, enhancing readability and maintainability. Additionally, the program employs a character-based
menu system, making it user-friendly. Overall, this program serves as a versatile tool for basic matrix
operations, providing a practical illustration of modular programming in C.

12
Date: 04/10/2023
Q7. Write a program in C using structure to perform addition and subtraction between two complex
number using functions.

Source code :
#include<stdio.h>

//definning a structure for complex number


struct complex
{
float real;
float imagi;
};
//definning a function to add two complex numbers
struct complex add(struct complex num1, struct complex num2)
{
struct complex result;
result.real = num1.real + num2.real;
result.imagi = num1.imagi + num2.imagi;
return (result);
}
//definning a function for subtraction of two complex numbers
struct complex subtract(struct complex num1, struct complex num2)
{
struct complex result;
result.real = num1.real - num2.real;
result.imagi = num1.imagi - num2.imagi;
return (result);
}
//starting of main function
int main()
{
struct complex c_num1, c_num2, sum, difference;
printf("Enter the real and imaginary numbers of the first complex
number:");
scanf("%f%f", &c_num1.real, &c_num2.imagi);
printf("Enter the real and imaginary numbers of the seconf complex
number:");
scanf("%f%f", &c_num2.real, &c_num2.imagi);
sum = add(c_num1, c_num2);
difference = subtract(c_num1, c_num2);
//display the result
printf("sum: %.2f + %.2fi\n", sum.real, sum.imagi);
printf("difference: %.2f - %.2fi\n", difference.real, difference.imagi);

return 0;
}

Output :
Enter the real and imaginary numbers of the first complex number:2 4
Enter the real and imaginary numbers of the seconf complex number:4 2
sum: 6.00 + 2.00i
difference: -2.00 - -2.00i

13
Discussion :

This C program defines a structure for complex numbers, consisting of a real and imaginary part. It then
declares functions to add and subtract two complex numbers, each taking two complex number structures as
parameters and returning a complex number structure as the result. In the main function, it prompts the user
to enter the real and imaginary parts of two complex numbers, performs addition and subtraction using the
defined functions, and displays the results. However, there is a small error in the user input section where the
imaginary part of the first complex number is assigned to the imaginary part of the second complex number
during the input process. The correct assignment should be `scanf("%f%f", &c_num1.real,
&c_num1.imagi);` instead of `scanf("%f%f", &c_num1.real, &c_num2.imagi);`. Additionally, the program
displays the incorrect input prompt for the second complex number. The corrected prompt should be "Enter
the real and imaginary numbers of the second complex number:". Overall, the program aims to perform
basic arithmetic operations on complex numbers and demonstrate the use of structures and functions in C.

14
Date: 11/10/2023
Q8. Design a structure Time containing two members- hours and minutes. There should be functions
for doing the following.
a) To read time
b) To display time
c) To get the sum of two times passed as arguments

Source code :
#include <stdio.h>

// Structure definition
struct Time
{
int hours;
int minutes;
};

// Function to read time


void readTime(struct Time *t)
{
printf("Enter hours: ");
scanf("%d", &t->hours);

printf("Enter minutes: ");


scanf("%d", &t->minutes);
}

// Function to display time


void displayTime(const struct Time *t)
{
printf("Time: %02d:%02d\n", t->hours, t->minutes);
}

// Function to get the sum of two times


struct Time addTimes(const struct Time *t1, const struct Time *t2)
{
struct Time result;

result.minutes = (t1->minutes + t2->minutes) % 60;


result.hours = t1->hours + t2->hours + (t1->minutes + t2->minutes) / 60;

return result;
}

int main()
{
struct Time time1, time2, sum;

// Read and display the first time


printf("Enter the first time:\n");
readTime(&time1);
displayTime(&time1);

15
// Read and display the second time
printf("\nEnter the second time:\n");
readTime(&time2);
displayTime(&time2);

// Get and display the sum of two times


sum = addTimes(&time1, &time2);
printf("\nSum of the two times:\n");
displayTime(&sum);

return 0;
}
Output :
Enter the first time:
Enter hours: 8
Enter minutes: 14
Time: 08:14

Enter the second time:


Enter hours: 6
Enter minutes: 24
Time: 06:24

Sum of the two times:


Time: 14:38
Discussion :

This C program defines a structure `Time` to represent hours and minutes. It includes functions to read time,
display time, and add two time values. The `readTime` function takes a pointer to a `Time` structure as an
argument and prompts the user to enter hours and minutes, storing the input in the structure. The
`displayTime` function takes a constant pointer to a `Time` structure and prints the time in a formatted way.
The `addTimes` function calculates the sum of two time structures, accounting for the carry-over of minutes
into hours. In the `main` function, it declares three `Time` structures: `time1`, `time2`, and `sum`. It prompts
the user to input two times, displays them, calculates their sum using the `addTimes` function, and finally
prints the result. The program provides a simple example of using structures and functions in C to
manipulate time data.

16
Date: 22/11/2023
Q9. Design a structure Fraction which contains data members for numerator and denominator. The
program should add two fractions using function.

Source code :
#include<stdio.h>

//definning a structure for Fraction


struct Fraction
{
int numerator;
int denominator;
};
//definning a function to add two Fraction
struct Fraction addFraction(struct Fraction f1, struct Fraction f2)
{
int lcm, num1, num2, gcdResult, sumofn;
struct Fraction result;
lcm = (f1.denominator * f2.denominator) / gcd(f1.denominator,
f2.denominator);
num1 = f1.numerator * (lcm / f1.denominator);
num2 = f2.numerator * (lcm / f2.denominator);
sumofn = num1 + num2;
gcdResult = gcd(sumofn, lcm);
result.numerator = sumofn / gcdResult;
result.denominator = lcm / gcdResult;
return (result);
}
//definning a function for gcd
int gcd(int a, int b)
{
int temp;
while(b != 0)
{
temp = b;
b = a % b;
a = temp;
}
return (a);
}
//starting of main() function
int main()
{
struct Fraction num1, num2, sum;
printf("Enter the numerator and denominator part of the first
fraction:");
scanf("%d%d", &num1.numerator, &num1.denominator);
printf("Enter the numerator and denominator part of the first
fraction:");
scanf("%d%d", &num2.numerator, &num2.denominator);
sum = addFraction(num1, num2);
printf("\nThe sum of %d/%d and %d/%d is: %d/%d", num1.numerator,
num1.denominator, num2.numerator, num2.denominator, sum.numerator,
sum.denominator);
return 0;
}

17
Output :
Enter the numerator and denominator part of the first fraction:1 2
Enter the numerator and denominator part of the first fraction: 1 4

The sum of 1/2 and 1/4 is: 3/4

Discussion :

This C program is designed to perform the addition of two fractions. It defines a structure named `Fraction`
to represent fractions with a numerator and a denominator. The program includes three functions:
`addFraction`, `gcd`, and `main`.

The `addFraction` function takes two fractions (`struct Fraction f1` and `struct Fraction f2`) as input,
calculates their least common multiple (LCM), adjusts the numerators accordingly, finds the sum of the
adjusted numerators, calculates the greatest common divisor (GCD) of the sum and LCM, and finally
simplifies the result by dividing both the numerator and denominator by the GCD. The `gcd` function
calculates the GCD of two integers using the Euclidean algorithm.

In the `main` function, the user is prompted to enter the numerator and denominator for two fractions
(`num1` and `num2`). The program then calls the `addFraction` function to compute the sum and displays
the result along with the original fractions. Note that there's a minor error in the program where the second
prompt for user input mistakenly mentions the "first fraction" again instead of prompting for the second
fraction.

Overall, this program provides a simple and efficient way to add two fractions while handling the necessary
arithmetic operations for proper fraction addition.

18
Date: 29/11/2023
Q10. Write a program to copy the contains of one file into another.

Source code :
#include <stdio.h>

//starting of main() function


int main()
{
FILE *sourceFile, *destinationFile;
char sourceFileName[100], destinationFileName[100];
char ch;

// Get source file name from the user


printf("Enter source file name: ");
scanf("%s", sourceFileName);

// Open the source file in read mode


sourceFile = fopen(sourceFileName, "r");

if (sourceFile == NULL)
{
printf("Error opening source file.\n");
return 1;
}

// Get destination file name from the user


printf("Enter destination file name: ");
scanf("%s", destinationFileName);

// Open the destination file in write mode


destinationFile = fopen(destinationFileName, "w");

if (destinationFile == NULL)
{
printf("Error opening destination file.\n");
fclose(sourceFile);
return 1;
}

else
{
// Copy contents from source file to destination file
while ((ch = fgetc(sourceFile)) != EOF)
fputc(ch, destinationFile);
printf("\nFile copid successfully.");
}

// Close both files


fclose(sourceFile);
fclose(destinationFile);

printf("File copy successful.\n");

return 0;
} //ending of main() function

19
Output :
File copid successfully.

Discussion :

This C program is designed to copy the contents of one file to another. It begins by declaring two file
pointers, `sourceFile` and `destinationFile`, and two character arrays, `sourceFileName` and
`destinationFileName`, to store the names of the source and destination files, respectively. The user is
prompted to enter the name of the source file, and if the file cannot be opened, an error message is
displayed, and the program terminates. Next, the user is prompted for the destination file name, and if the
destination file cannot be opened, an error message is displayed, the source file is closed, and the program
terminates. If both files are successfully opened, the program enters an else block where it reads each
character from the source file using `fgetc` and writes it to the destination file using `fputc` until the end of
the source file is reached. Finally, both files are closed, and a success message is displayed. It's worth noting
that there is a typo in the success message inside the loop, which states "File copid successfully" instead of
"File copied successfully." Overall, the program provides a basic file copy functionality but could benefit
from additional error handling and correction of the typo for better robustness and user feedback.

20
Data: 06/12/2023
Q11. A file named DATA Contains a series of integer numbers. Code a program to read these
numbers and then write all odd numbers to a file ODD and all even numbers to a file EVEN.

Source code :
#include <stdio.h>

int main()
{
FILE *inputFile, *oddFile, *evenFile;
int number;

// Open the input file


inputFile = fopen("DATA", "r");
if (inputFile == NULL)
{
printf("Error opening input file.\n");
return 1;
}

// Open the output files for odd and even numbers


oddFile = fopen("ODD", "w");
if (oddFile == NULL)
{
printf("Error opening ODD file.\n");
fclose(inputFile);
return 1;
}

evenFile = fopen("EVEN", "w");


if (evenFile == NULL)
{
printf("Error opening EVEN file.\n");
fclose(inputFile);
fclose(oddFile);
return 1;
}

// Read numbers from DATA file and write to ODD or EVEN file accordingly
while (fscanf(inputFile, "%d", &number) == 1)
{
if (number % 2 == 0)
fprintf(evenFile, "%d\n", number);
else
fprintf(oddFile, "%d\n", number);
}

// Close all files


fclose(inputFile);
fclose(oddFile);
fclose(evenFile);

printf("Numbers separated into ODD and EVEN files successfully.\n");

return 0;
}

21
Output :
Error opening input file.

Discussion :

This C program demonstrates a simple file handling operation where it reads a file named "DATA"
containing integers, and then separates the numbers into two output files, "ODD" and "EVEN," based on
whether they are odd or even. The program begins by opening the input file, and if successful, it proceeds to
open two output files for odd and even numbers. It then iterates through the numbers in the input file,
determining if each number is odd or even, and writes them to the respective output files accordingly.
Finally, the program closes all the files, providing error messages if any file opening fails. This program
effectively organizes the input data into two separate files based on the parity of the numbers, offering a
clear and modular approach to file manipulation in C.

22
Date: 13/12/2023
Q12. Write a program that swaps two numbers using pointers.

Source code :
#include<stdio.h>

//definning a function to swap two numbers using pointers


void swapnum(int *num1, int *num2)
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
//starting of main() function
int main()
{
int num1, num2;
printf("Enter the first and second numbers:");
scanf("%d%d", &num1, &num2);
printf("\nThe numbers before swap:");
printf("\nFirst number: %d", num1);
printf("\nSecond number: %d", num2);
swapnum(&num1, &num2);
printf("\nThe numbers after swap:");
printf("\nFirst number: %d", num1);
printf("\nSecond number: %d", num2);
return 0;
}

Output :
Enter the first and second numbers:12 14

The numbers before swap:


First number: 12
Second number: 14
The numbers after swap:
First number: 14
Second number: 12

Discussion :

This C program is designed to swap two numbers entered by the user using pointers. The program begins by
defining a function named `swapnum` that takes two integer pointers as parameters and swaps the values
they point to. Inside the `main` function, two integer variables `num1` and `num2` are declared to store user-
inputted values. The user is prompted to enter the values of these numbers using the `scanf` function. Before
the swap, the program prints the original values of `num1` and `num2`. It then calls the `swapnum` function,
passing the addresses of `num1` and `num2` as arguments to perform the swap. Finally, the program prints
the swapped values of `num1` and `num2`. This program utilizes pointers to manipulate the values of
variables directly in memory, providing an efficient way to exchange the values of two variables without
requiring a temporary variable.

23
Date: 10/01/2024
Q13. Write a menu drive program to perform following operations on strings:
a) Show address for each character in string.
b) Concatenate two strings without using strcate function.
c) Concatenate two strings using stract function.
d) Compare to strings.
e) Calculate length of the string (using pointer).
f) Convert all lowercase characters to uppercase.
g) Convert all uppercase characters to lowercase.
h) Calculate number of vawels.
i) Reverse the string.

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

//a function to show address of each characters in the string


void showAddress(char *str)
{
int i;
printf("Address for each character in the string:\n");
for (i = 0; str[i] != '\0'; i++)
printf("%c: %p\n", str[i], (void *)&str[i]);
}

//a function to concatenate two strings without using strcat function


void concatenateWithoutStrcat(char *str1, char *str2)
{
int len1 = strlen(str1);
int i, j = 0;

for (i = len1; str2[j] != '\0'; i++, j++)


str1[i] = str2[j];
str1[i] = '\0';
printf("Concatenated string: %s\n", str1);
}

//a function to concatenate two strings using strcat function


void concatenateWithStrcat(char *str1, char *str2)
{
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
}

//a function to compare two strings


int compareStrings(char *str1, char *str2)
{
return strcmp(str1, str2);
}

//a function to calculate the langth of a string


int calculateLength(char *str)
{
int length = 0;
while (*str != '\0')
{

24
length++;
str++;
}
return (length);
}

//a function to convert all upperscase characters to lowercase


void convertToLowercase(char *str)
{
while (*str != '\0')
{
if (*str >= 'A' && *str <= 'Z')
*str = *str + 32; // Convert to lowercase
str++;
}
printf("String in lowercase: %s\n", str);
}

//a function to convert all lowercase characters to uppercase


void convertToUppercase(char *str)
{
while (*str != '\0')
{
if (*str >= 'a' && *str <= 'z')
*str = *str - 32; // Convert to uppercase
str++;
}
printf("String in uppercase: %s\n", str);
}

//a function to count all vawels in the string


int countVowels(char *str)
{
int count = 0;
while (*str != '\0')
{
if (*str == 'a' || *str == 'e' || *str == 'i' || *str == 'o' || *str ==
'u' ||
*str == 'A' || *str == 'E' || *str == 'I' || *str == 'O' || *str ==
'U')
count++;
str++;
}
return count;
}

//a function to reverse a string


void reverseString(char *str) {
int length = strlen(str);
int i;
char temp;

for (i = 0; i < length / 2; i++) {


temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}

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


}

25
//starting of main function
int main()
{
char str1[100], str2[100];
int choice;

printf("Enter the first string: ");


gets(str1); //get the first string from the user

printf("Enter the second string: ");


gets(str2); //get the second string from the user

do
{
printf("\nMenu:\n");
printf("1. Show address for each character in string.\n");
printf("2. Concatenate two strings without using strcat function.\n");
printf("3. Concatenate two strings using strcat function.\n");
printf("4. Compare two strings.\n");
printf("5. Calculate length of the string (using pointer).\n");
printf("6. Convert all lowercase characters to uppercase.\n");
printf("7. Convert all uppercase characters to lowercase.\n");
printf("8. Calculate number of vowels.\n");
printf("9. Reverse the string.\n");
printf("0. Exit.\n");

printf("Enter your choice: ");


scanf("%d", &choice);

switch (choice)
{
case 1:
showAddress(str1);
break;
case 2:
concatenateWithoutStrcat(str1, str2);
break;
case 3:
concatenateWithStrcat(str1, str2);
break;
case 4:
printf("Result of string comparison: %d\n",
compareStrings(str1, str2));
break;
case 5:
printf("Length of the first string: %d\n",
calculateLength(str1));
break;
case 6:
convertToUppercase(str1);
break;
case 7:
convertToLowercase(str1);
break;
case 8:
printf("Number of vowels in the first string: %d\n",
countVowels(str1));
break;
case 9:
reverseString(str1);
break;
26
case 0:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice. Please enter a valid option.\n");
}

} while (choice != 0); //end of do-while loop

return 0;
} //end of main function

Output :
Enter the first string: AAB
Enter the second string: BBS

Menu:
1. Show address for each character in string.
2. Concatenate two strings without using strcat function.
3. Concatenate two strings using strcat function.
4. Compare two strings.
5. Calculate length of the string (using pointer).
6. Convert all lowercase characters to uppercase.
7. Convert all uppercase characters to lowercase.
8. Calculate number of vowels.
9. Reverse the string.
0. Exit.
Enter your choice: 2
Concatenated string: AABBBS

Menu:
1. Show address for each character in string.
2. Concatenate two strings without using strcat function.
3. Concatenate two strings using strcat function.
4. Compare two strings.
5. Calculate length of the string (using pointer).
6. Convert all lowercase characters to uppercase.
7. Convert all uppercase characters to lowercase.
8. Calculate number of vowels.
9. Reverse the string.
0. Exit.
Enter your choice: 0
Exiting the program.

Discussion :
This C program performs various string manipulation operations through a user-friendly menu-driven
interface. It first prompts the user to input two strings, and then presents a menu with options for different
string operations. The program includes functions to display the memory addresses of each character in a
string, concatenate two strings both with and without using the `strcat` function, compare two strings,
calculate the length of a string using pointers, convert characters to uppercase and lowercase, count the
number of vowels in a string, and reverse a string. The program utilizes loops and conditional statements for
effective menu navigation and user input processing. It employs pointers to manipulate strings efficiently,
and the functions are designed to operate on the user-provided strings. However, there are some issues, such
as the use of the deprecated `gets` function, which could pose security risks due to buffer overflows. The
program would benefit from replacing `gets` with `fgets` for safer input handling. Additionally, when
converting characters to lowercase or uppercase, the program prints the modified string outside the loop,
potentially resulting in incorrect output. It would be more accurate to print the modified string inside the
loop after the conversion is complete.
27

You might also like