0% found this document useful (0 votes)
17 views62 pages

Final PDF

Pdf

Uploaded by

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

Final PDF

Pdf

Uploaded by

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

SL.NO Assignments Page.

No Remarks
1. Write a program that reads the co ordinates of 1-2
vertices of a triangle and calculates and display
area of the triangle.
2. Write a program that will read two integers from 3-6
the user and swap their values using:
a)a third variable
b)arithmetic operations
c) bitwise operations.
3. Find the maximum and minimum of four 7-8
integers using conditional operator.
4. Check if an integer is a palindrome or not . 9-10
5. Count the number of 1s in the binary 11-12
representation
of an integer
6. Displayastringinatriangularformusing 13-14
getchar() function.
7. Reverse a string and check if it is palindrome 15-17
without using library function.
8. Perform addition and subtraction between two 18-20
complex numbers using structures.
9. Add two fractions using a structure containing 21-24
numerator and denominator
10. Copy the contents of one file to another 25-26
11. Read numbers from a file and write odd 27-29
numbers to “ODD” and even numbers to
“EVEN”.
12. Print the sum and product of digits of an integer 30-31
13. Check if a number is prime and generate prime 32-34
numbers less than 100.
14. Perform the following on an array: 35-38
i)Print even-valued numbers.
ii)Print odd-valued numbers.
iii) Print maximum and minimum values.
15. Search an element in an array and print whether 39-41
its found or not.
16. Merge two arrays and remove duplicates 42-45
17. Add and multiply two 2D arrays and display the 46-51
Result
18. Print the number of occurrences of each alphabet 52-54
in a text entered as a command line argument.
19 Swap two numbers using pointers 55-56
20. Modify the contents of two variables by passing 57-58
their addresses to a function
21. Computeareaandcircumferenceofacircle 59-60
using a function.
Q 1. Write a program that reads the coordinates of vertices of a triangle and
calculates the display the area of it.

ALGORITHM:

1.Input the coordinates of the vertices of the triangle(x1,y1),(x2,y2),(x3,y3).

2.Calculate the area using the formula:

area=0.5*(x1(y2-y3)+x2(y3-y1)+x3(y1-y2))

3.Display the area.

SOURCE CODE:

#include <stdio.h>

#include <math.h>

int main() {

float x1, y1, x2, y2, x3, y3, area;

// Input coordinates

printf("Enter coordinates of vertex 1 (x1, y1): ");

scanf("%f %f", &x1, &y1);

printf("Enter coordinates of vertex 2 (x2, y2): ");

scanf("%f %f", &x2, &y2);

printf("Enter coordinates of vertex 3 (x3, y3): ");

scanf("%f %f", &x3, &y3);

// Calculate area

area = 0.5 * fabs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));

// Display area

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

return 0;

1
OUTPUT:

Enter coordinates of vertex 1 (x1, y1): 7 4

Enter coordinates of vertex 2 (x2, y2): 1 2

Enter coordinates of vertex 3 (x3, y3): 5 4

Area of the triangle: 2.00

BRIEF DISCUSSION:

This program calculates the area of a triangle .It prompts the user to enter the co
ordinates of three vertices (x1,y1)(x2,y2)(x3,y3).The program then uses the formula
(area=0.5*(x1(y2-y3)+x2(y3-y1)+x3(y1-y2)) to compute the area. The use of fabs()
function ensures that the area is always positive.

2
Q 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:
1. Input:

*Get the initial values of two integer variables, x and y, from the user.

2. Output (Original Values):

*Display the initial values of x and y.

3. Swap using Third Variable:

*Create a temporary integer variable, temp.

*Assign the value of x to temp.

*Assign the value of y to x.

*Assign the value of temp to y.

*Display the swapped values of x and y.

4.Swap using Arithmetic Operations:

*Calculate x = x + y.

*Calculate y = x - y.

*Calculate x = x - y.

*Display the swapped values of x and y.

5. Swap using Bitwise XOR Operations:

*Calculate x = x ^ y.

*Calculate y = x ^ y.

*Calculate x = x ^ y.

3
*Display the swapped values of x and y.
SOURCE CODE:

#include <stdio.h>

int main() {

int x, y, temp;

printf("Enter the value of x: ");

scanf("%d", &x);

printf("Enter the value of y: ");

scanf("%d", &y);

printf("\nOriginal values:\n");

printf("x = %d\n", x);

printf("y = %d\n", y);

// Swapping using third variable

printf("\nSwapped values using third variable:\n");

temp = x;

x = y;

y = temp;

printf("x = %d\n", x);

printf("y = %d\n", y);

// Swapping using arithmetic operations

printf("\nSwapped values using arithmetic operations:\n");

x = x + y;

y = x - y;

x = x - y;

4
printf("x = %d\n", x);

printf("y = %d\n", y);

// Swapping using bitwise operations

printf("\nSwapped values using bitwise operations:\n");

x = x ^ y;

y = x ^ y;

x = x ^ y;

printf("x = %d\n", x);

printf("y = %d\n", y);

return 0;

OUTPUT:

Enter the value of x: 8

Enter the value of y: 2

Original values:

x = 8

y = 2

Swapped values using third variable:

x = 2

y = 8

Swapped values using arithmetic operations:

5
x = 8

y = 2

Swapped values using bitwise operations:

x = 2

y = 8

BRIEF DISCUSSION:

This program achieves the same result: swapping the values of integers by using three different
methods .It prompts the user to swap two values using a third variable(temp)or it can also
perform swapping by using arithmetic operations or by performing bitwise operations as shown
above.

6
Q 3. Write a program that will find maximum and minimum of four integers using
conditional operator.
ALGORITHM:
1.Input four integers.

2.Use nested conditional operators to find the maximum and minimum values.

3.Display the maximum and minimum values.

SOURCE CODE:

#include<stdio.h>

int main(){

int a, b, c, d, max, min;

// Input integers

printf("Enter four integers: ");

scanf("%d %d %d %d", &a, &b, &c, &d);

// Find maximum and minimum

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


> d ? b : d) : (c > d ? c : d));

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


? b : d) : (c < d ? c : d));

