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

C_Programming_Assignment_Formatted_Junior

The document provides a series of programming tasks that involve reading user input, performing calculations, and displaying results. It covers topics such as calculating the area of a triangle, swapping integers using different methods, finding maximum and minimum values, checking for palindromes, counting binary 1s, and displaying strings in triangular form. Each task includes an algorithm, source code in C, example outputs, and discussions on the logic and edge cases.

Uploaded by

nimaigarai1971
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views45 pages

C_Programming_Assignment_Formatted_Junior

The document provides a series of programming tasks that involve reading user input, performing calculations, and displaying results. It covers topics such as calculating the area of a triangle, swapping integers using different methods, finding maximum and minimum values, checking for palindromes, counting binary 1s, and displaying strings in triangular form. Each task includes an algorithm, source code in C, example outputs, and discussions on the logic and edge cases.

Uploaded by

nimaigarai1971
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 45

1) Write a program reads the coordinates of vertices of a triangle and calculates and display the area of it.

Algorithm:
Step 0: Start
Step 1: Prompt the user to input the coordinates of the first point (x1, y1).
Step 2: Prompt the user to input the coordinates of the second point (x2, y2).
Step 3: Prompt the user to input the coordinates of the third point (x3, y3).
Step 4: Calculate Determinant t.
Use the formula:
t = x1 * (y2 – y3) + x2 * (y3 – y1) + x3 * (y1 – y2).
Step 5: Check if Points Form a Triangle.
if t == 0, display:
“The coordinates of the points cannot form a triangle”.
else:
Continue to the next step.
Step 6: Calculate Area of Triangle.
Use the formula:
A = 0.5 * |t|
Step 7: Display :
“The area of the triangle is: A”.
Step 8: End

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

int main(){
int x1, y1, x2, y2, x3, y3, t;
float A, side1, side2, side3;

// Input for first point


printf(“Enter the coordinates of the first point: “);
scanf(“%d %d”, &x1, &y1);

// Input for second point


printf(“\nEnter the coordinates of the second point: “);
scanf(“%d %d”, &x2, &y2);

// Input for third point


printf(“\nEnter the coordinates of the third point: “);
scanf(“%d %d”, &x3, &y3);

// Calculating the area


t = x1 * (y2 – y3) + x2 * (y3 – y1) + x3 * (y1 – y2);
if(t==0)

1
printf(“The co-ordinated of the points cannot form a triangle”);
else{
A = 0.5 * fabs(t); // Use `fabs` to ensure a positive area
// Printing the results
printf(“\nThe area of the triangle is: %f”, A);
}
return 0;
}

Output:
1)Enter the coordinates of the first point: 5 9

Enter the coordinates of the second point: 1 7

Enter the coordinates of the third point: 8 3

The area of the triangle is: 15.000000

2)Enter the coordinates of the first point: 5 5

Enter the coordinates of the second point: 6 6

Enter the coordinates of the third point: 7 7


The co-ordinated of the points cannot form a triangle

Discussion:
The program shown above calculates area of a triangle by taking the coordinates of the three coordinates of
the vertices of the triangle. Then it calculates t = x1 * (y2 – y3) + x2 * (y3 – y1) + x3 * (y1 – y2) and if t is
equals to 0 then it tells the user that the coordinates of the three points do not make a triangle and they are on
the same line. If t is non-zero then it calculates the area by doing 0.5*|t| and then displays the value of area to
the user

2
2) Write a program that will read two integers from the user and swap their values using

a) a third variable
b) arithmetic operations
c) bitwise operations.

Algorithm:
a) Swapping using a third variable:
Step 1: Start.
Step 2: Take two integers a and b as input.
Step 3: Declare a third variable temp.
Step 4: Assign the value of a to temp.
Step 5: Assign the value of b to a.
Step 6: Assign the value of temp to b.
Step 7: Display the swapped values of a and b.
b) Swapping using arithmetic operations:
Step 1: Start.
Step 2: Take two integers a and b as input.
Step 3: Add a and b and store the result in a.
Step 4: Subtract the new value of a by b and assign it to b.
Step 5: Subtract the new value of b from a and assign it to a.
Step 6: Display the swapped values of a and b.
c) Swapping using bitwise XOR:
Step 1: Start.
Step 2: Take two integers a and b as input.
Step 3: Perform a = a ^ b (XOR operation).
Step 4: Perform b = a ^ b (XOR operation).
Step 5: Perform a = a ^ b (XOR operation).
Step 6: Display the swapped values of a and b.

Source Code:
#include <stdio.h>

void swapUsingThirdVariable(int *a, int *b) {


int temp;
temp = *a;
*a = *b;
*b = temp;
}

void swapUsingArithmetic(int *a, int *b) {


*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}

void swapUsingBitwise(int *a, int *b) {


*a = *a ^ *b;

3
*b = *a ^ *b;
*a = *a ^ *b;
}

int main() {
int x, y;

// Input
printf("Enter two integers: ");
scanf("%d %d", &x, &y);

// Swapping using third variable


int a = x, b = y;
swapUsingThirdVariable(&a, &b);
printf("After swapping using third variable: a = %d, b = %d\n", a, b);

// Swapping using arithmetic operations


a = x; b = y;
swapUsingArithmetic(&a, &b);
printf("After swapping using arithmetic operations: a = %d, b = %d\n", a,
b);

// Swapping using bitwise XOR


a = x; b = y;
swapUsingBitwise(&a, &b);
printf("After swapping using bitwise operations: a = %d, b = %d\n", a, b);

return 0;
}

Output:
Enter two integers: 5 10
After swapping using third variable: a = 10, b = 5
After swapping using arithmetic operations: a = 10, b = 5
After swapping using bitwise operations: a = 10, b = 5

Discussion:
This program demonstrates three different techniques for swapping two integers.

• Using a third variable: This is the simplest and most intuitive method. It involves using extra
memory to hold the value temporarily.

