0% found this document useful (0 votes)
11 views32 pages

Assignment (SEM - 1) (Abhay)

Good

Uploaded by

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

Assignment (SEM - 1) (Abhay)

Good

Uploaded by

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

Date : 17/08/2023

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

Source Code :

// C Program To Find The Sum And Product Of Digits Of An Integer.


#include <stdio.h>
int main()
{
// Declaration
int n, dig, sum, pro;

// Input From User


printf("Enter an integer number: ");
scanf("%d", &n);

// Initialization
sum = 0;
pro = 1;

// Calculating Sum and Product


while (n > 0)
{
dig = n % 10;
sum = sum + dig;
pro = pro * dig;
n = n / 10;
}

// Displaying The Result Of Sum And Product Of An Integer


printf("\nSum Of All Digits Of An Integer is : %d", sum);
printf("\nProduct Of All The Digits Of An Integer is : %d", pro);
return 0;
}

Output :

Enter an integer number: 428

Sum Of All Digits Of An Integer is : 14

Product Of All The Digits Of An Integer is : 64

Discussion :

This C program computes the sum and product of the digits of a user-entered integer. It begins by
prompting the user for input, reads the integer into variable n, and initializes variables sum and pro to
0 and 1, respectively. The program then utilizes a while loop to iterate through each digit of the input,
updating sum and pro accordingly. Finally, it prints the calculated sum and product using printf. The
code is well-organized with clear variable names and comments, facilitating easy understanding of its
functionality.

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 :

/* C Program To Find Whether A Given Number is Prime or Not


And To Generate The Prime Numbers Less Than 100 */

#include <stdio.h>
int main()
{
// Declaration
int i, j, num, c;

// Input From User


printf("Enter the number: ");
scanf("%d", &num);

// Initialization
c = 0;

// To Find Whether A Number is Prime or Not


for (i = 1; i <= num; i++)
{
if (num % i == 0)
{
c++;
}
}

// To Check And Display Whether the Given Number is Prime or Not


if (c == 2)
{
printf("\nThe Given Number is a Prime Number");
}
else

2
printf("\nThe Given Number is Not a Prime Number");

// To Print All The Prime Numbers Less Than 100


printf("\nPrime Numbers Between 1 and 100 are : ");
for (i = 2; i <= 100; i++) // 0 And 1 Are Not Prime Numbers
{
for (j = 2; j <= i; j++)
{
if (i % j == 0)
{
break;
}
}
if (i == j)
{
// Displaying The Prime Number
printf("%d ", i);
}
}
return 0;
}

Output :

Enter the number: 89

The Given Number is a Prime Number

Prime Numbers Between 1 and 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 does two things. First, it checks if a number you type in is a prime number or not.
Second, it shows all the prime numbers less than 100. After you enter a number, it uses a method to
see if it can be divided evenly by numbers up to itself. If it can only be divided by 1 and itself, it's a
prime number. The program then tells you if the entered number is prime. After that, it finds and
shows all the prime numbers between 1 and 100. The program is easy to understand and the
comments in the code help to explain what each part is doing.

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

/*C Program To Print The Even And Odd Valued Number From An Array.
And To Find The Maximum And Minimum Element Of An Array*/