// Display maximum and minimum

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

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

return 0;

OUTPUT:

Enter four integers: 5 9 2 7

Maximum: 9

Minimum: 2

7
BRIEF DISCUSSION:

The program prompts the user to enter four integer values using printf().The entered values are
then stored in variables a,b,c,d using scanf().The max variable is assigned the result of a series of
nested ternary operators(ternary operators efficiently compare the values and assign the
maximum value to max).similarly the min variable is assigned the result of nested ternary
operators, determining the smallest value among the four integers.

8
Q 4. Write a program that will read an integer from the user and check whether the
integer is a palindrome or not.
Algorithm:
1.Read an integer from the user.

2. Create a temporary variable to store the original integer.

3. Reverse the integer using a loop.

4. Compare the reversed integer with the original integer.

5. If they are equal, print "Palindrome", otherwise print "Not a palindrome".

SOURCE CODE:

#include<stdio.h>

int main()

int num, originalNum, reversedNum = 0;

printf("Enter an integer: ");

scanf("%d", &num);

originalNum = num;

while(num != 0) {

reversedNum = reversedNum * 10 + num % 10;

num /= 10;

if(originalNum == reversedNum)

printf("%d is a palindrome.\n", originalNum);

else

printf("%d is not a palindrome.\n", originalNum);

return 0;

9
OUTPUT:

Enter an integer: 121

121 is a palindrome

Enter an integer: 154

154 is not a palindrome

BRIEF DISCUSSION:

The code first reads an integer from the user and stores it in num. Then, it creates a copy of num
in originalNum. The loop iterates through each digit of num and reverses it by multiplying
reversedNum by 10 and adding the last digit of num. Finally, it compares originalNum and
reversedNum to determine if the number is a palindrome.

10
Q 5. Write a program that will count the no. of 1s in the binary representation of an
integer given by the user.

ALGORITHM:

1.Read an integer from the user.

2.Initialize a counter to 0.

3.Use a loop to check each bit of the integer. 4.If a

bit is 1, increment the counter.

5. Print the count of 1s.

SOURCE CODE:

#include <stdio.h>

int main() {

int num, count = 0;

printf("Enter an integer: ");

scanf("%d", &num);

while(num > 0) {

if(num & 1) {

count++;

num >>= 1;

printf("Number of 1s in binary representation: %d\n", count);

return 0;

11
OUTPUT:

Enter an integer: 54

Number of 1s in binary representation: 4

BRIEF DISCUSSION:

The code reads an integer from the user and initializes a counter to 0. It then uses a loop
to check each bit of the integer using the bitwise AND operator (&) and the right shift
operator (>>). If a bit is 1, the counter is incremented. Finally, the count of 1s is printed.

12
Q 6. Write a program that will read a string using getchar() function from the user and
display it in triangular form. e.g. If the string given is INDIA then should displayed as

IN

IND

INDI

INDIA

ALGORITHM:

1.Read a string from the user using getchar().

2.Create a loop to iterate through the string.

3.In each iteration, print the substring from the beginning to the current index.

SOURCE CODE:

#include <stdio.h>

int main() {

char str[100];

int i, j;

printf("Enter a string: ");

for(i = 0; (str[i] = getchar()) != '\n'; i++);

for(i = 0; i <= strlen(str); i++)

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

printf("%c", str[j]);

printf("\n");

13
}

return 0;

OUTPUT:

Enter a string:INDIA

IN

IND

INDI

INDIA

INDIA

BRIEF DISCUSSION:

The code reads a string from the user using getchar(). It then uses nested loops to print the string
in triangular form. The outer loop iterates through each character of the string, and the inner
loop prints the substring from the beginning to the current index.

14
Q 7. Write a program that will read a string from user and display the string in reverse order

Hence,check wheather the string is palindrome or not.Don’t use any library function.

ALGORITHM:

1. Input the string: Ask the user to enter a string.

2.Find the length: Count the characters in the string manually until a null character ('\0') or
newline ('\n') is found.

3.Reverse the string: Use a loop to reverse the string by swapping characters from both ends.
Store the reversed string in another variable.

4.Display the reversed string: Print the reversed string.

5.Check if it's a palindrome: Compare the original string with the reversed string. If all
characters match, it is a palindrome; otherwise, it is not.

Source Code:

#include<stdio.h>
int main() {
char a[100], b[100]; // a for the original string, b for the reversed string

int x = 0, y, z; // x is the length of the string, y and z are loop


counters

// Input the string


printf("Enter a string: ");
fgets(a, sizeof(a), stdin);
// Calculate the length of the string
while (a[x] != '\0' && a[x] != '\n') { x++;

15
// Reverse the string

for (y = 0, z = x - 1; z >= 0; y++, z--) {


b[y] = a[z];
}

b[y] = '\0'; // Add null character to the end of the reversed string

// Display the reversed string


printf("Reversed string: %s\n", b); //
Check if the string is a palindrome for (y
= 0; y < x; y++) {
if (a[y] != b[y]) {

printf("The string is not a palindrome.\n"); return 0;


}

printf("The string is a palindrome.\n");


return 0;
}

OUTPUT:

Enter a string: level


Reversed string: level
The string is a palindrome.
Enter a string: hello
Reversed string: olleh
The string is not a palindrome.

16
BRIEF DISCUSSION:

1.Input: The fgets() function is used to take the string input.


2.Length Calculation: The length of the string is determined by manually
iterating through the characters.

3.Reversing: A loop reverses the string by copying characters from the end of the original string
into a new string (b).

4.Palindrome Check: A for loop compares the characters of the original and reversed strings. If
any character differs, it’s not a palindrome.

17
Q 8. Write a program in c using structure to perform addition and substruction between two
complex numbers using function.

ALGORITHM:

6.Define a structure: Create a structure to represent a complex number with real and imaginary
parts.

7.Define functions: Write two functions:

One for adding two complex numbers.


One for subtracting two complex numbers.
8.Input from the user: In the main function, prompt the user to enter the real and

imaginary parts of two complex numbers.

9.Perform operations: Call the addition and subtraction functions with the input numbers.

10. Display results: Print the results of addition and subtraction in the standard complex

number format.

SOURCE CODE:

#include <stdio.h>

// Define a structure for a complex number

struct Complex {

float real; // Real part

float imaginary; // Imaginary part

};

// Function to add two complex numbers

struct Complex add(struct Complex a, struct Complex b) {

struct Complex result;

result.real = a.real + b.real;

18
result.imaginary = a.imaginary + b.imaginary;

return result;

// Function to subtract two complex numbers

struct Complex subtract(struct Complex a, struct Complex b) {

struct Complex result;

result.real = a.real - b.real;

result.imaginary = a.imaginary - b.imaginary;

return result;

int main() {

struct Complex a, b, sum, difference;

// Input the first complex number

printf("Enter the real and imaginary parts of the first complex number:
");

scanf("%f %f", &a.real, &a.imaginary);

// Input the second complex number

printf("Enter the real and imaginary parts of the second complex number: ");

scanf("%f %f", &b.real, &b.imaginary);

// Perform addition and subtraction

sum = add(a, b);

difference = subtract(a, b);

// Display the results

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

printf("Difference: %.2f + %.2fi\n", difference.real,


difference.imaginary);

return 0;

19
}

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

BRIEF DISCUSSION:

Structure Definition:
A structure named Complex is defined with two members: real:
Stores the real part of the complex number.
imaginary: Stores the imaginary part of the complex number.

1.Addition Function:
The add function takes two complex numbers as input.
It adds their real parts and their imaginary parts
2.Subtraction Function:
The subtract function takes two complex numbers.
and subtracts the real and imaginary parts separately.
The result is returned as a new complex number.
Main Function:
The user inputs two complex numbers.
The addition and subtraction functions are called.
The results are displayed in the form real + imaginary*i.

20
Q 9. Degin a structure fraction which contains data members for numerator and
denominator.The program should add two fractions using functions.

ALGORITHM:

1.Define a structure:

Create a structure named Fraction with two members: a for

the numerator.

b for the denominator.

2.Write a GCD function:

Use the Euclidean algorithm to find the greatest common divisor (GCD) of two

numbers.

3.Write a function to add fractions:

Use the formula:

\text{Sum} = \frac{(a_1 \cdot b_2) + (a_2 \cdot b_1)}{b_1 \cdot b_2} 4.Input

fractions:

Prompt the user to enter two fractions (numerator and denominator).

5.Call the addition function:


Compute the sum of the
fractions.
6.Display the result:

Print the simplified fraction.

21
SOURCE CODE:

#include <stdio.h>

// Define the structure

struct Fraction {

int a; // Numerator

int b; // Denominator

};

// Function to find GCD

int gcd(int x, int y) {

while (y != 0) {

int z = y;

y = x % y; x = z;

return x;

// Function to add two fractions

struct Fraction addFractions(struct Fraction f1, struct Fraction f2) { struct

Fraction result;

result.a = f1.a * f2.b + f2.a * f1.b; // Calculate numerator

result.b = f1.b * f2.b; // Calculate denominator

int commonDivisor = gcd(result.a, result.b); // Simplify fraction result.a /=

commonDivisor;

result.b /= commonDivisor;

return result;

int main() {

22
struct Fraction f1, f2, sum;

// Input the first fraction

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

scanf("%d %d", &f1.a, &f1.b);

// Input the second fraction

printf("Enter numerator and denominator of the second fraction: ");

scanf("%d %d", &f2.a, &f2.b);

// Add fractions

sum = addFractions(f1, f2);

// Display the printf("The sum of the fractions is: %d/%d\n", sum.a, sum.b);

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

BRIEF DISCUSSION:
1.Structure Definition:

Fraction structure contains:

a: Stores the numerator.

b: Stores the denominator.


2.GCD Function:
The gcd function finds the greatest common divisor using a simple loop and modulo operation.
3.Addition Function:
Numerator:
\text{result.a} = (\text{f1.a} \cdot \text{f2.b}) + (\text{f2.a} \cdot \text{f1.b}) \
text{result.b} = \text{f1.b} \cdot \text{f2.b}
4.Main Function:
23
Input two fractions from the user.
Call addFractions to compute the sum.
Print the simplified result.

24
Q 10. Write a program to copy the contents of the file into another.
ALGORITHM:
1.Open the source file in read mode.

2.Open the destination file in write mode.

3.Read the contents of the source file character by character and write them to the destination
file.

4.Close both files.

SOURCE CODE:
#include <stdio.h>

int main() {

FILE *sourceFile, *destFile;

char ch;

// Open the source file in read mode

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

(sourceFile == NULL) {

printf("Cannot open source file.\n");

return 1;

// Open the destination file in write mode destFile

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

if (destFile == NULL) {

printf("Cannot open destination file.\n");

return 1;

// Copy contents from source to destination

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

fputc(ch, destFile);

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

// Close the files

fclose(sourceFile);

fclose(destFile);

return 0;

OUTPUT:
When run, the program will copy the contents of source.txt into
destination.txt. The program will display:
File copied successfully.

BRIEF DISCUSSION:
This C program copies the contents of one file to another by opening the source file in read mode
and the destination file in write mode. It reads each character from the source file and writes it to
the destination file until it reaches the end of the source file. Finally, it closes both files, ensuring
that all data is properly copied. This is a simple example showing basic file operations in C.

26
Q 11. A file name data contains a series of integer numbers.Code a program to read this numbers and
then write all odd numbers to a file ODD and all even numbers to a file Even.

ALGORITHM:
1.Open the file DATA in read mode and two other files ODD and EVEN in write mode. 2.Verify
that all files are successfully opened. If not, display an error message and exit.
3.Use a loop to read numbers from the DATA file one by one. If a
number is even (num % 2 == 0), write it to the EVEN file.
Otherwise, write it to the ODD file.
4.Close all the files after processing.
5.Display a success message indicating that the operation is complete.

SOURCE CODE:
#include <stdio.h>

#include <stdlib.h>

int main() {

FILE *a, *b, *c; // a for DATA, b for ODD, c for EVEN

int x;

// Open files

a = fopen("DATA", "r");

b = fopen("ODD", "w");

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

// Check if files are opened successfully

if (a == NULL) {

printf("Error: Unable to open the DATA file.\n");

exit(1);

if (b == NULL || c == NULL) {

printf("Error: Unable to open ODD or EVEN file.\n");

fclose(a);

27
exit(1);
}

// Process numbers

while (fscanf(a, "%d", &x) != EOF) {

if (x % 2 == 0) {

fprintf(c, "%d\n", x); // Write even number to EVEN }

else {

fprintf(b, "%d\n", x); // Write odd number to ODD }

// Close files

fclose(a);

fclose(b);

fclose(c);

// Success message
printf("Odd and even numbers have been written to ODD and EVEN
files.\n");
return 0;
}

OUTPUT:
Input (DATA file):
Content of the file DATA:
5 10 15 20 25 30
Content of the file ODD:
5
15
25

Content of the file EVEN:


10

28
20
30

Console Output:

Odd and even numbers have been written to ODD and EVEN files.

BRIEF DISCUSSION:
1.Purpose: This program separates integers from the DATA file into odd and even
categories and writes them to ODD and EVEN files, respectively.

2.File Handling:

The program uses three files:

DATA: Input file containing numbers.


ODD: Output file for odd numbers.
EVEN: Output file for even numbers.

Proper checks ensure that the files are opened successfully.

3.Logic:

The modulo operation (x % 2) determines if a number is odd or even. If the


remainder is 0, the number is even; otherwise, it's odd.
4.Efficiency: The program processes numbers in a single pass, making it efficient for large
datasets.

5.Error Handling: Includes checks to handle file-related errors, ensuring graceful


termination if something goes wrong.

29
Q 12. Write a program to print the sum of product of digitis of an integer.
ALGORITHM:
1.Start the program.

2.Input an integer x.

3.If x is negative, make it positive.

4.Extract the last digit (b = x % 10), then remove it (x = x / 10).

5.While x > 0:

Extract the next digit (a = x % 10).


Calculate the product of a and b (y = a * b).
Add y to the sum (z += y).
Update b to a, and remove the last digit of x.

6.Print the sum of products (z).

7.End the program.

SOURCE CODE:
#include <stdio.h>

int main() {

int x, a, b, z = 0, y;

printf("Enter an integer: ");

scanf("%d", &x);

if (x < 0) {

x = -x; // Ensure the number is positive

b = x % 10; // Extract the last digit

x = x / 10;

while (x > 0) {

a = x % 10; // Extract the next digit

y = a * b; // Product of adjacent digits

z += y; // Add product to the sum

b = a; // Update b to the current digit

x = x / 10; // Remove the last digit


30
}
printf("Sum of product of digits: %d\n", z);

return 0;

OUTPUT:
Enter an integer: 2345
Sum of product of digits: 44

BRIEF DISCUSSION:
This program calculates the sum of the products of adjacent digits of an integer. By iterating
through the digits, it multiplies each pair and accumulates the sum. Using simple variables (a, b,
x, y, z) ensures clarity and compactness, demonstrating the use of loops and arithmetic
operations in C programming.

31
Q 13. – Write a program to find whether a given number is prime or not. Use

the same to generate number less than 100 .

ALGORITHM:

1.Take n as input.

2.Initialize a variable flag=0.

3.Check if n is prime or not:-

-iterate loop from 2 to n/2 , then

-if n is divisible by any number in this range, it’s not prime.

-otherwise, n is prime.

4.Generate prime number less than 100 using the following steps:- -

Iterate loop from 2 to 100, then

- Check if each number prime using step 3.

- If number is prime, print it.

5.print all the prime numbers less than 100.

SOURCE CODE:

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

int i,n,flag=0,x;

// read input from user.


printf("\n enter a number:");
scanf("%d",&n);
// iterate upto n/2.
for(i=2;i<=n/2;i++)
{

// check if n is divisible by any number.


if(n%i==0)
{
32
Flag=1;

break;

// check if a given number is prime or not.


if(flag==0)
{

printf("\n %d is prime number",n);

else

printf("\n %d is not a prime number",n);

// generate prime numbers less than 100.


printf("\n prime numbers less than 100 : \n");
for(x=2;x<=100;x++)
{

flag=1;
for(i=2;i<=x/2;i++)
{

//check if the numbers are prime or not.


if(x%i==0)
{

flag=0;
break;
}

33
if(flag==1)

//display all the prime numbers less than 100.


printf("\t %d",x);
}

return 0;

OUTPUT:

enter a number:12

12 is not a prime number

prime numbers less than 100 :

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

BRIEF DISCUSSION:

This program defines that how to check if a given number is prime. The condition if checks
whether a number is divisible by any integer between 2 and n/2. If it is divisible, the number is not
prime. Then, a loop runs through all numbers from 2 to 99, calling the Prime function for each.
Prime numbers are displayed as output. The program efficiently handles the prime check by
limiting the range of divisors . The algorithm is efficient and easy to implement, making it a great
solution for generating prime numbers within a given range.

34
Q 14. 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 an array.

ALGORITHM:

Step 1: Declare and initialization of variables.

1.Declare an array x of size n.


2.Initialize the array with n elements.
3.Declare variables max, min, to store the maximum and minimum. Step 2:

Print even and odd valued numbers.

1.Iterate through the array from the first element to the last element. 2.Check
each element to see if it even (i.e., element % 2 ==0).
3.If element is even, print it.
4.Check each element to see if it is odd (i.e., element % 2 !=0).
5.If the element is odd, print it.

Step 3: Find Maximum and Minimum Elements.

1.Initialize max and min with the first element of the array.

2.Iterate through the array from the second element to the last element.

3.Compare each element with max and update max if the element is greater.

4.Compare each element with min and update min if the element is smaller. Step 4:

Print Maximum and Minimum Elements.

1.Print the value of max as the maximum element.

2.Print the value of min as the minimum element.

SOURCE CODE:

#include<stdio.h>

int main()
35
{

int x[10],i,c=0,n,d=0,max,min;

// taking the array size.

printf("\n enter the length of an array:");

scanf("%d",&n);

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

// taking input and storing it in an array.

printf("\n enter elements of array:");

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

//printing elements of array.

printf("\n given array: \n");

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

printf("%4d",x[i]);

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

//check if numbers are even.

if(x[i]%2==0)

c=c+1;

//display no.the even valued numbers.

printf("\n even valued number=%d",c);

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

36
{

//check if the numbers are odd.

if(x[i]%2!=0)

d=d+1;

//display no. the odd valued numbers

printf("\n odd valued number=%d",d);

max=x[0];

min=x[0];

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

if(max<x[i])

max=x[i];

if(min>x[i])

min=x[i];

//display the max and min of array.

printf("\n maximum element of an array=%d",max);

printf("\n minimum element of an array=%d",min);

return 0;

37
OUTPUT:

enter the length of an array:6

enter elements of array:3

enter elements of array:4

enter elements of array:5

enter elements of array:9

enter elements of array:8

enter elements of array:7

given array:

3 4 5 9 8 7

even valued number=2

odd valued number=4

maximum element of an array=9

minimum element of an array=3

BRIEF DISCUSSION:

This program performs three tasks on an integer array:


It prints all even numbers by checking each array element for divisibility by 2. It prints all odd
numbers by checking each array element for divisibility by 2 and ensuring it leaves a remainder.
It calculates the maximum and minimum values by comparing each element in the array to the
current maximum and minimum values. As the array is traversed, the program updates these
values accordingly. Finally, the program outputs the even numbers, odd numbers, and the
maximum and minimum values. This approach effectively processes the array to meet all the
given requirements.

38
Q 15.– Write a program to search an element from an given array if the element is found
then print “found” otherwise print “not found” .

ALGORITHM:

1.Declare an array x of size n.

2.Initialize the array with n elements.

3.Take an element to search for as input.

4.Traverse through each element of the array.

5.Compare the current element with the target element.

6.If the element is found, print "found" and exit the search.

7.If the loop completes without finding the element, print "not found".

SOURCE CODE:

#include<stdio.h>

int main()

int x[10],i,n,v,flag=0;

// taking the array size.

printf("\n enter the length of array:");

scanf("%d",&n);

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

// taking input and storing it in an array.

printf("\n enter the element of array:");

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

// printing elements of an array.

printf("\n given matrix: \n");

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

39
printf("%4d",x[i]);

// searching the element.

printf("\n enter searching element:");

scanf("%d",&v);

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

if(v==x[i])

flag=1;

break;

// checking the searching element is found or not.

if(flag==0)

printf("\n not found");

else

printf("\n found");

return 0;

OUTPUT:

enter the length of array:6

enter the element of array:56

40
enter the element of array:87

enter the element of array:98

enter the element of array:43

enter the element of array:54

enter the element of array:12

given matrix:

568798435412

enter searching element:98

found

enter the length of array:4

enter the element of array:23

enter the element of array:45

enter the element of array:6

enter the element of array:67

given matrix:

2345 667

enter searching element:43

not found

BRIEF DISCUSSION:

This program searches for a specific element in an array. The user is inputing the element they
want to search for. The program then iterates through the array, comparing each element with
the searched value. If the target is found, it prints "Found" and exits the loop. If the loop finishes
without finding the element, it prints "Not Found".

41
Q 16. write a program to merge two array and also remove the duplicates .

ALGORITHM:

1.Declares arrays array1, array2, and merged to store the first array, second array,
and the merged array without duplicates, respectively.
2.Declares a variable mergedSize to keep track of the number of elements in the
merged array.
3.Gets user input for the elements of array1 and array2.

4.Iterates through array1:

For each element in array1, check if it is already present in merged using the
isPresent function.
If the element is not present in merged, add it to merged and increment
mergedSize.
5.Iterates through array2:

For each element in array2, check if it is already present in merged using the
isPresent function.
If the element is not present in merged, add it to merged and increment
mergedSize.
6.Print the merged array, which now contains the elements from both arrays without
duplicates.

SOURCE CODE:

#include <stdio.h>

#define SIZE1 5

#define SIZE2 5

#define MAX_SIZE (SIZE1 + SIZE2)

// Function to check if an element is already in the array

int isPresent(int arr[], int size, int element) {

int i;

42
for ( i = 0; i < size; i++) {

if (arr[i] == element) {

return 1; // Element found

return 0; // Element not found

int main() {

int array1[SIZE1], array2[SIZE2], merged[MAX_SIZE];

int mergedSize = 0,i;

// Input elements for the first array

printf("Enter 5 elements for the first array:\n");

for (i = 0; i < SIZE1; i++) {

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

// Input elements for the second array

printf("Enter 5 elements for the second array:\n");

for ( i = 0; i < SIZE2; i++) {

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

// Add elements of the first array to the merged array

for ( i = 0; i < SIZE1; i++) {

if (!isPresent(merged, mergedSize, array1[i])) {

merged[mergedSize++] = array1[i];

// Add elements of the second array to the merged array

for ( i = 0; i < SIZE2; i++) {

43
if (!isPresent(merged, mergedSize, array2[i])) {

merged[mergedSize++] = array2[i];

// Display the merged array without duplicates

printf("\nMerged array without duplicates:\n");

for (i = 0; i < mergedSize; i++) {

printf("%d ", merged[i]);

printf("\n");

return 0;

OUTPUT:

Enter 5 elements for the first array:

45

89

56

42

21

Enter 5 elements for the second array:

45

89

56

12

23

44
Merged array without duplicates:

45 89 56 42 21 12 23

BRIEF DISCUSSION:

This program merges two arrays into a single array while removing duplicates. It first defines a
function isDuplicate that checks if a value already exists in the merged array. It then merges the
two input arrays array1 and array2, adding elements only if they are not already present in the
merged array. The program uses a simple comparison approach to identify duplicates and
ensures the final merged array contains only unique elements. The result is displayed to the user
without any repeated numbers.

45
Q 17. Write a program to do the following :-

i.Add two 2D array and display the result.

ii.Multiply two 2D array and display the result.

ALGORITHM:

1.Define two 2D arrays and initialize them with size n.


2.For addition, iterate over each element in the arrays, adding corresponding elements,
and store the result in a third array.
3.For multiplication, use the row-column multiplication rule. Multiply elements of rows from
the first array by corresponding elements of columns from the second array and store the
result in a third array.
4.Display the results of both addition and multiplication.

SOURCE CODE:

#include<stdio.h>

int main()

int x[10][10],y[10][10],z[10][10],i,j,r1,r2,c1,c2,k;

// take the row and column of 1st matrix.

printf("\n enter the row and column of 1st matrix:");

scanf("%d %d",&r1,&c1);

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

for(j=0;j<c1;j++)

// taking input and storing it in 2D array.

printf("\n enter the element of 1st matrix:");

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

46
}

// take the row and column of 2nd matrix.

printf("\n enter the row and column of 2nd matrix:");

scanf("%d %d",&r2,&c2);

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

for(j=0;j<c2;j++)

// taking input and storing it in 2D array.

printf("\n enter the element of 2nd matrix:");

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

printf("\n 1st matrix: \n");

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

for(j=0;j<c1;j++)

printf("%4d",x[i][j]);

printf("\n");

printf("\n 2nd matrix: \n");

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

for(j=0;j<c2;j++)

printf("%4d",y[i][j]);

47
}

printf("\n");

if((r1==r2)&&(c1==c2))

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

for(j=0;j<c1;j++)

z[i][j]=x[i][j]+y[i][j];

// display the addition of two 2D array.

printf("\n addition of two matrix: \n");

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

for(j=0;j<c1;j++)

printf("%4d",z[i][j]);

printf("\n");

else

printf("Not possible");

if(c1==r2)

48
{

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

for(j=0;j<c2;j++)

z[i][j]=0;

for(k=0;k<c1;k++)

z[i][j]=z[i][j]+x[i][k]*y[k][j];

// display the multiplication of two 2D array.

printf("\n multiplication of two matrix: \n");

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

for(j=0;j<c2;j++)

printf("%4d",z[i][j]);

printf("\n");

else

printf("Not possible");

return 0;

49
}

OUTPUT:

enter the row and column of 1st matrix: 3 3

enter the element of 1st matrix:1

enter the element of 1st matrix:3

enter the element of 1st matrix:7

enter the element of 1st matrix:9

enter the element of 1st matrix:8

enter the element of 1st matrix:6

enter the element of 1st matrix:6

enter the element of 1st matrix:4

enter the element of 1st matrix:3

enter the row and column of 2nd matrix:3 3

enter the element of 2nd matrix:5

enter the element of 2nd matrix:7

enter the element of 2nd matrix:9

enter the element of 2nd matrix:6

enter the element of 2nd matrix:4

enter the element of 2nd matrix:4

enter the element of 2nd matrix:3

enter the element of 2nd matrix:3

enter the element of 2nd matrix:2

1st matrix:

1 3 7

50
9 8 6

6 4 3

2nd matrix:

5 7 9

6 4 4

3 3 2

addition of two matrix:

6 10 16

15 12 10

9 7 5

multiplication of two matrix:

44 40 35

111 113 125

63 67 76

BRIEF DISCUSSION:

This program performs two operations on 2D arrays:

Matrix Addition: The add Matrices function adds corresponding elements of two matrices and
stores the result in a third matrix.

Matrix Multiplication: The multiply Matrices function follows the standard matrix multiplication

rule, where each element in the resulting matrix is the sum of the product of corresponding row

and column elements from the two matrices.

The display Matrix function is used to print the resulting matrices for both addition and
multiplication. The program uses nested loops to handle both operations and displays the results
accordingly.
51
Q 18. Write a program that prints a table indicating the number of occurrences of each
alphabet in the text entered as command line arguments.

ALGORITM:
1)Declare a array to hold the input string.
2)Prompt the user to enter a string.
3)Read the string, including spaces.
4)Declare a variable (len) to store length of the input string.
5)Declare a (b[len]) array to track if a character has already been counted. 6)Check
the occurrence of each alphabet using for loop.
7)Finally, it prints the occurrences of each alphabet.

SOURCE CODE :

#include <stdio.h>

#include <string.h>

int main()

char s[100]; // Array to hold the input string (max 99 characters)

int c,j,i;

// Prompt the user to enter a string

printf("Enter a string: ");

fgets(s, sizeof(s), stdin);// Read the string, including spaces

// Remove the newline character if it was added by fgets

s[strcspn(s,"\n")] = '\0';

int len = strlen(s);// Length of the input string

int b[len]; // Array to track if a character has already been counted

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

52
b[i] = 0;

printf("Character Occurrences:\n");

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

if (b[i])

continue; // Skip if this character has already been counted

c=1;// Start the count at 1 for the current character

for (j=i+1;j<len;j++)

if (s[i] == s[j])

c++; // If characters match, increase the count

b[j] = 1; // Mark this character as counted

printf("%c : %d\n", s[i], c);

return 0;

OUTPUT :

Enter a string: BARRACKPORERASTRAGURUSURENDRANATHCOLLEGE

Character Occurrences:

B : 1

53
A : 6

R : 8

C : 2

K : 1

P : 1

O : 2

E : 4

S : 2

T : 2

G : 2

U : 3

N : 2

D : 1

H : 1

L : 2

BRIEF DISCUSSION :

In this program, we want to print a table which indicates the number of occurrences of
each alphabet entered as command line argument. We declare a array to hold the input
string then, prompt the user to enter a string. Declare a variable to store the length of
string. Check the occurrences of each alphabet then display the table which indicates
the occurrences of each alphabet.

54
Q 19.Write a program that swaps two number using pointers.

ALGORITHM :

1.Declare two variables to store the numbers to be swapped (a,b). 2.Declare


the pointers to hold the addresses of these variable (*p,*q). 3.Use the
pointers to swap the values of the two variables.
4.Display the values of the variables before and after the swap.

SOURCE CODE :

#include<stdio.h>

int main()

int a,b,c,*p,*q;

//Take two number from user

printf("Enter 1st number:");

scanf("%d",&a);

printf("\nEnter 2nd number:");

scanf("%d",&b);

printf("\nBefore Swapping: a=%d and b=%d",a,b);

//Store both address of a and b to pointers

p=&a;

q=&b;

c=*p;

*p=*q;

*q=c;

//Display the swapping value

printf("\nAfter Swapping: a=%d and b=%d",*p,*q);

return 0;

55
OUTPUT :

Enter 1st number:10

Enter 2nd number:20

Before Swapping: a=10 and b=20

After Swapping: a=20 and b=10

BRIEF DISCUSSION :

This program swaps two numbers using pointers. In the main function, the program first takes
input for two number and stores their addresses in pointers variables. Before and after the swap,
it display the values of the numbers to show the effect of the pointer-based swap.

56
Q 20.Write a program in which a function passes the address of two variables and then alter its
contents.

ALGORITHM :

1.Define a function that accepts the addresses (pointers) of these two variables.
2.Main Function :-
a)Input two numbers from user
b)Store the inputted two number in a variable (a,b)
c)Call the function from main, passing the addresses of the variables. (&a,&b)
3.Function Definition with arguments :-
d)Alter the contents using function
4.Display the values before and after the function call to show the changes.

SOURCE CODE :

#include<stdio.h>

//Function declaration

void alterValues(int *a, int *b);

int main()

int a,b;

//Take two number from the user

printf("Enter 1st number=");

scanf("%d",&a);

printf("Enter 2nd number=");

scanf("%d",&b);

printf("\nBefore altering:a=%d and b=%d",a,b);

//Function calling

alterValues(&a, &b);

//Display the alter values

printf("\nAfter altering:a=%d and b=%d",a,b);

57
return 0;
}
//Function definition to alter the values void
alterValues(int *a, int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
}

OUTPUT :

Enter 1st number=32

Enter 2nd number=21

Before altering: a=32 and b=21

After altering: a=21 and b=32

BRIEF DISCUSSION :

In this program, a function alterValues is defined that accepts the addresses of two variables. The
main function input two numbers and then calls the alterValues function, passing the addresses of
the numbers. The program displays the values of the variables before and after the function call to
show how their contents are changed using pointers.

58
Q 21.Write a program which takes the radius of a circle as input from the user, passes it to another
function that computes the area and circumference of the circle and display the value of area and
circumference from the main () function:-

ALGORITHM:

1.Define pi=3.14
2.Function Declaration
3.Main function :-
a.Input the radius of the circle
b.Store the inputted radius value in a variable
c.Function Calling
4.Function Definition :-
e)Calculate the area and circumference of the circle using formula :-
i)Area=pi*r*r
ii)Circumference=2*pi*r
5.Display the area and circumference of the circle.

SOURCE CODE:

#include <stdio.h>

#define pi 3.14

// Function declaration

void circle(float r,float *area,float *c);

int main()

float r,area,c;

// Taking radius as input from the user

printf("Enter the radius of the circle: ");

scanf("%f",&r);

59
// Compute area and circumference

circle(r,&area,&c);

// Display the area and circumference

printf("\nArea of the circle=%f",area);

printf("\nCircumference of the circle=%f",c);

return 0;

// Function definition to compute the area and circumference of the circle

void circle(float r,float *area,float *c)

*area=pi*r*r;

*c=2*pi*r;

OUTPUT:

Enter the radius of the circle: 4


Area of the circle=50.240002
Circumference of the circle=25.120001

BRIEF DISCUSSION:

This program calculates the area and circumference of a circle, first we define pi=3.14 as constant
value, then declare a function. The user inputs the radius and store it to a variable and this value is
passed to a function circle, then we find the area and circumference of the circle using formula :-
*Area=pi*r*r and *circumference= 2*pi*r
The function uses pointers to pass back the results (area and circumference) to the main()
function. Finally, the main() function prints out the calculated values for area and circumference.

60

You might also like