• Using arithmetic operations: This avoids using extra memory but may lead to overflow in some cases
when dealing with very large numbers.

• Using bitwise XOR: This method is efficient and avoids extra memory, but it requires understanding
of XOR operations. This method is particularly useful in low-level programming.
Each method has its advantages and limitations, and the choice depends on the specific application
and constraints.

4
3) Write a program that will find the maximum and minimum of four integers using conditional operator.

Algorithm:
Step 1: Start.
Step 2: Take four integers a, b, c, and d as input.
Step 3: Use the conditional operator to find the maximum value:

• Compare a and b, then compare the result with c, and finally compare the result with d.
Step 4: Use the conditional operator to find the minimum value:

• Compare a and b, then compare the result with c, and finally compare the result with d.
Step 5: Display the maximum and minimum values.
Step 6: Stop.

Source Code:
#include <stdio.h>

int main() {
int a, b, c, d;
int max, min;

// Input
printf("Enter four integers: ");
scanf("%d %d %d %d", &a, &b, &c, &d);

// Finding maximum using conditional operator


max = (a > b ? a : b);
max = (max > c ? max : c);
max = (max > d ? max : d);

// Finding minimum using conditional operator


min = (a < b ? a : b);
min = (min < c ? min : c);
min = (min < d ? min : d);

// Output
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);

return 0;
}

Output:
Enter four integers: 12 45 7 30
Maximum: 45
Minimum: 7

5
Discussion:
This program uses the conditional (ternary) operator ? : to find the maximum and minimum values among
four integers. The operator compares two values at a time, and the result is nested to handle all four
numbers.
• Advantages:

o Compact and efficient for comparing multiple numbers.


o Eliminates the need for multiple if-else statements.

• Edge Cases:

o Handles negative numbers and identical values effectively.

o Works correctly regardless of the order of input values.

6
4) Write a program that will read an integer from the user and check whether the integer is a palindrome or
not.

Algorithm:
Step 1: Start.
Step 2: Take an integer n as input.
Step 3: Store the original value of n in a variable original.
Step 4: Initialize a variable reversed to 0.
Step 5: Use a loop to reverse the digits of the number:

• Extract the last digit of n using n % 10.


• Append this digit to reversed by multiplying reversed by 10 and adding the digit.

• Remove the last digit of n using n / 10.


Step 6: Compare reversed with original.
• If they are equal, the number is a palindrome.

• Otherwise, it is not a palindrome.


Step 7: Display the result.
Step 8: Stop.

Source Code:
#include <stdio.h>

int main() {
int n, original, reversed = 0, digit;

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

// Store the original value


original = n;

// Reverse the number


while (n != 0) {
digit = n % 10; // Extract the last digit
reversed = reversed * 10 + digit; // Append the digit to reversed
n = n / 10; // Remove the last digit
}

// Check if the original number is a palindrome


if (original == reversed) {
printf("The number %d is a palindrome.\n", original);
} else {
printf("The number %d is not a palindrome.\n", original);
}

return 0;
}

7
Output:
Enter an integer: 121
The number 121 is a palindrome.

Enter an integer: 123


The number 123 is not a palindrome.

Discussion:
This program determines if an integer is a palindrome by reversing its digits and comparing the reversed
value with the original.

• Palindrome Definition: A number is a palindrome if it reads the same backward as forward, e.g., 121
or 1221.

• Logic Details:

o Extract each digit using the modulus operator %.

o Reconstruct the reversed number by appending digits to it.

o A simple comparison determines whether the number is a palindrome.


• Edge Cases:

o Works for negative numbers (e.g., -121 is not considered a palindrome).

o Handles single-digit numbers correctly.

8
5) Write a program that will count the number of 1s in the binary representation of an integer given by the
user.

Algorithm:
Step 1: Start.
Step 2: Take an integer n as input.
Step 3: Initialize a counter variable count to 0.
Step 4: While n is not equal to 0, perform the following steps:
• Check if the least significant bit of n is 1 by performing n & 1.

• If true, increment count by 1.

• Right-shift n by 1 using n = n >> 1.


Step 5: Display the value of count.
Step 6: Stop.

Source Code:
#include <stdio.h>

int main() {
int n, count = 0;

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

// Count the number of 1s in the binary representation


while (n != 0) {
if (n & 1) { // Check if the least significant bit is 1
count++;
}
n = n >> 1; // Right shift to process the next bit
}

// Output the count


printf("The number of 1s in the binary representation is: %d\n", count);

return 0;
}

Output:
Enter an integer: 13
The number of 1s in the binary representation is: 3

Enter an integer: 0
The number of 1s in the binary representation is: 0

9
Discussion:

This program counts the number of 1s in the binary representation of an integer using bitwise operations.

• Logic Details:

o The n & 1 operation checks whether the least significant bit is 1.


o The n >> 1 operation shifts the bits of n to the right, discarding the least significant bit,
allowing the program to process all bits sequentially.

• Edge Cases:
o Works for zero, where the count of 1s is 0.

o Handles negative numbers correctly due to the inherent representation of signed integers in
binary.

• Efficiency:

o This approach processes each bit exactly once, making it efficient with a time complexity of
O(log n) for positive integers.

10
6) Write a program that will read a string using getchar() function from the user and display it in triangular
form

Algorithm:
Step 1: Start.
Step 2: Declare a character array str to store the input string and an integer variable len for the string length.
Step 3: Read characters one by one using getchar() until a newline character (\n) is encountered. Append
each character to str.
Step 4: Terminate the string with a null character (\0).
Step 5: Find the length of the string by counting characters until the null character is reached.
Step 6: Use a loop to display the string in triangular form:

• For each iteration from 1 to len, display the first i characters of the string.
Step 7: Stop.

Source Code:

#include <stdio.h>