#include <stdio.h>
int main()
{
// Declaration
int n, i, max, min;

// Input From The User


printf("Enter The Number Of Elements In Array : ");
scanf("%d", &n);

// Array Declaration
int arr[n];

// Take n Elements As Input From The User


printf("\nEnter %d Elements In The Array : ", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

// To Find And Print All The Even Valued Numbers


printf("\nEven Numbers In The Array Are : ");
for (i = 0; i < n; i++)
{
if (arr[i] % 2 == 0)
printf("%d ", arr[i]);
}

// To Find And Print All The Odd Valued Numbers


printf("\nOdd Numbers In The Array Are: ");
for (i = 0; i < n; i++)
{
if (arr[i] % 2 == 1)
printf("%d ", arr[i]);
}

// To Find The Maximum Element Of An Array


max = arr[0];
for (i = 0; i < n; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}

4
// Displaying The Maximum Element
printf("\nMaximum Element Of An Array is : %d", max);

// To Find The Minimum Element Of An Array


min = arr[0];
for (i = 0; i < n; i++)
{
if (arr[i] < min)
{
min = arr[i];
}
}

// Displaying The Minimum Element


printf("\nMinimum Element Of An Array is : %d", min);

return 0;
}
Output :

Enter The Number Of Elements In Array : 6

Enter 6 Elements In The Array : 2 4 7 9 8 5

Even Numbers In The Array Are : 2 4 8

Odd Numbers In The Array Are: 7 9 5

Maximum Element Of An Array is : 9

Minimum Element Of An Array is : 2

Discussion :

This C program has a fourfold objective: it prints the even and odd numbers from an array, and then
finds and displays both the maximum and minimum elements within that array. The user is prompted
to input the number of elements in the array, after which the program initializes an array based on
this size. It then takes user inputs for the array elements.The program then proceeds to identify and
print the even and odd numbers separately using two separate loops. Following this, it finds the
maximum element in the array using a loop that iterates through each element, updating the
maximum value when a larger element is encountered. Similarly, it determines the minimum element
in the array using a loop that adjusts the minimum value upon finding a smaller element.Finally, the
program prints the calculated maximum and minimum values. This program provides a practical
demonstration of array manipulation and searching for maximum and minimum values.

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

/*C Program To Search An Element From A Given Array


And If The Element is Found Then Print 'Found' Otherwise Print 'Not Found'. */

#include <stdio.h>
int main()
{
// Declaration
int arr[50], n, i, ele;

// Input From The User


printf("Enter The Number Of Elements In Array : ");
scanf("%d", &n);

// Take n Elements As Input From The User


printf("\nEnter %d Elements In The Array : ", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

// Input The Element Which User Want To Search


printf("\nEnter The Element To Search : ");
scanf("%d", &ele);

// To Find The Searched Element


for (i = 0; i < n; i++)
{
if (arr[i] == ele)
{
// Displaying The Searched Element
printf("\n%d is Found At Position %d ", ele, i + 1);
return 0;

6
}
}
printf("\nElement is Not Found In The Array");

return 0;
}

Output :

Enter The Number Of Elements In Array : 6


Enter 6 Elements In The Array : 2 4 5 8 6 9
Enter The Element To Search : 5
5 is Found At Position 3
Discussion :

This C program is designed to search for a specific element in a user-provided array. It begins by
asking the user to input the number of elements they want in the array and then takes these elements
as input. Following this, the program prompts the user to enter the element they wish to search for
within the array.The core of the program lies in the subsequent loop that iterates through the array to
find the specified element. If the element is found, the program prints a message indicating the
element's position in the array. However, if the element is not found after checking the entire array, it
prints a message stating that the element is not present.The code is straightforward, effectively
utilizing a loop for the search process. The messages are clear and concise, making it easy for the user
to understand whether the desired element is present in the array and its position if found.

7
Date : 28/08/2023
Q5. Write a program to merge two array and also remove the duplicates.

Source Code :

// C Program To Merge Two Arrays And Also Remove The Duplicates.

#include <stdio.h>
int main()
{
// Declaration
int A[100], B[100], C[200], i, j, n1, n2, ind = 0;

// Input From User


printf("Enter The Number Of Elements In The First Array: ");
scanf("%d", &n1);

printf("\nEnter %d Elements In The First Array : ", n1);


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

printf("\nEnter The Number Of Elements In The Second Array: ");


scanf("%d", &n2);

printf("Enter %d Elements In The Second Array : ", n2);


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

// To Merge Two Arrays


for (i = 0; i < n1; i++)
{
C[ind++] = A[i];
}

for (i = 0; i < n2; i++)


{
C[ind++] = B[i];
}

// Display Merged Array


printf("\nMerged Array: ");
for (i = 0; i < n1+n2; i++)
{
printf("%d ", C[i]);
}

// To Remove Duplicates
ind = 0; // Reset index for reusing it
for (i = 0; i < n1+n2; i++)
{
int isDuplicate = 0;
for (j = 0; j < ind; j++)
{
if (C[i] == C[j])
{
isDuplicate = 1;

8
break;
}
}
if (!isDuplicate)
{
C[ind++] = C[i];
}
}

// Display Merged Array Without Duplicates


printf("\nMerged Array Without Duplicates: ");
for (i = 0; i < ind; i++)
{
printf("%d ", C[i]);
}

return 0;
}
Output :

Enter The Number Of Elements In The First Array: 8

Enter 8 Elements In The First Array : 1 4 6 8 2 3 9 7

Enter The Number Of Elements In The Second Array: 6

Enter 6 Elements In The Second Array : 4 2 6 5 10 12

Merged Array: 1 4 6 8 2 3 9 7 4 2 6 5 10 12

Merged Array Without Duplicates: 1 4 6 8 2 3 9 7 5 10 12

Discussion :

This C program serves a dual purpose: it merges two arrays and removes any duplicate elements from
the merged result. The program starts by prompting the user to input the number of elements in the
first and second arrays, followed by collecting the respective array elements. It then proceeds to merge
the two arrays into a third array, C, by sequentially copying elements from both arrays. The merged
array is displayed, showing the combination of elements from the first and second arrays.To address
duplicates, the program initiates a second step where it iterates through the merged array, identifying
and removing any duplicate elements. This is done by comparing each element with the ones that have
already been added to the new array, C. If an element is found to be unique, it is added to the new
array, effectively filtering out duplicates.The final result is presented by displaying the merged array
without duplicates. The program showcases effective array manipulation, merging, and duplicate
removal. Overall, the program provides a practical example of handling arrays and ensuring
uniqueness in a merged collection of elements.

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

/* A Menu-Driven Program To Perform Following Matrix Operations (2-D array


implementation):
a) Sum b) Difference c) Product d) Transpose */

#include <stdio.h>
// Function Declaration
void input(int A[30][30], int r, int c);
void display(int A[30][30], int r, int c);
void sum(int A[30][30], int B[30][30], int result[30][30], int r1, int c1, int
r2,int c2);
void diff(int A[30][30], int B[30][30], int result[30][30], int r1, int c1,int
r2, int c2);
void pro(int A[30][30], int B[30][30], int result[30][30], int r1, int c1, int
r2, int c2);
void trans(int A[30][30], int result[30][30], int r, int c);
int main()
{
// Declaration
int A[30][30], B[30][30], result[30][30], r1, c1, r2, c2;
char ch;
int choice;

do
{
// Matrix Operation Menu
printf("Menu : ");
printf("\n1. Sum Of The Matrix");
printf("\n2. Difference Of The Matrix");
printf("\n3. Product Of The Matrix");
printf("\n4. Transpose Of The Matrix");

printf("\nEnter Your Choice : ");


scanf("%d", &choice);
switch (choice)
{
// For Matrix Sum
case 1:
printf("\nEnter The Number Of Rows And Columns For Matrix 1 : ");
scanf("%d%d", &r1, &c1);

printf("\nEnter The Elements in Matrix 1 : ");


input(A, r1, c1);

printf("Enter The Number Of Rows And Columns For Matrix 2 : ");


scanf("%d%d", &r2, &c2);

10
printf("\nEnter The Elements in Matrix 2 : ");
input(B, r2, c2);

printf("\nThe 1st Given Matrix is : \n");


display(A, r1, c1);

printf("\nThe 2nd Given Matrix is : \n");


display(B, r2, c2);

printf("\nThe Sum Of The Two Matrices Are : \n");


sum(A, B, result, r1, c1, r2, c2);
break;

// For Matrix Difference


case 2:
printf("\nEnter The Number Of Rows And Columns For Matrix 1 : ");
scanf("%d%d", &r1, &c1);

printf("\nEnter The Elements in Matrix 1 : ");


input(A, r1, c1);

printf("Enter The Number Of Rows And Columns For Matrix 2 : ");


scanf("%d%d", &r2, &c2);

printf("\nEnter The Elements in Matrix 2 : ");


input(B, r2, c2);

printf("\nThe 1st Given Matrix is : \n");


display(A, r1, c1);

printf("\nThe 2nd Given Matrix is : \n");


display(B, r2, c2);

printf("\nThe Difference Of The Two Matrices Are : \n");


diff(A, B, result, r1, c1, r2, c2);
break;

// For Matrix Product


case 3:
printf("\nEnter The Number Of Rows And Columns For Matrix 1 : ");
scanf("%d%d", &r1, &c1);

printf("\nEnter The Elements in Matrix 1 : ");


input(A, r1, c1);

printf("Enter The Number Of Rows And Columns For Matrix 2 : ");


scanf("%d%d", &r2, &c2);

printf("\nEnter The Elements in Matrix 2 : ");


input(B, r2, c2);

printf("\nThe 1st Given Matrix is : \n");


display(A, r1, c1);

printf("\nThe 2nd Given Matrix is : \n");


display(B, r2, c2);

printf("\nThe Product Of The Two Matrices Are : \n");


pro(A, B, result, r1, c1, r2, c2);
break;

11
// For Matrix Transpose
case 4:
printf("\nEnter The Number Of Rows And Columns For Matrix : ");
scanf("%d%d", &r1, &c1);

printf("\nEnter The Elements in the Matrix : ");


input(A, r1, c1);

printf("\nThe Given Matrix is : \n");


display(A, r1, c1);

printf("\nThe Transpose Of The Matrix is : \n");


trans(A, result, r1, c1);
break;

default:
printf("\nWrong Choice.");
}
printf("\nDo you want to Continue ?(y/n): ");
scanf(" %c", &ch);

} while (ch == 'y' || ch == 'Y');

return 0;
}
// Function Definition
// To Input The Matrix From The User
void input(int A[30][30], int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
scanf("%d", &A[i][j]);
}
}
}
// To Display The Given Matrix
void display(int A[30][30], int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%5d", A[i][j]);
}
printf("\n");
}
}
// To Find The Sum Of The Two Matrices
void sum(int A[30][30], int B[][30], int result[][30], int r1, int c1, int
r2,int c2)
{
int i, j;
if (r1 == r2 && c1 == c2)
{
for (i = 0; i < r1; i++)
{

12
for (j = 0; j < c1; j++)
{
result[i][j] = A[i][j] + B[i][j];
printf("%5d", result[i][j]);
}
printf("\n");
}
}
}
// To Find The Difference Of The Two Matrices
void diff(int A[30][30], int B[30][30], int result[30][30], int r1, int c1, int
r2, int c2)
{
int i, j;
if (r1 == r2 && c1 == c2)
{
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
result[i][j] = A[i][j] - B[i][j];
printf("%5d ", result[i][j]);
}
printf("\n");
}
}
}
// To Find The Product Of The Two Matrices
void pro(int A[30][30], int B[30][30], int result[30][30], int r1, int c1, int
r2, int c2)
{
int i, j, k;
if (c1 == r2)
{
for (i = 0; i < r1; i++)
{
for (j = 0; j < c2; j++)
{
result[i][j] = 0;
for (k = 0; k < c1; k++)
{
result[i][j] += A[i][k] * B[k][j];
}
printf("%5d ", result[i][j]);
}
printf("\n");
}
}
else
{
printf("\nThe Given Matrix is Not A Sqaure Matrix.");
}
}
// To Find The Transpose Of A Matrix
void trans(int A[30][30], int result[30][30], int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{

13
result[i][j] = A[j][i];
printf("%5d ", result[i][j]);
}
printf("\n");
}
}
Output :

