0% found this document useful (0 votes)
24 views45 pages

C Program Assingment - BPSA24

C programming assignment 2024 sem 1

Uploaded by

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

C Program Assingment - BPSA24

C programming assignment 2024 sem 1

Uploaded by

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

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

Ans Source code:


#include <stdio.h>

int main() {
int num, digit, sum = 0, product = 1;

// Input: Get an integer from the user


printf("Enter an integer: ");

scanf("%d", &num);

// Calculate sum and product of digits


while (num != 0) {

digit = num % 10; // Extract the last digit


sum += digit; // Add digit to sum

product *= digit; // Multiply digit to product


num /= 10; // Remove the last digit

// Output: Print the sum and product of digits


printf("Sum of digits: %d\n", sum);

printf("Product of digits: %d\n", product);

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.

Ans Source code:

#include<stdio.h>

int main ()

// input 7 is a prime number

int n,count=0,i;

printf("enterr any number: ");

scanf("%d",&n);

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

if(n%i==0)

count++;

if(count==2)

printf("prime number");

else

printf("not prime number");

Output:

enter any number: 47


3
Prime number

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

For generate prime number less then 100

int main() {

int i, j;

printf("Prime numbers between 1 and 100 are: \n");

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

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

if (i % j == 0) {

break;

if (i == j) {

printf("%d, ", i);

return 0;

}
4
Output:

Prime no. 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,

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 -

i) print the even valued number from an array.


ii) print the odd valued number from an array.
iii) print the maximum and minimum element of array.

i) print the even valued number from an array.


Ans Source code:

#include<stdio.h>

#include<conio.h>
int main()
{

int arr[10], i;
printf("Enter any 10 array elements: ");

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


scanf("%d", &arr[i]);

printf("\nAll Even Array elements are:\n");


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

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

ii) print the odd valued number from an array.


Ans:
#include<stdio.h>
int main()

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

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

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

iii) print the maximum and minimum element of array.

Ans Source code:

#include <stdio.h>

#include <conio.h>

int main()

{
int a[100],i,n,min,max;

printf("Enter size of the array : ");

scanf("%d",&n);

printf("Enter elements in array : ");


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

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

printf("minimum of array is : %d",min);


printf("\nmaximum of array is : %d",max);

return 0;
}

Output:

Enter size of the array: 5


Enter elements in array: 1

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

Ans source code:

#include <stdio.h>
#include <conio.h>

int main()
{
int arr[10],i,n,ele;

printf("Enter array size: ");


scanf("%d", &n);
printf("Enter array elements: ");
for(i=0; i<n; i++)
{
scanf("%d",&arr[i]);
}
printf("Enter element to search: ");
scanf("%d", &ele);

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


{

11
if(arr[i]==ele)
{
printf("%d found at position %d", ele, i+1);
return 0;
}

}
printf("Element not found");
}

Output:

Enter array size: 5


Enter array elements: 45 37 69 84 61
Enter element to search: 69
69 found at position 3
• 1) Read the array size and store that value into the variable n.
• 2) Read the entered elements and store those elements into an array a[] using scanf
statement and the for loop. scanf(“%d”,&a[i]) indicates scanf statement reads the
entered element and assigned that element to a[i].
• 3) Read the key which we want to search in an array.
• 4) Compare the key with each element of the array as a[i]==key and print element
found, if the key matches with any element of the array otherwise print element not
found.

12
Q5. Write a program to merge two arrays and remove the duplicates.
Ans Source code:
#include <stdio.h>

// Function to merge and remove duplicates from two arrays


void mergeAndRemoveDuplicates(int arr1[], int size1, int arr2[], int size2, int
mergedArr[], int *mergedSize) {
// Merge the arrays
int i, j, k;
for (i = 0; i < size1; i++) {
mergedArr[i] = arr1[i];
}

k = size1; // Start merging from the end of arr1


for (i = 0; i < size2; i++) {
int isDuplicate = 0;

// Check for duplicates


for (j = 0; j < size1; j++) {
if (arr2[i] == arr1[j]) {
isDuplicate = 1;
break;
}

13
}
// If not a duplicate, add to mergedArr
if (!isDuplicate) {
mergedArr[k] = arr2[i];
k++;
}
}

*mergedSize = k; // Update the merged size


}