int main() {
char str[100];
int len = 0;

// Input the string using getchar()


printf("Enter a string: ");
char ch;
while ((ch = getchar()) != '\n') { // Read until newline character
str[len++] = ch;
}
str[len] = '\0'; // Terminate the string with null character

// Display the string in triangular form


printf("Triangular form of the string:\n");
for (int i = 1; i <= len; i++) {
for (int j = 0; j < i; j++) {
putchar(str[j]);
}
putchar('\n'); // Move to the next line
}

return 0;
}

Output:
Enter a string: INDIA
Triangular form of the string:
I
IN
IND
INDI
INDIA

11
Discussion:

This program reads a string using the getchar() function, stores it in a character array, and then displays it in
triangular form.

• Logic Details:

o The string is read character by character until the newline character (\n) is encountered.

o A nested loop is used to print the increasing number of characters from the string in each
iteration.

• Edge Cases:

o Works correctly for strings with spaces, as spaces are treated as valid characters.

o Handles empty strings gracefully (no output for triangular form).

• Memory Management:
o The character array has a fixed size (100), which should be sufficient for most use cases.

12
7) Write a program that will read a string from the user, display the string in reversed order, and check
whether the string is a palindrome or not without using any library functions

Algorithm:
Step 1: Start.
Step 2: Declare a character array str to store the input string, a character array reversed for the reversed
string, and an integer variable len for the string length.
Step 3: Read the string character by character using a loop until a newline character (\n) is encountered.
Append each character to str.
Step 4: Terminate the string with a null character (\0).
Step 5: Calculate the length of the string manually by iterating through the characters until the null character
is reached.
Step 6: Reverse the string:
• Copy characters from str to reversed in reverse order using a loop.

• Terminate reversed with a null character.


Step 7: Display the reversed string.
Step 8: Compare the original string with the reversed string character by character to check if it is a
palindrome.

• If all characters match, it is a palindrome.

• Otherwise, it is not a palindrome.


Step 9: Display whether the string is a palindrome or not.
Step 10: Stop.

Source Code:

#include <stdio.h>

int main() {
char str[100], reversed[100];
int len = 0, isPalindrome = 1;

// Input the string


printf("Enter a string: ");
char ch;
while ((ch = getchar()) != '\n') { // Read until newline character
str[len++] = ch;
}
str[len] = '\0'; // Terminate the string with null character

// Reverse the string


for (int i = 0; i < len; i++) {
reversed[i] = str[len - 1 - i]; // Copy characters in reverse order
}
reversed[len] = '\0'; // Terminate the reversed string

// Display the reversed string


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

13
// Check if the string is a palindrome
for (int i = 0; i < len; i++) {
if (str[i] != reversed[i]) {
isPalindrome = 0; // Set to false if characters don't match
break;
}
}

// Display the result


if (isPalindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}

return 0;
}

Output:
Enter a string: MADAM
Reversed string: MADAM
The string is a palindrome.

Enter a string: HELLO


Reversed string: OLLEH
The string is not a palindrome.

Discussion:

This program reads a string character by character, reverses it manually, and checks if the string is a
palindrome without using any library functions.

• Palindrome Definition: A string is a palindrome if it reads the same forward and backward, such as
"MADAM" or "RACECAR".

• Logic Details:

o String reversal is done by copying characters from the original string to another array in
reverse order.

o Palindrome check is done by comparing each character of the original string with its reversed
counterpart.

• Edge Cases:

o Works for strings with spaces or special characters.


o Handles empty strings gracefully.

• Efficiency:
o Time complexity is O(n) for both reversal and palindrome check.

14
8) Write a program in C using structures to perform addition and subtraction between two complex numbers
using functions

Algorithm:
Step 1: Start.
Step 2: Define a structure Complex with two members: real (for the real part) and imag (for the imaginary
part).
Step 3: Declare functions addComplex and subtractComplex that take two Complex numbers as arguments
and return the result as a Complex number.
Step 4: Implement the addComplex function:

• Add the real parts of the two complex numbers.

• Add the imaginary parts of the two complex numbers.

• Return the result as a new Complex number.


Step 5: Implement the subtractComplex function:

• Subtract the real part of the second number from the first.
• Subtract the imaginary part of the second number from the first.
• Return the result as a new Complex number.
Step 6: In the main function:
• Read two complex numbers from the user.

• Call addComplex and subtractComplex with the input numbers.

• Display the results.


Step 7: Stop.

Source Code:

#include <stdio.h>

// Structure definition for complex numbers


typedef struct {
float real;
float imag;
} Complex;

// Function to add two complex numbers


Complex addComplex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}

// Function to subtract two complex numbers


Complex subtractComplex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real - c2.real;

15
result.imag = c1.imag - c2.imag;
return result;
}

int main() {
Complex c1, c2, sum, difference;

// Input two complex numbers


printf("Enter the real and imaginary parts of the first complex number: ");
scanf("%f %f", &c1.real, &c1.imag);
printf("Enter the real and imaginary parts of the second complex number:
");
scanf("%f %f", &c2.real, &c2.imag);

// Perform addition and subtraction


sum = addComplex(c1, c2);
difference = subtractComplex(c1, c2);

// Output the results


printf("Sum: %.2f + %.2fi\n", sum.real, sum.imag);
printf("Difference: %.2f + %.2fi\n", difference.real, difference.imag);

return 0;
}

Output:
Enter the real and imaginary parts of the first complex number: 3 4
Enter the real and imaginary parts of the second complex number: 1 2
Sum: 4.00 + 6.00i
Difference: 2.00 + 2.00i

Discussion:

This program uses a structure to represent complex numbers and functions to perform addition and
subtraction.

• Advantages of Using Structures:

o The Complex structure organizes the real and imaginary parts of a complex number, making
the code easier to read and maintain.

• Logic Details:

o Addition: Add the corresponding real and imaginary parts of two complex numbers.

o Subtraction: Subtract the corresponding real and imaginary parts of two complex numbers.

• Edge Cases:

o Handles numbers with zero real or imaginary parts correctly (e.g., 0 + 5i).

o Works with negative numbers.

16
9) Design a structure Fraction that contains data members for numerator and denominator. The program
should add two fractions using a function

