C Program Assingment - BPSA24
C Program Assingment - BPSA24
int main() {
int num, digit, sum = 0, product = 1;
scanf("%d", &num);
return 0;
• Output:
• Enter an integer: 54
• Sum of digits: 9
• Product of digits: 20
• The program provides a simple and efficient way to calculate the sum and product of
digits for a given integer.
1
• It demonstrates the use of loops and basic arithmetic operations in C programming.
• The code is concise, making it suitable for educational purposes and for those learning
the fundamentals of C programming.
2
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.
#include<stdio.h>
int main ()
int n,count=0,i;
scanf("%d",&n);
for(i=1;i<=n;i++)
if(n%i==0)
count++;
if(count==2)
printf("prime number");
else
Output:
• The program demonstrates the use of a function for prime number checking.
• It showcases a common algorithm to determine whether a number is prime.
• The program provides a practical example of using functions for code modularity and
efficiency.
• Additionally, it generates and displays prime numbers less than 100, offering a useful
application of the prime-checking function.
int main() {
int i, j;
if (i % j == 0) {
break;
if (i == j) {
return 0;
}
4
Output:
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,
The program uses two nested loops, an outer loop iterating from 2 to 100 and an inner loop
iterating from 2 to the current value of the outer loop. For each value of the outer loop, the
inner loop iterates through all integers from 2 to the current value of the outer loop, checking
if the current value of the outer loop is divisible by any of the integers. If the current value of
the outer loop is divisible by any of the integers, it is not a prime number, and the inner loop
breaks. If the current value of the outer loop is not divisible by any of the integers, it is a
prime number, and the program prints it.
5
Q3. Write a program to perform the following actions -
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[10], i;
printf("Enter any 10 array elements: ");
{
if(arr[i]%2==0)
{
printf("%d ", arr[i]);
}
}
getch();
return 0;
6
Output:
Enter any 10 array element: 1
2
3
4
5
6
7
8
9
10
All even array element are:
2 4 6 8 10
• 1. Array Initialization: The program begins by defining an array of named numbers
containing some sample values.
• 2. Array Size Calculation: The size variable is calculated to determine the number of
elements in the array. This is important for iterating through the array.
• 3. Looping Through the Array: Therefor loop is used iterate through each element of
the array.
• 4. Checking for Even Numbers: Inside the loop, each element is checked to see if it's
an even number using the modulo operator (%). If the remainder is 0, then the number
is even.
• 5. Printing Even Numbers: When an even number is found, it is printed to the console.
• 6. Program Output: The final output will be the even-valued numbers in the array.
{
int arr[10], i, odd;
7
printf("Enter any 10 array elements: ");
for(i=0; i<10; i++)
scanf("%d", &arr[i]);
printf("\nAll odd Array elements are:\n");
{
if(arr[i]%2 !=0)
{
printf("%d ", arr[i]);
odd++;
}
}
getch();
return 0;
}
Output:
Enter any 10 array elements: 1
2
3
4
5
6
7
8
9
10
All odd array elements are:
13579
8
• 1. Array Initialization: Like the previous program, it starts by defining an array of
named numbers containing sample values.
• 2. Array Size Calculation: The size variable is calculated to determine the number of
elements in the array.
• 3. Looping Through the Array: Therefor loop is used iterate through each element of
the array.
• 4. Checking for Odd Numbers: Inside the loop, each element is checked to see if it's
an odd number using the modulo operator (%). If the remainder is not 0, then the
number is odd.
• 5. Printing Odd Numbers: When an odd number is found, it is printed to the console.
• 6. Program Output: The final output will be the odd-valued numbers in the array.
#include <stdio.h>
#include <conio.h>
int main()
{
int a[100],i,n,min,max;
scanf("%d",&n);
9
scanf("%d",&a[i]);
}
min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
return 0;
}
Output:
2
43
0
-3
Minimum of an array: -3
Maximum of an array: 35
• 1) Read the entered array size and store that value into the variable n.
10
• 2) Read the entered elements using scanf and store the entered array elements into the
array using for loop for(i=0;i<n;i++).
• 3) Initialize min, max values with the 1st element of the array.
• 4) Compare min, max values with a[i],
Q4. Write a program to search for a element from a given array. If the
element is found, then print “found” otherwise print “not found” .
#include <stdio.h>
#include <conio.h>
int main()
{
int arr[10],i,n,ele;
11
if(arr[i]==ele)
{
printf("%d found at position %d", ele, i+1);
return 0;
}
}
printf("Element not found");
}
Output:
12
Q5. Write a program to merge two arrays and remove the duplicates.
Ans Source code:
#include <stdio.h>
13
}
// If not a duplicate, add to mergedArr
if (!isDuplicate) {
mergedArr[k] = arr2[i];
k++;
}
}
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
14
Merging Arrays:
• The program uses a simple approach to merge two arrays. Elements from the first
array (arr1) are copied to the merged array (mergedArr), and then elements from the
second array (arr2) are added if they are not duplicates.
Duplicate Removal:
• The program checks for duplicates by comparing elements from the second array
(arr2) with elements in the first array (arr1). If an element is not found in arr1, it is
considered unique, and it is added to the merged array.
• The time complexity of the program is O(m * n), where m and n are the sizes of the
two arrays. This is because, for each element in arr2, it iterates through all elements in
arr1 to check for duplicates.
Array Manipulation:
• The program demonstrates basic array manipulation and how to use functions in C to
handle array operations.
Adjustments:
• Users can adjust the sample arrays in the main function to test the program with
different inputs.
• This program provides a starting point for merging arrays and removing duplicates in
a simple manner, and it can be extended or optimized based on specific requirements
and constraints.
15
Q6. Write 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 to input a matrix
}
}
}
// Function to display a matrix
16
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
// Function to compute the sum of two matrices
void matrixSum(int matA[10][10], int matB[10][10], int result[10][10], int rows, int cols) {
for (int i = 0; i < rows; i++)
}
// Function to compute the difference of two matrices
void matrixDifference(int matA[10][10], int matB[10][10], int result[10][10], int rows, int
cols) {
void matrixProduct(int matA[10][10], int matB[10][10], int result[10][10], int rowsA, int
colsA, int colsB) {
result[i][j] = 0;
for (int k = 0; k < colsA; k++)
17
// Function to compute the transpose of a matrix
void matrixTranspose(int matrix[10][10], int result[10][10], int rows, int cols) {
result[j][i] = matrix[i][j];
}
int main() {
int choice;
// Input matrix A
// Input matrix B
printf("Enter the number of rows and columns for matrix B:\n");
scanf("%d", &choice);
switch (choice) {
case 1:
18
if (rowsA == rowsB && colsA == colsB) {
matrixSum(matA, matB, result, rowsA, colsA);
break;
case 2:
break;
case 3:
if (colsA == rowsB) {
matrixProduct(matA, matB, result, rowsA, colsA, colsB);
break;
case 4:
break;
default:
19
printf("Invalid choice.\n");
}
return 0;
}
Output:
Enter the number of rows and columns for matrix A:
22
Enter the elements of matrix A (2x2):
12
34
Matrix A:
1 2
3 4
Enter the number of rows and columns for matrix B:
22
Enter the elements of matrix B (2x2):
56
78
Matrix B:
5 6
7 8
2. Difference
3. Product
4. Transpose
Enter your choice (1-4): 3
20
19 22
43 50
Matrix Operations:
• The program allows the user to perform various matrix operations, including sum,
difference, product, and transpose.
Menu-Driven Interface:
The user interacts with the program through a menu-driven interface, choosing the
desired matrix operation by entering a corresponding number (1-4).
Matrix Input:
• The user inputs two matrices (matrix A and matrix B) along with their dimensions.
Matrix Operations Functions:
• The program defines separate functions (input Matrix, display Matrix, matrix Sum,
matrix Difference, matrix Product, and matrix Transpose) for different aspects of
matrix manipulation.
Dimension Compatibility Checks:
• Before performing certain operations (sum, difference, and product), the program
checks whether the dimensions of the matrices allow the operation to be carried out. If
not, an error message is displayed.
Matrix Display:
• The program displays the input matrices and the result matrix using the display
Matrix function.
Switch Case Implementation:
• The menu-driven operations are implemented using a switch statement, which
evaluates the user's choice and executes the corresponding operation.
21
Q.7 Write a program in C using structure to perform addition and
subtraction between two complex number using functions.
#include <stdio.h>
struct Complex {
float real;
float imag;
};
22
result.real = num1.real + num2.real;
result.imag = num1.imag + num2.imag;
return result;
}
int main() {
struct Complex num1, num2, sum, difference;
printf("Enter the real and imaginary parts of the first complex number:\n");
scanf("%f %f", &num1.real, &num1.imag);
// Perform addition
sum = addComplex(num1, num2);
// Perform subtraction
difference = subtractComplex(num1, num2);
23
// Display the result of addition
printf("Sum: %.2f + %.2fi\n", sum.real, sum.imag);
return 0;
}
Outout:
Enter the real and imaginary parts of the first complex number:
4.1 6.2
Enter the real and imaginary parts of the second complex number:
2.6 3.6
• Structures for Abstraction: The use of a structure for complex numbers provides a
convenient way to group related data (real and imaginary parts) into a single entity.
This enhances code readability and abstraction.
• Functions for Modularity: The program defines separate functions for addition and
subtraction, promoting modularity and code organization. Each function encapsulates
a specific operation.
• User Interaction: The program interacts with the user by prompting for input, making
it user-friendly. It ensures that the user provides the necessary information for complex
numbers.
• Arithmetic Operations: The program demonstrates basic arithmetic operations on
complex numbers. Addition and subtraction are commonly used operations in complex
number manipulation.
• Precision in Display: The results are displayed with a precision of two decimal places
(%.2f), providing a clean and readable output.
• Potential Extensions: The program can be extended to include more complex number
operations, such as multiplication and division, by adding corresponding
24
• This program provides a clear example of structuring code for complex number
operations, demonstrating the use of structures and functions in C for better
organization and readability.
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
Ans Source code:
#include <stdio.h>
int hours;
int minutes;
};
25
void readTime(struct Time *t) {
printf("Enter hours: ");
scanf("%d", &(t->hours));
printf("Enter minutes: ");
scanf("%d", &(t->minutes));
}
}
// Function to get the sum of two times
return result;
}
int main() {
struct Time time1, time2, sum;
readTime(&time2);
printf("\nTime 1: ");
displayTime(time1);
26
printf("Time 2: ");
displayTime(time2);
return 0;
}
Output:
Enter details for time 1:
Enter hours: 4
Enter minutes: 30
Enter minutes: 40
Time 1: Time: 04:30
• We defined a structure named Time with two members (hours and minutes) to
encapsulate the information related to time.
• User Interaction Functions:
• readTime: This function takes a pointer to a Time structure as an argument and reads
user input for hours and minutes. It stores the input in the provided structure.
• displayTime: This function takes a Time structure as an argument and displays the time
in HH:MM format.
• Time Addition Function:
27
• addTimes: This function takes two Time structures as arguments and calculates their
sum. It considers the carryover from minutes to hours when needed and returns the
result as a new Time structure.
• Main Function: we create instances of the Time structure (time1, time2, and sum).
• User input is obtained for two different times using the readTime function.
• The displayTime function is used to show the entered times.
• The addTimes function is called to find the sum of the entered times, and the result is
displayed using displayTime.
#include <stdio.h>
28
// Structure to represent a fraction
struct Fraction {
int numerator;
int denominator;
};
// Function to add two fractions
// Perform addition
result.numerator = (frac1.numerator * frac2.denominator) + (frac2.numerator *
frac1.denominator);
return result;
}
}
int main() {
29
// Input for the second fraction
printf("Enter the numerator and denominator of the second fraction:\n");
// Perform addition
sum = addFractions(fraction1, fraction2);
printf("Sum of ");
displayFraction(fraction1);
printf(" is ");
displayFraction(sum);
return 0;
}
Output:
Enter the numerator and denominator of the first fraction:
45
Enter the numerator and denominator of the second fraction:
13
Q.10 Write a program to copy the contents of one file into another.
Ans Source code:
#include <stdio.h>
int main() {
FILE *sourceFile, *destinationFile;
30
char ch;
// Open the source file in read mode
}
// Open the destination file in write mode
return 2;
}
fputc(ch, destinationFile);
}
return 0;
}
Output:
• File Copying: The fgetc function is used to read characters from the source file one at
a time.
31
• The fputc function is used to write each character to the destination file.
• End-of-File (EOF) Check: The program uses the EOF (End-of-File) marker to
determine when it has reached the end of the source file.
• File Closure: After copying is complete, the program closes both the source and
destination files using fclose.
• Overall, this program provides a foundational understanding of file handling in C and
the basic process of copying file contents.
32
main()
{
FILE *f1, *f2, *f3;
int number, i;
printf("Contents of DATA file\n\n");
f1 = fopen("DATA", "w"); /* Create DATA file */
for(i = 1; i <= 30; i++)
{
scanf("%d", &number);
if(number == -1) break;
putw(number,f1);
}
fclose(f1);
f1 = fopen("DATA", "r");
f2 = fopen("ODD", "w");
f3 = fopen("EVEN", "w");
f2 = fopen("ODD","r");
f3 = fopen("EVEN", "r");
printf("\n\nContents of ODD file\n\n");
33
while((number = getw(f2)) != EOF)
printf("%4d", number);
printf("\n\nContents of EVEN file\n\n");
Output:
Contents of DATA file
1
2
3
4
5
-1
1 3 5
2 4
34
• File Closing and Reopening:
The program closes the "DATA," "ODD," and "EVEN" files after writing and categorizing.
It then reopens the "ODD" and "EVEN" files in read mode for printing their contents.
• Printing Contents:
The program prints the contents of the "ODD" file, displaying odd numbers.
It also prints the contents of the "EVEN" file, displaying even numbers.
File Formatting:
%4d is used in the printf statements to format the output, ensuring each number is displayed
with at least four characters.
• End-of-File Handling:
The program uses EOF as a sentinel value while reading from files to determine the end of the
file.
35
// Function to swap two numbers using pointers
void swapNumbers(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1, num2;
return 0;
}
Output:
Enter the first number: 4
Enter the second number: 10
Original numbers:4, 10
Swapped numbers: 10, 4
• The program aims to swap the values of two numbers using pointers.
36
• Users input two numbers, num1 and num2.
• The swapNumbers function is employed, taking pointers as parameters to perform the
swap. Pointers allow the program to modify the original variables indirectly.
• The program shows the original and swapped values of the numbers.
• The program is kept concise, emphasizing the essential concept of using pointers for
swapping.
37
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<ctype.h>
#include<string.h>
void showAddress(const char *str);
void concatenateWithoutStrcat(char *str1, const char *str2);
void concatenateWithStrcat(char *str1, const char *str2);
int compareStrings(const char *str1, const char *str2);
int calculateLength(const char *str);
void convertToLowercase(char *str);
void convertToUppercase(char *str);
int countVowels(const char *str);
void reverseString(char *str);
int main() {
char str1[100], str2[100];
int choice;
do {
printf("\nString Operations Menu:\n");
printf("1. Show address of 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 (use pointers)\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");
38
printf("9. Reverse the string\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 0:
printf("Exiting the program. Goodbye!\n");
break;
case 1:
printf("Enter a string: ");
scanf("%s", str1);
showAddress(str1);
break;
case 2:
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
concatenateWithoutStrcat(str1, str2);
printf("Concatenated string: %s\n", str1);
break;
case 3:
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
concatenateWithStrcat(str1, str2);
printf("Concatenated string: %s\n", str1);
break;
case 4:
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
39
if (compareStrings(str1, str2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
break;
case 5:
printf("Enter a string: ");
scanf("%s", str1);
printf("Length of the string: %d\n", calculateLength(str1));
break;
case 6:
printf("Enter a string: ");
scanf("%s", str1);
convertToLowercase(str1);
printf("String in lowercase: %s\n", str1);
break;
case 7:
printf("Enter a string: ");
scanf("%s", str1);
convertToUppercase(str1);
printf("String in uppercase: %s\n", str1);
break;
case 8:
printf("Enter a string: ");
scanf("%s", str1);
printf("Number of vowels: %d\n", countVowels(str1));
break;
case 9:
printf("Enter a string: ");
scanf("%s", str1);
reverseString(str1);
printf("Reversed string: %s\n", str1);
break;
40
default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 0);
return 0;
}
void showAddress(const char *str) {
printf("Address of each character in the string:\n");
while (*str != '\0') {
printf("%c: %p\n", *str, (void *)str);
str++;
}
}
void concatenateWithoutStrcat(char *str1, const char *str2) {
while (*str1 != '\0') {
str1++;
}
while (*str2 != '\0') {
*str1 = *str2;
str1++;
str2++;
}
*str1 = '\0';
}
void concatenateWithStrcat(char *str1, const char *str2) {
strcat(str1, str2);
}
int compareStrings(const char *str1, const char *str2) {
while (*str1 != '\0' && *str2 != '\0' && *str1 == *str2) {
str1++;
str2++;
}
return *str1 - *str2;
}
41
int calculateLength(const char *str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
void convertToLowercase(char *str) {
while (*str != '\0') {
*str = tolower(*str);
str++;
}
}
void convertToUppercase(char *str) {
while (*str != '\0') {
*str = toupper(*str);
str++;
}
}
int countVowels(const char *str) {
int count = 0;
while (*str != '\0') {
char ch = tolower(*str);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
str++;
}
return count;
void reverseString(char *str) {
char *start = str;
char *end = str + calculateLength(str) - 1;
while (start < end) {
42
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
Output:
Sting operation menu:
1. Show addressn of each character in sting
2. Concatenate two strings without using strcat functic
3. Concatenate two strings using strcat function
4. Compare two strings
5. Calculate length of the string (use pointers)
6. Convert all lowercase characters to uppercase
7. Convert all uppercase characters to lowercase
8. Calculate number of vowels
9. Reverse the string
Exit
Output:
Sting operation menu:
1. Show addressn of each character in sting
2. Concatenate two strings without using strcat functic
3. Concatenate two strings using strcat function
4. Compare two strings
5. Calculate length of the string (use pointers)
6. Convert all lowercase characters to uppercase
7. Convert all uppercase characters to lowercase
43
8. Calculate number of vowels
9. Reverse the string
Exit
Enter your choice: 8
Enter a string: Suraj Shaw
No. of vowels: 3
____________________________
REMARKS AND SIGNATURE
44
45