Menu :
1. Sum Of The Matrix
2. Difference Of The Matrix
3. Product Of The Matrix
4. Transpose Of The Matrix
Enter Your Choice : 4
Enter The Number Of Rows And Columns For Matrix : 3 3
Enter The Elements in the Matrix : 5 2 3 6 4 7 8 2 5
The Given Matrix is :
5 2 3
6 4 7
8 2 5
The Transpose Of The Matrix is :
5 6 8
2 4 2
3 7 5
Do you want to Continue ?(y/n): y
Menu :
1. Sum Of The Matrix
2. Difference Of The Matrix
3. Product Of The Matrix
4. Transpose Of The Matrix
Enter Your Choice : 3
Enter The Number Of Rows And Columns For Matrix 1 : 3 3
Enter The Elements in Matrix 1 : 2 4 1 3 6 9 8 5 4
Enter The Number Of Rows And Columns For Matrix 2 : 3 3
Enter The Elements in Matrix 2 : 1 2 4 5 3 2 6 1 2
The 1st Given Matrix is :

14
2 4 1
3 6 9
8 5 4
The 2nd Given Matrix is :
1 2 4
5 3 2
6 1 2
The Product Of The Two Matrices Are :
28 17 18
87 33 42
57 35 50
Do you want to Continue ?(y/n): n