Algorithm:
Step 1: Start.
Step 2: Define a structure Fraction with two integer members: numerator and denominator.
Step 3: Declare a function addFractions that takes two Fraction structures as arguments and returns their sum
as a new Fraction.
Step 4: Implement the addFractions function:

• Calculate the least common denominator (LCD) of the two fractions.


• Adjust the numerators of the fractions to have the same denominator.

• Add the adjusted numerators and keep the common denominator.

• Simplify the resulting fraction by dividing both numerator and denominator by their greatest
common divisor (GCD).
Step 5: Implement a helper function gcd to calculate the greatest common divisor of two numbers.
Step 6: In the main function:

• Read two fractions from the user.

• Call the addFractions function to compute the sum.


• Display the resulting fraction.
Step 7: Stop.

Source Code:
#include <stdio.h>
// Structure definition for Fraction
typedef struct {
int numerator;
int denominator;
} Fraction;
// Function to calculate the GCD of two numbers
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to add two fractions
Fraction addFractions(Fraction f1, Fraction f2) {
Fraction result;
// Calculate the least common denominator (LCD)
result.denominator = f1.denominator * f2.denominator;
// Adjust the numerators to the same denominator
result.numerator = (f1.numerator * f2.denominator) + (f2.numerator *
f1.denominator);
// Simplify the fraction

17
int divisor = gcd(result.numerator, result.denominator);
result.numerator /= divisor;
result.denominator /= divisor;
return result;
}
int main() {
Fraction f1, f2, sum;
// Input two fractions
printf("Enter numerator and denominator of the first fraction: ");
scanf("%d %d", &f1.numerator, &f1.denominator);
printf("Enter numerator and denominator of the second fraction: ");
scanf("%d %d", &f2.numerator, &f2.denominator);
// Check for zero denominators
if (f1.denominator == 0 || f2.denominator == 0) {
printf("Error: Denominator cannot be zero.\n");
return 1;
}
// Add the fractions
sum = addFractions(f1, f2);
// Output the result
printf("The sum of the fractions is: %d/%d\n", sum.numerator,
sum.denominator);
return 0;
}

Output:
Enter numerator and denominator of the first fraction: 1 2
Enter numerator and denominator of the second fraction: 1 3
The sum of the fractions is: 5/6

Enter numerator and denominator of the first fraction: 3 4


Enter numerator and denominator of the second fraction: 2 4
The sum of the fractions is: 5/4

Discussion:

This program uses a structure to represent fractions and a function to add them.

• Fraction Representation:
o Each fraction is represented by its numerator and denominator.
• Addition Logic:
o The least common denominator is calculated as the product of the denominators.
o Numerators are adjusted to the common denominator before adding.
o The result is simplified using the greatest common divisor (GCD).
• Edge Cases:
o Handles fractions with negative numerators or denominators correctly.
o Includes a check to ensure the denominator is not zero.

18
10) Write a program to copy the contents of one file into another

Algorithm:
Step 1: Start.
Step 2: Declare file pointers sourceFile and destinationFile.
Step 3: Open the source file in read mode ("r") and the destination file in write mode ("w").

• If the source file cannot be opened, display an error message and exit the program.
Step 4: Use a loop to read characters from the source file until the end of the file (EOF) is reached.

• For each character read, write it to the destination file.


Step 5: Close both files.
Step 6: Display a success message indicating that the file copy was completed.
Step 7: Stop.

Source Code:

#include <stdio.h>

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

// Input file names


printf("Enter the name of the source file: ");
scanf("%s", sourceFileName);
printf("Enter the name of the destination file: ");
scanf("%s", destinationFileName);

// Open the source file in read mode


sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL) {
printf("Error: Cannot open source file.\n");
return 1;
}

// Open the destination file in write mode


destinationFile = fopen(destinationFileName, "w");
if (destinationFile == NULL) {
printf("Error: Cannot open destination file.\n");
fclose(sourceFile);
return 1;
}

// Copy contents from source to destination


while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destinationFile);
}

// Close the files


fclose(sourceFile);
fclose(destinationFile);

19
// Success message
printf("File copied successfully from %s to %s.\n", sourceFileName,
destinationFileName);

return 0;
}

Output:
Console Input/Output:
Enter the name of the source file: input.txt
Enter the name of the destination file: output.txt
File copied successfully from input.txt to output.txt.
File Contents:
input.txt:
Hello, this is the source file content.
output.txt:
Hello, this is the source file content.

Discussion:

This program copies the contents of one file into another using file I/O in C.

• Logic Details:

o The fgetc() function reads characters from the source file one by one.

o The fputc() function writes these characters to the destination file.

o Files are opened in appropriate modes ("r" for reading, "w" for writing).

• Edge Cases:

o Handles errors if the source file does not exist or cannot be opened.

o Overwrites the destination file if it already exists.

• Efficiency:

o Suitable for copying text files. For large files or binary data, a buffered approach using fread
and fwrite may be more efficient.

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

Algorithm:
Step 1: Start.
Step 2: Open the DATA file in read mode ("r").
• If the file cannot be opened, display an error message and exit the program.
Step 3: Open the files ODD and EVEN in write mode ("w").
• If either file cannot be opened, display an error message and exit the program.
Step 4: Use a loop to read integers from the DATA file until the end of the file (EOF) is reached.
• If the integer is odd, write it to the ODD file.
• If the integer is even, write it to the EVEN file.
Step 5: Close all the files.
Step 6: Display a success message indicating that the process is complete.
Step 7: Stop.

Source Code:

#include <stdio.h>

