C_Programming_Assignment_Formatted_Junior
C_Programming_Assignment_Formatted_Junior
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;
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
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>
3
*b = *a ^ *b;
*a = *a ^ *b;
}
int main() {
int x, y;
// Input
printf("Enter two integers: ");
scanf("%d %d", &x, &y);
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);
// 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:
• Edge Cases:
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:
Source Code:
#include <stdio.h>
int main() {
int n, original, reversed = 0, digit;
// Input
printf("Enter an integer: ");
scanf("%d", &n);
return 0;
}
7
Output:
Enter an integer: 121
The number 121 is 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:
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.
Source Code:
#include <stdio.h>
int main() {
int n, count = 0;
// Input
printf("Enter an integer: ");
scanf("%d", &n);
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:
• 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;
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.
• 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.
Source Code:
#include <stdio.h>
int main() {
char str[100], reversed[100];
int len = 0, isPalindrome = 1;
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;
}
}
return 0;
}
Output:
Enter a string: MADAM
Reversed string: MADAM
The string is 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:
• 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:
• 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.
Source Code:
#include <stdio.h>
15
result.imag = c1.imag - c2.imag;
return result;
}
int main() {
Complex c1, c2, sum, difference;
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.
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).
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:
• 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:
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
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.
Source Code:
#include <stdio.h>
int main() {
FILE *sourceFile, *destinationFile;
char sourceFileName[100], destinationFileName[100];
char ch;
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 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.
• 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;
// 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
}
}
// 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:
Source Code:
#include <stdio.h>
int main() {
int n, digit, sum = 0, product = 1;
// Input
printf("Enter an integer: ");
scanf("%d", &n);
// 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 %.
• Edge Cases:
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:
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>
int main() {
int 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.
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:
• Edge Cases:
o Works for both small and large numbers within the range of int.
26
14) Write a program to perform the following actions:
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;
// 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");
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:
3. Find maximum and minimum values: The program compares each element with max and min during
traversal.
• Edge Cases:
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;
// 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>
int main() {
int n1, n2, i, mergedSize;
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]);
}
// Remove duplicates
mergedSize = removeDuplicates(merged, mergedSize);
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:
• Logic Details:
• Edge Cases:
o Handles empty arrays (n1 = 0 or n2 = 0).
o Works when all elements are unique or when all are duplicates.
• Efficiency:
33
17) Write a program to perform the following:
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.
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];
// Add matrices
printf("Result of addition:\n");
addMatrices(rowsA, colsA, A, B, C);
printMatrix(rowsA, colsA, C);
if (colsA != rowsB) {
printf("Error: Matrices cannot be multiplied.\n");
return 1;
}
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:
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:
• 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>
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 Each letter is mapped to its position in the count array using ch - 'a'.
• Edge Cases:
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:
Source Code:
#include <stdio.h>
int main() {
int a, b;
// Input
printf("Enter two numbers:\n");
scanf("%d %d", &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 Dereferencing the pointers (*p1, *p2) allows direct manipulation of the values stored in a and
b.
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:
Source Code:
#include <stdio.h>
int main() {
int a, b;
// Input
printf("Enter two numbers:\n");
scanf("%d %d", &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:
#include <stdio.h>
#define PI 3.14159 // Define the value of π
int main() {
float radius, area, circumference;
return 0;
}
Output:
Example 1:
Enter the radius of the circle: 5
Example 2:
Enter the radius of the circle: 10.5
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:
• Edge Cases:
o Negative radius is not validated in this example. Validation can be added to ensure a positive
radius.
45