Discussion :

This C program acts as a calculator for matrix operations, offering a menu-driven interface for users.
The program supports four main matrix operations: sum, difference, product, and transpose. Each
operation is structured within a function to enhance modularity.The program begins by prompting
the user to choose an operation from the menu. Depending on the selected operation, the user is
guided to input the necessary details, such as the number of rows and columns for the matrices
involved. The matrices are then filled with user-inputted elements.For the sum, difference, and
product operations, the program uses functions to perform the calculations and displays the resulting
matrices. Special conditions, like checking if matrices are compatible for multiplication, are
incorporated to ensure accurate operations.The transpose operation is executed separately, flipping
the rows and columns of a matrix. The result is displayed, revealing the transposed matrix.To enhance
user experience, the program includes a loop that allows users to perform multiple operations without
restarting. After each operation, the user is asked if they want to continue. In simpler terms, this
program is like a smart helper for matrix math. It provides a user-friendly menu to perform various
matrix operations, making it convenient for anyone dealing with matrices to quickly get the results
they need.

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

/*A Program in C Using Structure To Perform Addition And Subtraction Between


Two Complex Number Using Functions. */
#include <stdio.h>
// Structure Definition
struct Complex
{
int real;
int imag;
};

// Function Declaration
struct Complex addComplex(struct Complex num1, struct Complex num2);
struct Complex subtractComplex(struct Complex num1, struct Complex num2);
int main()
{
// Structure Declaration
struct Complex num1, num2, sum, difference;
// Input From The User
printf("Enter real and imaginary parts of the first complex number: ");
scanf("%d %d", &num1.real, &num1.imag);
printf("\nEnter real and imaginary parts of the second complex number: ");
scanf("%d %d", &num2.real, &num2.imag);
// Displaying The Given Complex Number
printf("\nThe First Given Complex Number is : %d + %di", num1.real,
num1.imag);
printf("\nThe Second Given Complex Number is : %d + %di", num2.real,
num2.imag);
// Performing Addition And Subtraction
sum = addComplex(num1, num2); // Function Call
difference = subtractComplex(num1, num2); // Function Call
// Displaying the results
printf("\nSum Of The Two Complex Number is : %d + %di", sum.real,
sum.imag);

16
printf("\nDifference Of The Two Complex Number is : %d + %di",
difference.real, difference.imag);
return 0;
}
// Function Definition
// Function To Add Two Complex Numbers
struct Complex addComplex(struct Complex num1, struct Complex num2)
{
struct Complex result;
result.real = num1.real + num2.real;
result.imag = num1.imag + num2.imag;
return result;
}

// Function To Subtract Two Complex Numbers


struct Complex subtractComplex(struct Complex num1, struct Complex num2)
{
struct Complex result;
result.real = num1.real - num2.real;
result.imag = num1.imag - num2.imag;
return result;
}

Output :

Enter real and imaginary parts of the first complex number: 8 9


Enter real and imaginary parts of the second complex number: 5 6
The First Given Complex Number is : 8 + 9i
The Second Given Complex Number is : 5 + 6i
Sum Of The Two Complex Number is : 13 + 15i
Difference Of The Two Complex Number is : 3 + 3i
Discussion :