int main() {
FILE *dataFile, *oddFile, *evenFile;
int num;

// Open the DATA file in read mode


dataFile = fopen("DATA", "r");
if (dataFile == NULL) {
printf("Error: Cannot open file DATA.\n");
return 1;
}

// Open the ODD and EVEN files in write mode


oddFile = fopen("ODD", "w");
if (oddFile == NULL) {
printf("Error: Cannot open file ODD.\n");
fclose(dataFile);
return 1;}

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


if (evenFile == NULL) {
printf("Error: Cannot open file EVEN.\n");
fclose(dataFile);
fclose(oddFile);
return 1;}

// Read numbers from the DATA file and write to ODD or EVEN file
while (fscanf(dataFile, "%d", &num) != EOF) {
if (num % 2 == 0) {
fprintf(evenFile, "%d\n", num); // Write even numbers to EVEN file
} else {
fprintf(oddFile, "%d\n", num); // Write odd numbers to ODD file

21
}
}

// Close all the files


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

// Success message
printf("Numbers have been separated into ODD and EVEN files
successfully.\n");

return 0;
}

Output:
Console Output:
Numbers have been separated into ODD and EVEN files successfully.
File Contents:
DATA File (DATA):
12 45 8 23 34 19 50 31
ODD File (ODD):
45
23
19
31
EVEN File (EVEN):
12
8
34
50

Discussion:

This program reads integers from a file named DATA and writes all odd numbers to a file ODD and all even
numbers to a file EVEN.
• Logic Details:
o The numbers are read one at a time using fscanf.
o The condition num % 2 == 0 is used to check for even numbers.
• Error Handling:
o The program ensures all files are successfully opened before proceeding.
o Displays appropriate error messages if file operations fail.
• Edge Cases:
o Handles empty files gracefully (no output to ODD or EVEN).
o Handles large numbers correctly.

22
12) Write a program to print the sum and product of digits of an integer

Algorithm:
Step 1: Start.
Step 2: Take an integer n as input from the user.
Step 3: Initialize two variables, sum to 0 and product to 1, to store the sum and product of digits,
respectively.
Step 4: Extract the digits of the integer using a loop:

• Use n % 10 to get the last digit.

• Add the digit to sum.

• Multiply the digit with product.

• Remove the last digit from n using n / 10.


Step 5: Repeat Step 4 until n becomes 0.
Step 6: Display the values of sum and product.
Step 7: Stop.

Source Code:

#include <stdio.h>

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

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

// Handle negative numbers


if (n < 0) {
n = -n;
}

// Calculate sum and product of digits


while (n != 0) {
digit = n % 10; // Extract the last digit
sum += digit; // Add the digit to sum
product *= digit; // Multiply the digit with product
n = n / 10; // Remove the last digit
}

// Output
printf("Sum of digits: %d\n", sum);
printf("Product of digits: %d\n", product);

return 0;
}

23
Output:
Example 1:
Enter an integer: 1234

Sum of digits: 10

Product of digits: 24

Example 2:
Enter an integer: -432

Sum of digits: 9

Product of digits: 24

Discussion:

This program calculates the sum and product of the digits of an integer.

• Logic Details:
o Each digit is extracted using the modulus operator %.

o Digits are accumulated in sum and multiplied in product.

• Handling Negative Numbers:

o The program converts negative numbers to positive using n = -n before processing.

• Edge Cases:

o Handles single-digit numbers correctly (e.g., 5 → sum=5, product=5).

o Works for negative integers and outputs positive results.


• Efficiency:

o The time complexity is O(d), where d is the number of digits in the input.

24
13) Write a program to find whether a given number is prime or not. Use the same to generate prime
numbers less than 100

Algorithm:
Part 1: Check if a number is prime
Step 1: Start.
Step 2: Take an integer n as input.
Step 3: If n is less than 2, it is not prime.
Step 4: Use a loop from i = 2 to sqrt(n) to check divisibility:

• If n is divisible by any i, it is not a prime number.


Step 5: If no divisors are found, the number is prime.

Part 2: Generate all prime numbers less than 100

Step 1: Start.
Step 2: Use a loop to iterate from 2 to 99.
Step 3: For each number, call the prime-checking function.
Step 4: If the number is prime, print it.
Step 5: Stop.

Source Code:

#include <stdio.h>
#include <math.h>

// Function to check if a number is prime


int isPrime(int n) {
if (n < 2) {
return 0; // Not prime
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0; // Not prime
}
}
return 1; // Prime
}

int main() {
int n;

// Check if a given number is prime


printf("Enter a number to check if it is prime: ");
scanf("%d", &n);

if (isPrime(n)) {
printf("%d is a prime number.\n", n);
} else {
printf("%d is not a prime number.\n", n);
}

25
// Generate all prime numbers less than 100
printf("Prime numbers less than 100 are:\n");
for (int i = 2; i < 100; i++) {
if (isPrime(i)) {
printf("%d ", i);
}
}
printf("\n");

return 0;
}

Output:
Example 1: Check if a number is prime
Enter a number to check if it is prime: 29

29 is a prime number.

Example 2: Generate prime numbers less than 100


Prime numbers less than 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 program checks whether a number is prime and generates all prime numbers less than 100.

• Prime Number Definition: A number is prime if it is greater than 1 and divisible only by 1 and itself.

• Logic Details:

o Divisibility is checked up to sqrt(n) to improve efficiency.


o A helper function isPrime is used to determine if a number is prime.

• Edge Cases:

o Handles numbers less than 2 correctly (not prime).

o Works for both small and large numbers within the range of int.

26
14) Write a program to perform the following actions:

i) Print the even-valued numbers from an array.


ii) Print the odd-valued numbers from the array.
iii) Print the maximum and minimum elements of the array.

Algorithm:
Step 1: Start.
Step 2: Take the size of the array n and the elements of the array as input.
Step 3: Initialize variables max and min with the first element of the array.
Step 4: Use a loop to traverse the array:
• For each element:
o Check if it is even or odd.
o Compare it with max and update max if it is greater.
o Compare it with min and update min if it is smaller.
Step 5: Display the even numbers, odd numbers, maximum, and minimum values.
Step 6: Stop.

