Assignment (SEM - 1) (Abhay)
Assignment (SEM - 1) (Abhay)
Q1. Write a program to print the sum and product of digits of an integer.
Source Code :
// Initialization
sum = 0;
pro = 1;
Output :
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 :
#include <stdio.h>
int main()
{
// Declaration
int i, j, num, c;
// Initialization
c = 0;
2
printf("\nThe Given Number is Not a Prime Number");
Output :
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;
// Array Declaration
int arr[n];
4
// Displaying The Maximum Element
printf("\nMaximum Element Of An Array is : %d", max);
return 0;
}
Output :
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 :
#include <stdio.h>
int main()
{
// Declaration
int arr[50], n, i, ele;
6
}
}
printf("\nElement is Not Found In The Array");
return 0;
}
Output :
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 :
#include <stdio.h>
int main()
{
// Declaration
int A[100], B[100], C[200], i, j, n1, n2, ind = 0;
// 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];
}
}
return 0;
}
Output :
Merged Array: 1 4 6 8 2 3 9 7 4 2 6 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 :
#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");
10
printf("\nEnter The Elements in Matrix 2 : ");
input(B, r2, c2);
11
// For Matrix Transpose
case 4:
printf("\nEnter The Number Of Rows And Columns For Matrix : ");
scanf("%d%d", &r1, &c1);
default:
printf("\nWrong Choice.");
}
printf("\nDo you want to Continue ?(y/n): ");
scanf(" %c", &ch);
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 :
// 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;
}
Output :
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;
};
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;
}
// Main function
int main()
{
struct Time 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 :
// 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 :
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 :
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *sourceFile, *destinationFile;
char sourceFilename[100], destFilename[100], c;
// Read contents from the source file and copy to the destination file
c = fgetc(sourceFile);
while (c != EOF)
{
fputc(c, destinationFile);
c = fgetc(sourceFile);
}
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 :
#include <stdio.h>
int main()
{
// File Pointers
FILE *dataFile, *oddFile, *evenFile;
// Declaration
int totalNumbers, currentNumber, i;
24
// Opening The Files In Read Mode
oddFile = fopen("ODD.txt", "r");
evenFile = fopen("EVEN.txt", "r");
5 7 9
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 :
#include <stdio.h>
// Function Declaration
void swap(int *, int *);
int main()
{
// Declaration
int n1, n2;
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 :
#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");
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.");
}
return 0;
}
// Function Definitions...
// Function to display the address of each character in the string
void displayAddresses(char *str) {
char *characterPointer;
length1 = strlen(s1);
length2 = strlen(s2);
29
if (strcmp(s1, s2) == 0) {
printf("\nThe Two Strings Are Equal.");
} else {
printf("\nThe Two Strings Are Not Equal.");
}
}
length = strlen(s);
30
printf("\nThe Reversed String is: ");
for (pointerToInput = s + length - 1; pointerToInput >= s;
pointerToInput--) {
pointerToOutput = pointerToInput;
printf("%c", *pointerToOutput);
}
}
Output :
31
Enter Your Choice: h
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