This C program utilizes structures and functions to perform addition and subtraction between two complex
numbers. The program defines a structure named Complex to represent a complex number with real and
imaginary parts. Two functions, addComplex and subtractComplex, are declared and defined to handle the
addition and subtraction operations, respectively. In the main function, user input is obtained for two complex
numbers, and the program displays the given complex numbers. The defined functions are then called to
calculate the sum and difference of the complex numbers. Finally, the results are displayed. The program
provides a clear illustration of how structures and functions can be employed to organize and streamline
complex number computations in C.

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

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

#include <stdio.h>

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

// Function prototypes / Declaration


int calculateSum(struct Time t1, struct Time t2);
int displayTime(struct Time t);
int readTime(struct Time *t);

// Function to calculate the sum of two times


int calculateSum(struct Time t1, struct Time t2)
{
if (t1.minutes > 60 || t2.minutes > 60 || t1.hours > 24 || t2.hours > 24)
printf("\nYou have entered wrong time");
else
{
if ((t1.minutes + t2.minutes) < 60)
printf("\nSum of the times is: %d hours and %d minutes", t1.hours +
t2.hours, t1.minutes + t2.minutes);
else if ((t1.minutes + t2.minutes) >= 60)
{
int totalHours = t1.hours + t2.hours + (t1.minutes + t2.minutes) /
60;
int totalMinutes = (t1.minutes + t2.minutes) % 60;
printf("\nSum of the times is: %d hours and %d minutes",
totalHours, totalMinutes);
}
}
return 0;
}

// Function to display time


int displayTime(struct Time t)
{
if (t.minutes > 60 || t.hours > 24)
printf("\nYou have entered wrong time");

18
else
{
t.hours = t.hours + (t.minutes / 60);
t.minutes = t.minutes % 60;
printf("\nThe time is: %d hours and %d minutes", t.hours, t.minutes);
}
return 0;
}

// Function to read time


int readTime(struct Time *t)
{
printf("Enter the hour and minute: ");
scanf("%d%d", &(t->hours), &(t->minutes));
return 0;
}

// Main function
int main()
{
struct Time time1, time2;

// Read and display the first time


printf("Enter the details for the 1st time:\n");
readTime(&time1);
displayTime(time1);

// Read and display the second time


printf("\nEnter the details for the 2nd time:\n");
readTime(&time2);
displayTime(time2);

// Calculate and display the sum of times


calculateSum(time1, time2);

return 0;
}
Output :
Enter the details for the 1st time:
Enter the hour and minute: 4 23
The time is: 4 hours and 23 minutes
Enter the details for the 2nd time:
Enter the hour and minute: 6 33
The time is: 6 hours and 33 minutes
Sum of the times is: 10 hours and 56 minutes
Discussion :

This C program defines a structure called Time to represent time in terms of hours and minutes. It includes
functions for reading time, displaying time, and calculating the sum of two times passed as arguments. The
readTime function prompts the user to input the hour and minute values for a given time. The displayTime
function ensures that the entered time is within valid ranges and then displays it in a standardized format.The
calculateSum function takes two time structures, checks for valid time entries, and computes the sum of the
times. The main part of the program declares two Time structures, reads and displays user-input times, and
then calculates and displays the sum of these times. Overall, this program provides a basic framework for
working with time representations. It employs conditional checks to ensure the entered time values are valid
and handles the addition of hours and minutes appropriately when calculating the sum of two times.

Date : 22/11/2023

19
Q9. Design a structure Fraction which contains data members for numerator and denominator.
The program should add two fractions using function.

Source Code :

/* A Program in C To Design A Structure Fraction Which Contains Data Members


For
Numerator And Denominator.
The Program Should Add Two Fractions Using Function. */
#include <stdio.h>

// Structure Definition
struct Fraction
{
int num;
int denom;
};

// Function Declaration
int GCD(int x, int y);
struct Fraction Add(struct Fraction n, struct Fraction d);

int main()
{
// Structure Declaration
struct Fraction n1, n2, n3;
// Input From The User
printf("Enter The 1st Numerator And Denominator : ");
scanf("%d%d", &n1.num, &n1.denom);
printf("Enter The 2nd Numerator And Denominator : ");
scanf("%d%d", &n2.num, &n2.denom);
// Displaying The Given Fraction
printf("\nThe 1st Given Fraction is : %d / %d", n1.num, n1.denom);
printf("\nThe 2nd Given Fraction is : %d / %d", n2.num, n2.denom);
// To Add Two Fractions
n3 = Add(n1, n2); // Function Call
// Displaying The Result Of Fraction Addition
printf("\nThe Addition Of The Two Fractions Are : %d / %d", n3.num,
n3.denom);
return 0;
}
// Function Definition
// To Calculate The Value Of GCD
int GCD(int x, int y)
{
if (x % y == 0)
{
return y;
}
else
{
return GCD(y, (x % y));
}
}

// Function Definition
// To Find The Addition Of Two Fractions
struct Fraction Add(struct Fraction n, struct Fraction d)
{
struct Fraction Result;

20
int number;
// To Calculate The Value Of Fraction Addition
Result.num = (n.num * d.denom) + (d.num * n.denom);
Result.denom = n.denom * d.denom;
// Checking The Numbers From GCD Calculation
if (Result.num > Result.denom)
{
number = GCD(Result.num, Result.denom); // Function Call
}
else
{
number = GCD(Result.denom, Result.num); // Function Call
}
// To Find The Actual Answer Of Fraction Addition Betweem Two Numbers
Result.num = Result.num / number;
Result.denom = Result.denom / number;
return Result;
}
Output :