Source Code:

#include <stdio.h>

int main() {
int n, i;

// Input size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Declare the array


int arr[n];

// Input array elements


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

// Initialize max and min


int max = arr[0], min = arr[0];

// Print even and odd numbers and find max and min
printf("Even numbers: ");
for (i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
printf("%d ", arr[i]);
}
if (arr[i] > max) {
max = arr[i]; // Update max
}
if (arr[i] < min) {
min = arr[i]; // Update min}}

27
printf("\n");

printf("Odd numbers: ");


for (i = 0; i < n; i++) {
if (arr[i] % 2 != 0) {
printf("%d ", arr[i]);}}
printf("\n");

// Output max and min


printf("Maximum element: %d\n", max);
printf("Minimum element: %d\n", min);

return 0;
}

Output:
Example 1:
Enter the size of the array: 6
Enter 6 elements:
12 7 45 34 8 2
Even numbers: 12 34 8 2
Odd numbers: 7 45
Maximum element: 45
Minimum element: 2
Example 2:
Enter the size of the array: 5
Enter 5 elements:
5 3 9 11 13
Even numbers:
Odd numbers: 5 3 9 11 13
Maximum element: 13
Minimum element: 3

Discussion:

This program performs three tasks on an array of integers:


1. Print even numbers: It checks each element with arr[i] % 2 == 0.

2. Print odd numbers: It checks each element with arr[i] % 2 != 0.

3. Find maximum and minimum values: The program compares each element with max and min during
traversal.

• Edge Cases:

o Handles arrays with all even or all odd numbers.

o Handles arrays with only one element (maximum and minimum will be the same).

28
15) Write a program to search an element in a given array. If the element is found, print "found".
Otherwise, print "not found".
Algorithm:
Step 1: Start.
Step 2: Take the size of the array n and the elements of the array as input.
Step 3: Take the element to search (key) as input.
Step 4: Use a loop to traverse the array:
• Compare each element with the key.
• If a match is found, print "found" and exit the loop.
Step 5: If the loop completes without finding the element, print "not found".
Step 6: Stop.

Source Code:

#include <stdio.h>

int main() {
int n, key, i, found = 0;

// Input size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Declare the array


int arr[n];

// Input array elements


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

// Input the element to search


printf("Enter the element to search: ");
scanf("%d", &key);

// Search for the element in the array


for (i = 0; i < n; i++) {
if (arr[i] == key) {
found = 1;
break;}
}

// Output result
if (found) {
printf("found\n");
} else {
printf("not found\n");
}

return 0;
}

29
Output:
Example 1:
Enter the size of the array: 5
Enter 5 elements:
12 45 67 89 23
Enter the element to search: 67
found
Example 2:
Enter the size of the array: 4
Enter 4 elements:
3 8 15 27
Enter the element to search: 10
not found

Discussion:
This program searches for a specific element in an array using a linear search algorithm.
• Logic Details:
o The program iterates through each element of the array and compares it with the search key.
o A flag (found) is used to indicate whether the element has been found.
• Efficiency:
o The time complexity of the program is O(n), where n is the size of the array.
• Edge Cases:
o Handles an empty array (n = 0) gracefully.
o Works correctly when the key is the first, last, or only element in the array.
This solution demonstrates a simple and effective way to perform a linear search in an array.

30
16) Write a program to merge two arrays and also remove the duplicates

Algorithm:
Step 1: Start.
Step 2: Take the sizes of two arrays n1 and n2 as input.
Step 3: Input the elements of both arrays into arr1 and arr2.
Step 4: Merge the two arrays into a single array merged.
• Copy all elements from arr1 to merged.
• Copy all elements from arr2 to merged.
Step 5: Remove duplicates from the merged array:
• Use nested loops to compare each element of the array with every other element.
• If a duplicate is found, shift all subsequent elements to the left to overwrite the duplicate.
Step 6: Display the merged array without duplicates.
Step 7: Stop.

Source Code:

#include <stdio.h>

// Function to remove duplicates from an array


int removeDuplicates(int arr[], int n) {
int i, j, k;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; ) {
if (arr[i] == arr[j]) {
// Shift elements to the left
for (k = j; k < n - 1; k++) {
arr[k] = arr[k + 1];
}
n--; // Reduce array size
} else {
j++; // Move to the next element}
}
}
return n; // Return the new size of the array
}

int main() {
int n1, n2, i, mergedSize;

// Input size of the first array


printf("Enter the size of the first array: ");
scanf("%d", &n1);
int arr1[n1];
printf("Enter %d elements for the first array:\n", n1);
for (i = 0; i < n1; i++) {
scanf("%d", &arr1[i]);
}

// Input size of the second array


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

31
scanf("%d", &n2);
int arr2[n2];
printf("Enter %d elements for the second array:\n", n2);
for (i = 0; i < n2; i++) {
scanf("%d", &arr2[i]);
}

// Merge the two arrays


mergedSize = n1 + n2;
int merged[mergedSize];
for (i = 0; i < n1; i++) {
merged[i] = arr1[i];
}
for (i = 0; i < n2; i++) {
merged[n1 + i] = arr2[i];}

// Remove duplicates
mergedSize = removeDuplicates(merged, mergedSize);

// Output the merged array without duplicates


printf("Merged array without duplicates:\n");
for (i = 0; i < mergedSize; i++) {
printf("%d ", merged[i]);
}
printf("\n");

return 0;
}

Output:
Example 1:
Enter the size of the first array: 5
Enter 5 elements for the first array:
1 2 3 4 5
Enter the size of the second array: 5
Enter 5 elements for the second array:
3 4 5 6 7
Merged array without duplicates:
1 2 3 4 5 6 7
Example 2:
Enter the size of the first array: 3
Enter 3 elements for the first array:
10 20 30
Enter the size of the second array: 4
Enter 4 elements for the second array:
20 30 40 50
Merged array without duplicates:
10 20 30 40 50