int main() {
int arr1[] = {1, 2, 3, 4, 5};
int size1 = sizeof(arr1) / sizeof(arr1[0]);

int arr2[] = {3, 4, 5, 6, 7};


int size2 = sizeof(arr2) / sizeof(arr2[0]);

int mergedArr[size1 + size2];


int mergedSize;

// Call the mergeAndRemoveDuplicates function


mergeAndRemoveDuplicates(arr1, size1, arr2, size2, mergedArr, &mergedSize);

// Print the merged array without duplicates


printf("Merged Array without Duplicates: ");
for (int i = 0; i < mergedSize; i++) {
printf("%d ", mergedArr[i]);
}
return 0;
}
Output:
Merged array without duplicates: 1 2 3 4 5 6 7

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.

Ans Source code:

#include <stdio.h>
// Function to input a matrix

void inputMatrix(int matrix[10][10], int rows, int cols) {


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

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


for (int j = 0; j < cols; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);

}
}

}
// Function to display a matrix

void displayMatrix(int matrix[10][10], int rows, int cols) {


printf("Matrix:\n");

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

for (int j = 0; j < cols; j++)


result[i][j] = matA[i][j] + matB[i][j];

}
// 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) {

for (int i = 0; i < rows; i++)


for (int j = 0; j < cols; j++)

result[i][j] = matA[i][j] - matB[i][j];


}
// Function to compute the product of two matrices