Enter The 1st Numerator And Denominator : 6 5

Enter The 2nd Numerator And Denominator : 2 3

The 1st Given Fraction is : 6 / 5

The 2nd Given Fraction is : 2 / 3

The Addition Of The Two Fractions Are : 28 / 15

Discussion :
This C program is designed to work with fractions using a structure named Fraction with members
for the numerator and denominator. The main function prompts the user to input two fractions,
displays the given fractions, adds them using a separate function named Add, and then displays the
result of the fraction addition. The Add function takes two Fraction structures, calculates the sum of
the fractions, and employs the concept of Greatest Common Divisor (GCD) to simplify the result. The
GCD function is defined to find the greatest common divisor between two numbers, which is then used
to simplify the numerator and denominator of the sum. This ensures that the result is presented in its
simplest form.Overall, the program shows how to organize the code neatly, making it easier to
understand and reuse the logic for adding fractions.

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

Source Code :

// C program to copy the contents of one file into another.

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

int main()
{
FILE *sourceFile, *destinationFile;
char sourceFilename[100], destFilename[100], c;

// Prompt user for the source filename


printf("Enter the source filename to open for reading \n");
scanf("%s", sourceFilename);

// Open the source file for reading


sourceFile = fopen(sourceFilename, "r");
if (sourceFile == NULL)
{
printf("Cannot open file %s \n", sourceFilename);
exit(0);
}

// Prompt user for the destination filename


printf("Enter the destination filename to open for writing \n");
scanf("%s", destFilename);

// Open the destination file for writing


destinationFile = fopen(destFilename, "w");
if (destinationFile == NULL)
{
printf("Cannot open file %s \n", destFilename);
exit(0);
}

// Read contents from the source file and copy to the destination file
c = fgetc(sourceFile);
while (c != EOF)
{
fputc(c, destinationFile);
c = fgetc(sourceFile);
}

// Notify user about successful copy


printf("\nContents copied to %s", destFilename);

// Close both files


fclose(sourceFile);
fclose(destinationFile);

return 0;
}

Output :

22
Enter the source filename to open for reading
a.txt
Enter the destination filename to open for writing
b.txt
Contents copied to b.txt

Discussion :

This C program is designed to copy the contents of one file into another, providing a basic file copying
functionality. It begins by prompting the user to input the source filename, then attempts to open the
source file for reading. If the source file opening fails, an error message is displayed, and the program
exits. The user is also prompted for the destination filename, and the program attempts to open the
destination file for writing. Similarly, if the destination file opening fails, an error message is
displayed, and the program exits. The program then uses a loop to read characters from the source
file and writes them to the destination file until the end of the source file (EOF) is reached. A
notification about the successful copy is displayed, and both files are closed.

23
Date : 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 :

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

#include <stdio.h>

int main()
{
// File Pointers
FILE *dataFile, *oddFile, *evenFile;

// Declaration
int totalNumbers, currentNumber, i;

// Input From The User


printf("Enter the total number of contents in the data file: ");
scanf("%d", &totalNumbers);

printf("Enter the contents of the data file (enter -1 to stop): ");


dataFile = fopen("DATA.txt", "w");
for (i = 0; i < totalNumbers; i++)
{
scanf("%d", &currentNumber);
if (currentNumber == -1)
{
break;
}
putw(currentNumber, dataFile);
}
fclose(dataFile);

// Opening The Files In Read & Write Mode


dataFile = fopen("DATA.txt", "r");
oddFile = fopen("ODD.txt", "w");
evenFile = fopen("EVEN.txt", "w");

// Read From The DATA File


while ((currentNumber = getw(dataFile)) != EOF)
{
if (currentNumber % 2 == 0)
{
putw(currentNumber, evenFile);
}
else
{
putw(currentNumber, oddFile);
}
}

// Closing The Files


fclose(dataFile);
fclose(oddFile);
fclose(evenFile);

24
// Opening The Files In Read Mode
oddFile = fopen("ODD.txt", "r");
evenFile = fopen("EVEN.txt", "r");

// Displaying The ODD File Contents


printf("\nThe Contents Of ODD File : \n");
while ((currentNumber = getw(oddFile)) != EOF)
{
printf("%5d", currentNumber);
}

// Displaying The EVEN File Contents


printf("\nThe Contents Of EVEN File : \n");
while ((currentNumber = getw(evenFile)) != EOF)
{
printf("%5d", currentNumber);
}

// Closing The Files


fclose(oddFile);
fclose(evenFile);
return 0;
}
Output :

Enter the total number of contents in the data file: 10

Enter the contents of the data file (enter -1 to stop): 2 4 5 8 6 4 7 9 6 -1

The Contents Of ODD File :

5 7 9

The Contents Of EVEN File :

2 4 8 6 4 6

Discussion :