32
Discussion:

This program merges two arrays and removes duplicates efficiently.

• Logic Details:

o Elements from both arrays are merged into a single array.


o Duplicate elements are removed by comparing each element with subsequent elements and
shifting duplicates left.

• Edge Cases:
o Handles empty arrays (n1 = 0 or n2 = 0).

o Works when all elements are unique or when all are duplicates.

• Efficiency:

o Removing duplicates involves nested loops, so the time complexity is O(n²).

33
17) Write a program to perform the following:

i) Add two 2D arrays and display the result.


ii) Multiply two 2D arrays and display the result.

Algorithm:
i) Addition of two 2D arrays

Step 1: Start.
Step 2: Take the dimensions of the arrays (rows and cols) as input.
Step 3: Input the elements of the two 2D arrays (A and B).
Step 4: Create a result array C.

• For each element C[i][j], calculate C[i][j] = A[i][j] + B[i][j].


Step 5: Display the resulting array C.

ii) Multiplication of two 2D arrays

Step 1: Start.
Step 2: Take the dimensions of the arrays:

• For multiplication, the number of columns of the first array (colsA) must equal the number of rows
of the second array (rowsB).
Step 3: Input the elements of the two 2D arrays (A and B).
Step 4: Create a result array C.

• For each element C[i][j], calculate the dot product of the ith row of A and the jth column of B.
Step 5: Display the resulting array C.

Source Code:

#include <stdio.h>

void addMatrices(int rows, int cols, int A[10][10], int B[10][10], int
C[10][10]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}

void multiplyMatrices(int rowsA, int colsA, int rowsB, int colsB, int
A[10][10], int B[10][10], int C[10][10]) {
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
C[i][j] = 0;
for (int k = 0; k < colsA; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}

34
void printMatrix(int rows, int cols, int matrix[10][10]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int rowsA, colsA, rowsB, colsB;
int A[10][10], B[10][10], C[10][10];

// Input dimensions for addition


printf("Enter the number of rows and columns for addition: ");
scanf("%d %d", &rowsA, &colsA);

// Input matrices for addition


printf("Enter elements of first matrix:\n");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
scanf("%d", &A[i][j]);
}
}
printf("Enter elements of second matrix:\n");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
scanf("%d", &B[i][j]);
}
}

// Add matrices
printf("Result of addition:\n");
addMatrices(rowsA, colsA, A, B, C);
printMatrix(rowsA, colsA, C);

// Input dimensions for multiplication


printf("Enter the number of rows and columns for the first matrix for
multiplication: ");
scanf("%d %d", &rowsA, &colsA);
printf("Enter the number of rows and columns for the second matrix for
multiplication: ");
scanf("%d %d", &rowsB, &colsB);

if (colsA != rowsB) {
printf("Error: Matrices cannot be multiplied.\n");
return 1;
}

// Input matrices for multiplication


printf("Enter elements of first matrix:\n");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
scanf("%d", &A[i][j]);

35
}
}
printf("Enter elements of second matrix:\n");
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
scanf("%d", &B[i][j]);
}
}

// Multiply matrices
printf("Result of multiplication:\n");
multiplyMatrices(rowsA, colsA, rowsB, colsB, A, B, C);
printMatrix(rowsA, colsB, C);

return 0;
}

Output:
Example 1: Addition
Enter the number of rows and columns for addition: 2 2
Enter elements of first matrix:
1 2
3 4
Enter elements of second matrix:
5 6
7 8
Result of addition:
6 8
10 12
Example 2: Multiplication
Enter the number of rows and columns for the first matrix for multiplication: 2
2
Enter the number of rows and columns for the second matrix for multiplication:
2 2
Enter elements of first matrix:
1 2
3 4
Enter elements of second matrix:
5 6
7 8
Result of multiplication:
19 22
43 50

36
Discussion:

• Addition: Adds corresponding elements of two matrices. Works only when the dimensions of the
two matrices are the same.

• Multiplication: Multiplies two matrices using the dot product. Requires that the number of columns
in the first matrix equals the number of rows in the second.

• Edge Cases:

o Addition handles matrices of any valid size with matching dimensions.

o Multiplication validates dimensions before performing the operation.

37
18) Write a program that prints a table indicating the number of occurrences of each alphabet in the
text entered as command-line arguments

Algorithm:
Step 1: Start.
Step 2: Read the command-line arguments, which include the program name and the input text.
Step 3: Initialize an array count[26] of size 26 to 0, representing the occurrence of each letter ('a' to 'z').
Step 4: For each character in the input text:

• Convert the character to lowercase if it is uppercase.

• Check if the character is a letter ('a' to 'z').

• If it is, increment the corresponding element in the count array based on the character's ASCII value.
Step 5: Display the count for each letter from 'a' to 'z'.
Step 6: Stop.

Source Code:

#include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[]) {


int count[26] = {0}; // Array to store the count of each alphabet
char ch;
int i, j;

// Check if input is provided


if (argc < 2) {
printf("Error: Please provide text as command-line arguments.\n");
return 1;
}

// Process each command-line argument


for (i = 1; i < argc; i++) {
for (j = 0; argv[i][j] != '\0'; j++) {
ch = argv[i][j];
if (isalpha(ch)) { // Check if the character is an alphabet
ch = tolower(ch); // Convert to lowercase
count[ch - 'a']++; // Increment the corresponding count
}
}
}

// Print the table of occurrences


printf("Alphabet Occurrences:\n");
for (i = 0; i < 26; i++) {
if (count[i] > 0) {
printf("%c: %d\n", i + 'a', count[i]);}
}

return 0;
}

38
Compilation and Execution:
Example Command:
gcc count_alphabets.c -o count_alphabets
./count_alphabets This is a Sample text
Output:
Alphabet Occurrences:
a: 2
e: 2
h: 1
i: 2
l: 1
m: 1
p: 1
s: 4
t: 3
x: 1