void matrixProduct(int matA[10][10], int matB[10][10], int result[10][10], int rowsA, int
colsA, int colsB) {

for (int i = 0; i < rowsA; i++)


for (int j = 0; j < colsB; j++) {

result[i][j] = 0;
for (int k = 0; k < colsA; k++)

result[i][j] += matA[i][k] * matB[k][j];


}

17
// Function to compute the transpose of a matrix
void matrixTranspose(int matrix[10][10], int result[10][10], int rows, int cols) {

for (int i = 0; i < rows; i++)


for (int j = 0; j < cols; j++)

result[j][i] = matrix[i][j];
}

int main() {
int choice;

int matA[10][10], matB[10][10], result[10][10];


int rowsA, colsA, rowsB, colsB;

// Input matrix A

printf("Enter the number of rows and columns for matrix A:\n");


scanf("%d %d", &rowsA, &colsA);

inputMatrix(matA, rowsA, colsA);

// Input matrix B
printf("Enter the number of rows and columns for matrix B:\n");

scanf("%d %d", &rowsB, &colsB);


inputMatrix(matB, rowsB, colsB);

// Menu for matrix operations


printf("Choose the matrix operation:\n");

printf("1. Sum\n2. Difference\n3. Product\n4. Transpose\n");


printf("Enter your choice (1-4): ");

scanf("%d", &choice);

switch (choice) {
case 1:

18
if (rowsA == rowsB && colsA == colsB) {
matrixSum(matA, matB, result, rowsA, colsA);

displayMatrix(result, rowsA, colsA);


} else {

printf("Matrices cannot be added. Dimensions are not compatible.\n");


}

break;
case 2:

if (rowsA == rowsB && colsA == colsB) {


matrixDifference(matA, matB, result, rowsA, colsA);

displayMatrix(result, rowsA, colsA);


} else {

printf("Matrices cannot be subtracted. Dimensions are not compatible.\n");


}

break;
case 3:

if (colsA == rowsB) {
matrixProduct(matA, matB, result, rowsA, colsA, colsB);

displayMatrix(result, rowsA, colsB);


} else {
printf("Matrices cannot be multiplied. Number of columns in matrix A should be
equal to the number of rows in matrix B.\n");
}

break;
case 4:

matrixTranspose(matA, result, rowsA, colsA);


displayMatrix(result, colsA, rowsA);

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

Choose the matrix operation:


1. Sum

2. Difference
3. Product

4. Transpose
Enter your choice (1-4): 3

Product of the matrices:

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.

Ans Source code:

#include <stdio.h>

// Define a structure to represent complex numbers

struct Complex {
float real;
float imag;
};

// Function to add two complex numbers


struct Complex addComplex(struct Complex num1, struct Complex num2) {

struct Complex result;

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

int main() {
struct Complex num1, num2, sum, difference;

// Input for the first complex number

printf("Enter the real and imaginary parts of the first complex number:\n");
scanf("%f %f", &num1.real, &num1.imag);

// Input for the second complex number


printf("Enter the real and imaginary parts of the second complex number:\n");
scanf("%f %f", &num2.real, &num2.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);

// Display the result of subtraction

printf("Difference: %.2f + %.2fi\n", difference.real, difference.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

Sum: 6.70 + 9.80i


Difference: 1.50 + 2.60i

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

// Structure to represent time


struct Time {

int hours;
int minutes;
};

// Function to read time

25
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(struct Time t) {


printf("Time: %02d:%02d\n", t.hours, t.minutes);

}
// Function to get the sum of two times

struct Time addTimes(struct Time time1, struct Time time2) {


struct Time result;

result.minutes = (time1.minutes + time2.minutes) % 60;


result.hours = time1.hours + time2.hours + (time1.minutes + time2.minutes) / 60;

return result;
}

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

printf("Enter details for time 1:\n");


readTime(&time1);

printf("\nEnter details for time 2:\n");

readTime(&time2);

printf("\nTime 1: ");
displayTime(time1);

26
printf("Time 2: ");

displayTime(time2);

sum = addTimes(time1, time2);

printf("\nSum of Time 1 and Time 2: ");


displayTime(sum);

return 0;
}

Output:
Enter details for time 1:

Enter hours: 4
Enter minutes: 30

Enter details for time 2:


Enter hours: 1

Enter minutes: 40
Time 1: Time: 04:30

Time 2: Time: 01:40

Sum of Time 1 and Time 2: Time: 06:10


Structure Definition:

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

Q.9 Design a structure Fraction which contains data members for


numerator and denominator. The program should add two fractions using
function.
Ans Source code:

#include <stdio.h>

28
// Structure to represent a fraction
struct Fraction {

int numerator;
int denominator;

};
// Function to add two fractions

struct Fraction addFractions(struct Fraction frac1, struct Fraction frac2) {


struct Fraction result;

// Find a common denominator

result.denominator = frac1.denominator * frac2.denominator;

// Perform addition
result.numerator = (frac1.numerator * frac2.denominator) + (frac2.numerator *
frac1.denominator);

return result;
}

// Function to display a fraction


void displayFraction(struct Fraction frac) {
printf("%d/%d", frac.numerator, frac.denominator);

}
int main() {

struct Fraction fraction1, fraction2, sum;

// Input for the first fraction


printf("Enter the numerator and denominator of the first fraction:\n");

scanf("%d %d", &fraction1.numerator, &fraction1.denominator);

29
// Input for the second fraction
printf("Enter the numerator and denominator of the second fraction:\n");

scanf("%d %d", &fraction2.numerator, &fraction2.denominator);

// Perform addition
sum = addFractions(fraction1, fraction2);

// Display the result

printf("Sum of ");
displayFraction(fraction1);

printf(" and ");


displayFraction(fraction2);

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

Sum of 4/5 and 1/3 is 17/15


The C program employs a Fraction structure to model fractions, featuring functions for reading,
adding, and displaying fractions. The code streamlines the addition process by directly
computing a common denominator in the addFractions function

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

sourceFile = fopen("source.txt", "r");


if (sourceFile == NULL) {

perror("Error opening source file");


return 1;

}
// Open the destination file in write mode

destinationFile = fopen("destination.txt", "w");


if (destinationFile == NULL) {

perror("Error opening destination file");


fclose(sourceFile);

return 2;
}

// Copy contents from source to destination


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

fputc(ch, destinationFile);
}

// Close the files


fclose(sourceFile);
fclose(destinationFile);

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

return 0;

}
Output:

File copied successfully.

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

Q.11 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.
Ans source code:
#include <stdio.h>

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

/* Read from DATA file */


while((number = getw(f1)) != EOF)
{
if(number %2 == 0)
putw(number, f3); /* Write to EVEN file */
else
putw(number, f2); /* Write to ODD file */
}
fclose(f1);
fclose(f2);
fclose(f3);

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

while((number = getw(f3)) != EOF)


printf("%4d", number);
fclose(f2);
fclose(f3);
}

Output:
Contents of DATA file

1
2
3
4
5
-1

Contents of ODD file

1 3 5

Contents of EVEN file

2 4

• File Creation and Input:


The program starts by creating a file named "DATA" in write mode ("w").
It then prompts the user to input integer numbers and writes them to the "DATA" file until -1
is entered.
• File Reading and Categorization:
After writing to the "DATA" file, the program reopens it in read mode ("r").
It reads each number from "DATA" and categorizes them into odd and even numbers.
Odd numbers are written to a file named "ODD," and even numbers are written to a file named
"EVEN."

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.

Q.12 Write a program that swaps two numbers using pointers.


Ans
#include <stdio.h>

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;

// Input the two numbers


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

printf("Enter the second number: ");


scanf("%d", &num2);

// Display the original numbers


printf("Original numbers: %d, %d\n", num1, num2);

// Call the function to swap numbers using pointers


swapNumbers(&num1, &num2);

// Display the swapped numbers


printf("Swapped numbers: %d, %d\n", 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.

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

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.

Ans Source code:

#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

Enter your choice: 5


Enter a string: Suraj
Length of the string: 5

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

You might also like