This computer program does some tasks with numbers. It first asks you how many numbers you want
to enter, and then it asks you to type those numbers. It saves those numbers in a file called
"DATA.txt". After that, it separates the numbers into two groups: odd numbers and even numbers.
Odd numbers go into a file called "ODD.txt", and even numbers go into a file called "EVEN.txt".
Finally, it shows you the contents of these two new files.

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

Source Code :

// C Program To Swap Two Numbers Using Pointers.

#include <stdio.h>
// Function Declaration
void swap(int *, int *);
int main()
{
// Declaration
int n1, n2;

// Input From The User


printf("Enter The Two Numbers : ");
scanf("%d%d", &n1, &n2);

// Displaying The Given Number


printf("\nBefore Swapping : \nNumber 1 = %d And Number 2 = %d", n1, n2);
swap(&n1, &n2); // Function Call

// Displaying The Result Of Swapping


printf("\nAfter Swapping : \nNumber 1 = %d And Number 2 = %d", n1, n2);
return 0;
}
// Function Definition
// To Swap The Values
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output :
Enter The Two Numbers : 10 20
Before Swapping :
Number 1 = 10 And Number 2 = 20
After Swapping :
Number 1 = 20 And Number 2 = 10
Discussion :
The provided C program successfully swaps two numbers using pointers. In the main function, two integer
variables, n1 and n2, are declared to store user-inputted values. The program prompts the user to enter these
numbers, and the scanf function correctly uses the address-of operator to store the input values in the memory
locations of n1 and n2. The initial values are then displayed using printf statements.The program proceeds to
call the swap function, passing the addresses of n1 and n2 as arguments. The swap function, well-defined below
the main function, effectively exchanges the values stored at the given memory locations using pointer
references.After the swap function executes, the program displays the swapped values using printf statements
in the main function. This program illustrates how pointers can be employed for efficient value interchange in
C programming.

26
Date : 10/01/2024
Q13. Write a menu driven program to perform following operations on strings:
a. Show address of each character in string.
b. Concatenate two strings without using strcat function.
c. Concatenate two strings using strcat function.
d. Compare two strings.
e. Calculate length of the string (use pointers).
f. Convert all lowercase characters to uppercase.
g. Convert all uppercase characters to lowercase.
h. Calculate number of vowels.
i. Reverse the string.
Source Code :

/*A menu driven program to perform following operations on strings:


a. Show address of each character in string
b. Concatenate two strings without using strcat function.
c. Concatenate two strings using strcat function.
d. Compare two strings
e. Calculate length of the string (use pointers)
f. Convert all lowercase characters to uppercase
g. Convert all uppercase characters to lowercase
h. Calculate number of vowels
i. Reverse the string */

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_SIZE 100

// Function Declaration
void displayAddresses(char *str);
void concatWithoutStrcat(char *s1, char *s2);
void concatWithStrcat(char *s1, char *s2);
void compare(char *s1, char *s2);
void calcLength(char *s);
void converttoLowercase(char *s);
void converttoUppercase(char *s);
void countVowels(char *s);
void reverse(char *s);

int main() {
// Declaration
char s[MAX_SIZE], s1[MAX_SIZE], s2[MAX_SIZE], ch, choice;

// Menu
do {
printf("\nString Operations Menu: \n");
printf("a. Show Address Of Each Character In String\n");
printf("b. Concatenate Two Strings Without Using strcat Function.\n");
printf("c. Concatenate Two Strings Using strcat Function.\n");
printf("d. Compare Two Strings.\n");

27
printf("e. Calculate Length Of The String (Use Pointers).\n");
printf("f. Convert All Lowercase Characters To Uppercase.\n");
printf("g. Convert All Uppercase Characters To Lowercase.\n");
printf("h. Calculate Number Of Vowels.\n");
printf("i. Reverse The String Without Using strrev Function.\n");

// Input From The User


printf("\nEnter Your Choice: ");
scanf(" %c", &choice);
getchar();

switch (choice) {
case 'a':
printf("\nEnter The String: ");
gets(s);
displayAddresses(s);
break;

case 'b':
printf("\nEnter The First String: ");
gets(s1);
printf("\nEnter The Second String To Be Concatenated: ");
gets(s2);
concatWithoutStrcat(s1, s2);
break;

case 'c':
printf("\nEnter The First String: ");
gets(s1);
printf("\nEnter The Second String To Be Concatenated: ");
gets(s2);
concatWithStrcat(s1, s2);
break;

case 'd':
printf("\nEnter The First String: ");
gets(s1);
printf("\nEnter The Second String To Be Compared: ");
gets(s2);
compare(s1, s2);
break;

case 'e':
printf("\nEnter The String: ");
gets(s);
calcLength(s);
break;

case 'f':
printf("\nEnter The String To Convert To Uppercase: ");
gets(s);
converttoUppercase(s);
break;

case 'g':
printf("\nEnter The String To Convert To Lowercase: ");
gets(s);
converttoLowercase(s);
break;

case 'h':

28
printf("\nEnter The String To Count Vowels: ");
gets(s);
countVowels(s);
break;

case 'i':
printf("\nEnter The String To Be Reversed: ");
gets(s);
reverse(s);
break;

default:
printf("\nWrong Choice.");
}

printf("\nDo you want to continue? (y/n): ");


scanf(" %c", &ch);
getchar();
} while (ch == 'y' || ch == 'Y');

return 0;
}