Discussion:

• Logic Details:

o The isalpha function ensures only alphabetic characters are processed.


o The tolower function converts uppercase letters to lowercase, treating 'A' and 'a' as the same.

o Each letter is mapped to its position in the count array using ch - 'a'.

• Edge Cases:

o Handles mixed-case text correctly by converting all letters to lowercase.


o Ignores non-alphabetic characters such as digits, punctuation, or whitespace.

o Handles empty input gracefully with an error message.

39
19) Write a program that swaps two numbers using pointers

Algorithm:
Step 1: Start.
Step 2: Take two integer variables a and b as input.
Step 3: Declare two pointers p1 and p2 to point to a and b, respectively.
Step 4: Use a temporary variable temp to perform the swap:

• Assign the value at *p1 to temp.

• Assign the value at *p2 to *p1.

• Assign the value of temp to *p2.


Step 5: Display the values of a and b after the swap.
Step 6: Stop.

Source Code:

#include <stdio.h>

void swap(int *p1, int *p2) {


int temp;
temp = *p1; // Store the value of *p1 in temp
*p1 = *p2; // Assign the value of *p2 to *p1
*p2 = temp; // Assign the value of temp to *p2
}

int main() {
int a, b;

// Input
printf("Enter two numbers:\n");
scanf("%d %d", &a, &b);

printf("Before swapping: a = %d, b = %d\n", a, b);

// Swap using pointers


swap(&a, &b);

// Output
printf("After swapping: a = %d, b = %d\n", a, b);

return 0;
}

Output:
Example 1:
Enter two numbers:
10 20
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10

40
Example 2:
Enter two numbers:
-5 15
Before swapping: a = -5, b = 15
After swapping: a = 15, b = -5

Discussion:
This program swaps two numbers using pointers, demonstrating the concept of pointer manipulation in C.

• Logic Details:

o Pointers p1 and p2 store the addresses of a and b.

o Dereferencing the pointers (*p1, *p2) allows direct manipulation of the values stored in a and
b.

o A temporary variable is used to store intermediate values during the swap.

• Advantages of Using Pointers:


o Direct access to the memory locations of variables.

o Useful for functions that need to modify the original values passed as arguments.

41
20) Write a program in which a function passes the address of two variables and then alters their
contents

Algorithm:
Step 1: Start.
Step 2: Declare two integer variables a and b.
Step 3: Pass the addresses of a and b to a function named alterValues.
Step 4: In the alterValues function:

• Increment the first variable by 10.

• Multiply the second variable by 2.


Step 5: Return to the main function and display the modified values of a and b.
Step 6: Stop.

Source Code:

#include <stdio.h>

// Function to alter the contents of two variables


void alterValues(int *x, int *y) {
*x += 10; // Increment the value at address x by 10
*y *= 2; // Multiply the value at address y by 2
}

int main() {
int a, b;

// Input
printf("Enter two numbers:\n");
scanf("%d %d", &a, &b);

printf("Before altering: a = %d, b = %d\n", a, b);

// Pass the addresses of a and b to the function


alterValues(&a, &b);

// Output
printf("After altering: a = %d, b = %d\n", a, b);

return 0;
}

Output:
Example 1:
Enter two numbers:
5 10
Before altering: a = 5, b = 10
After altering: a = 15, b = 20

42
Example 2:
Enter two numbers:
-3 4
Before altering: a = -3, b = 4
After altering: a = 7, b = 8

Discussion:

This program demonstrates passing the addresses of two variables to a function and altering their values.

• Key Concepts:

o Pointers: The function receives pointers to the variables and modifies their values directly in
memory.

o Pass-by-Reference: Changes made in the function persist in the calling function (main) since
the variables' memory addresses are used.

• Logic Details:
o *x and *y allow direct manipulation of the values stored at the addresses of a and b.

43
21) Write a program in which a function passes the radius of a circle to another function that
computes the area and circumference of the circle and displays the values from the main() function.

Algorithm:
Step 1: Start.
Step 2: Take the radius of the circle as input in the main() function.
Step 3: Pass the radius to another function named calculateCircle.
Step 4: In the calculateCircle function:

• Compute the area using the formula: area = π * radius * radius.


• Compute the circumference using the formula: circumference = 2 * π * radius.
• Return the area and circumference to the main() function.
Step 5: Display the values of the area and circumference from the main() function.
Step 6: Stop.
Source Code:

#include <stdio.h>
#define PI 3.14159 // Define the value of π

// Function to calculate the area and circumference


void calculateCircle(float radius, float *area, float *circumference) {
*area = PI * radius * radius; // Calculate the area
*circumference = 2 * PI * radius; // Calculate the circumference}

int main() {
float radius, area, circumference;

// Input the radius of the circle


printf("Enter the radius of the circle: ");
scanf("%f", &radius);

// Call the function to calculate area and circumference


calculateCircle(radius, &area, &circumference);

// Display the results


printf("Area of the circle: %.2f\n", area);
printf("Circumference of the circle: %.2f\n", circumference);

return 0;
}

Output:
Example 1:
Enter the radius of the circle: 5

Area of the circle: 78.54

Circumference of the circle: 31.42

Example 2:
Enter the radius of the circle: 10.5

Area of the circle: 346.36

Circumference of the circle: 65.97

44
Discussion:

This program separates the calculation logic into a function to demonstrate the use of passing values and
pointers between functions.

• Key Concepts:

o The calculateCircle function uses pointers (*area and *circumference) to modify and return
the results directly to the calling function.

o The use of #define simplifies the representation of the constant value π (PI).

• Advantages:

o This modular approach enhances readability and reusability.


o Supports floating-point precision for radius, area, and circumference calculations.

• Edge Cases:

o Handles a radius of 0 correctly (outputs area and circumference as 0.00).

o Negative radius is not validated in this example. Validation can be added to ensure a positive
radius.

45

You might also like