// Function Definitions...
// Function to display the address of each character in the string
void displayAddresses(char *str) {
char *characterPointer;

printf("\nThe Address Of Each Character is: \n");


printf("Char Address\n");

for (characterPointer = str; *characterPointer != '\0'; characterPointer++)


{
printf("%c : %u", *characterPointer, characterPointer);
printf("\n");
}
}

// Function to concatenate two strings without using strcat function


void concatWithoutStrcat(char *s1, char *s2) {
int i, length1, length2;

length1 = strlen(s1);
length2 = strlen(s2);

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


s1[length1 + i] = s2[i];
}
s1[length1 + length2] = '\0';

printf("\nThe Concatenated String is: %s", s1);


}

// Function to concatenate two strings using strcat function


void concatWithStrcat(char *s1, char *s2) {
strcat(s1, s2);
printf("\nThe Concatenated String using strcat is: %s", s1);
}

// Function to compare two strings


void compare(char *s1, char *s2) {

29
if (strcmp(s1, s2) == 0) {
printf("\nThe Two Strings Are Equal.");
} else {
printf("\nThe Two Strings Are Not Equal.");
}
}

// Function to calculate the length of the string using pointers


void calcLength(char *s) {
char *characterPointer;
int length = 0;

for (characterPointer = s; *characterPointer != '\0'; characterPointer++) {


length++;
}
printf("\nThe Length Of The Given String is: %d", length);
}

// Function to convert all lowercase characters to uppercase


void converttoUppercase(char *s) {
char *characterPointer;

printf("\nThe Converted String To Uppercase: ");


for (characterPointer = s; *characterPointer != '\0'; characterPointer++) {
printf("%c", toupper(*characterPointer));
}
}

// Function to convert all uppercase characters to lowercase


void converttoLowercase(char *s) {
char *characterPointer;

printf("\nThe Converted String To Lowercase: ");


for (characterPointer = s; *characterPointer != '\0'; characterPointer++) {
printf("%c", tolower(*characterPointer));
}
}

// Function to count the number of vowels in the given string


void countVowels(char *s) {
char *characterPointer;
int count = 0;

for (characterPointer = s; *characterPointer != '\0'; characterPointer++) {


if (*characterPointer == 'A' || *characterPointer == 'a' ||
*characterPointer == 'E' || *characterPointer == 'e' || *characterPointer ==
'I' || *characterPointer == 'i' || *characterPointer == 'O' ||
*characterPointer == 'o' || *characterPointer == 'U' || *characterPointer ==
'u') {
count++;
}
}
printf("\nThe Total Number Of Vowels In The Given String is: %d", count);
}

// Function to reverse the given string


void reverse(char *s) {
int length;
char *pointerToOutput = s, *pointerToInput;

length = strlen(s);

30
printf("\nThe Reversed String is: ");
for (pointerToInput = s + length - 1; pointerToInput >= s;
pointerToInput--) {
pointerToOutput = pointerToInput;
printf("%c", *pointerToOutput);
}
}
Output :

String Operations Menu:

a. Show Address Of Each Character In String

b. Concatenate Two Strings Without Using strcat Function.

c. Concatenate Two Strings Using strcat Function.

d. Compare Two Strings.

e. Calculate Length Of The String (Use Pointers).

f. Convert All Lowercase Characters To Uppercase.

g. Convert All Uppercase Characters To Lowercase.

h. Calculate Number Of Vowels.

i. Reverse The String.

Enter Your Choice: b

Enter The First String: Abhay

Enter The Second String To Be Concatenated: Shaw

The Concatenated String is: Abhay Shaw

Do you want to continue? (y/n): y

String Operations Menu:

a. Show Address Of Each Character In String

b. Concatenate Two Strings Without Using strcat Function.

c. Concatenate Two Strings Using strcat Function.

d. Compare Two Strings.

e. Calculate Length Of The String (Use Pointers).

f. Convert All Lowercase Characters To Uppercase.

g. Convert All Uppercase Characters To Lowercase.

h. Calculate Number Of Vowels.

i. Reverse The String.

31
Enter Your Choice: h

Enter The String To Count Vowels: Abhay Shaw

The Total Number Of Vowels In The Given String is: 3

Do you want to continue? (y/n): n

Discussion :
This C program is like a versatile tool for handling words, known as strings. It provides a menu-
driven interface where you can choose from different operations to manipulate strings. These
operations include displaying the memory addresses of each letter, combining two strings, comparing
them, calculating string length, converting cases, counting vowels, and reversing the string. To use the
program, you simply select the operation you want to perform from the menu. For instance, if you're
curious about where each letter is stored in the computer's memory, the program will show you the
unique addresses. If you decide to combine two words, it gives you two options: one without any
special function and another using the strcat function. The program continues to ask for your input
until you indicate you're done.

32

You might also like