Nothing Special   »   [go: up one dir, main page]

C Lab Manual R 20

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 36

Exercise 1:

a) AIM: Write a C program to calculate the area of a triangle.

Algorithm:
Step 1: In this C program, User will enter the three sides of the triangle a, b, c.
Step 2: Calculating the Perimeter of the Triangle using the formula P = a+b+c.
Step 3: Calculating the semi perimeter using the formula (a+b+c)/2. Although we can write
semi perimeter = (Perimeter/2) but we want to show the formula behind. That’s why we used
the standard formula
Step 4: Calculating the Area of a triangle using Heron’s Formula:

sqrt(s*(s-a)*(s-b)*(s-c));

Program:
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, Perimeter, s, Area;
printf("\nPlease Enter three sides of triangle\n");
scanf("%f%f%f",&a,&b,&c);
Perimeter = a+b+c;
s = (a+b+c)/2;
Area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("\n Perimeter of Traiangle = %.2f\n", Perimeter);
printf("\n Semi Perimeter of Traiangle = %.2f\n",s);
printf("\n Area of triangle = %.2f\n",Area);
return 0;
}
Output :
Please Enter the three sides of triangle
5
6
7
Area of triangle = 14.70
b) AIM: Write a C program to find the largest of three numbers using ternary operator.
Algorithm:
1. In first step, let's declare three variables to hold the values of three input numbers.
2. use ternary operator to compare the values of three variable and assign the result into a
variable
3. print the value of a variable.

Program:

#include <stdio.h>
int main(){
int a, b, c;
printf("Enter three numbers ");
scanf("%d %d %d", &a, &b, &c);
int result = ( a > b ) ? (a > c ? a : c) : ( b > c ? b : c);
printf(" Largest of three numbers is %d ", result);
return 0;
}
Output:

Enter three numbers :  8  2   1

Largest of three numbers is 8

c) AIM: Write a C program to swap two numbers without using temporary variable.
Algorithm:
Step 1) Add the value of a and b and assign the result in a.
a = a+b;
Step 2) To get the swapped value of b: Subtract the value of b from a (which was the sum of a
and b).
b = a-b;
Step 3) To get the swapped value of a: Subtract the value of b from a.
a = a-b;

Program:
#include <stdio.h>

int main()
{
//variable declarations
int a,b;
//Input values
printf("Enter the value of a: ");
scanf("%d",&a);
printf("Enter the value of b: ");
scanf("%d",&b);
//Numbers before swapping
printf("Before swapping... a: %d, b: %d\n",a,b);
//swapping numbers
a = a+b; //step 1
b = a-b; //step 2
a = a-b; //step 3
//Numbers after swapping
printf("After swapping... a: %d, b: %d\n",a,b);
return 0;
}

Output:

First run:
Enter the value of a: 10
Enter the value of b: 20
Before swapping... a: 10, b: 20
After swapping... a: 20, b: 10
Exercise 2:

a) AIM: Write a C program to find the 2’s complement of a binary number.


Algorithm:

Step 1: Input a binary string from user. Store it in a variable say binary.

Step 2: Find ones complement of the binary string. Store the result in some variable say ones
Comp.

Step 3: Declare and initialize another binary string variable to store twos complement, say twos
Comp = "".

Step 4: Initialize a variable to store carry bit during addition, say carry = 1.
You may think now, why initialize carry to 1, why not 0? Since, we need to add only 1 to the
binary string hence, I have initially assumed carry bit as the bit to be added.

Step 5: Run a loop from length of binary string to 1, decrement 1 in each iteration. The loop
structure should look like for(i=SIZE-1; i>=1; i--) (where SIZE is length of the binary string).
You may think, why iterating in reverse order? Because addition is carried out in right to left
order.

Step 6: Inside the loop there can be three cases.


If both current binary bit and carry bit are 1 then, put 0 to twos complement. Which is
if(onesComp[i]=='1' && carry==1) then, twosComp[i] = '0', carry is still preserved to 1.
If current binary bit is 0 and carry bit is 1 then, put 1 to twos complement and set carry bit to 0.
Which is if(onesComp[i]=='0' && carry==1) then, twosComp[i] = '1' and carry = 0.
If carry bit is 0, then assign the value of onesComp to twosComp.

Program:

#include <stdio.h>
#define SIZE 8
int main()
{
char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE + 1];
int i, carry=1;
printf("Enter %d bit binary value: ", SIZE);
/* Input 8-bit binary string */
gets(binary);
/* Find ones complement of the binary number */
for(i=0; i<SIZE; i++)
{
if(binary[i] == '1')
{
onesComp[i] = '0';
}
else if(binary[i] == '0')
{
onesComp[i] = '1';
}
}
onesComp[SIZE] = '\0';
/*
* Add 1 to the ones complement
*/
for(i=SIZE-1; i>=0; i--)
{
if(onesComp[i] == '1' && carry == 1)
{
twosComp[i] = '0';
}
else if(onesComp[i] == '0' && carry == 1)
{
twosComp[i] = '1';
carry = 0;
}
else
{
twosComp[i] = onesComp[i];
}
}
twosComp[SIZE] = '\0';
printf("Original binary = %s\n", binary);
printf("Ones complement = %s\n", onesComp);
printf("Twos complement = %s\n", twosComp);
return 0;
}

Output :
Enter 8 bit binary value: 01101100
Original binary = 01101100
Ones complement = 10010011
Twos complement = 10010100

b) AIM: Write a C program to find the roots of a quadratic equation.


Algorithm:

Step 1: Input coefficients of quadratic equation from user. Store it in some variable say a, b and
c.
Step 2: Find discriminant of the given equation, using formula discriminant = (b*b) - (4*a*c).
Step 3: Compute roots based on the nature of discriminant.
If discriminant > 0 then,
root1 = (-b + sqrt(discriminant)) / (2*a) and
root2 = (-b - sqrt(discriminant)) / (2*a).
Learn - Program to find square root of a number using sqrt() function.

Step 4: If discriminant == 0 then, root1 = root2 = -b / (2*a).


Else if discriminant < 0 then, there are two distinct complex roots where
root1 = -b / (2*a) and root2 = -b / (2*a).
Imaginary part of the root is given by imaginary = sqrt(-discriminant) / (2*a).

Program :
#include <stdio.h>
#include <math.h> /* Used for sqrt() */
int main()
{
float a, b, c;
float root1, root2, imaginary;
float discriminant;
printf("Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ");
scanf("%f%f%f", &a, &b, &c);
/* Find discriminant of the equation */
discriminant = (b * b) - (4 * a * c);
/* Find the nature of discriminant */
if(discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);

printf("Two distinct and real roots exists: %.2f and %.2f", root1, root2);
}
else if(discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("Two equal and real roots exists: %.2f and %.2f", root1, root2);
}
else if(discriminant < 0)
{
root1 = root2 = -b / (2 * a);
imaginary = sqrt(-discriminant) / (2 * a);
printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2f",
root1, imaginary, root2, imaginary);
}
return 0;
}

Output :
Enter values of a, b, c of quadratic equation (aX^2 + bX + c): 8 -4 -2
Two distinct and real roots exists: 0.81 and -0.31

c) AIM: Write a C program to implement simple calculator using switch statement.


Algorithm:
1. Input two numbers and a character from user in the given format. Store them in some
variable say num1, op and num2.
2. Switch the value of op i.e. switch(op).
3. There are four possible values of op i.e. '+', '-', '*' and '/'.
4. For case '+' perform addition and store result in some variable i.e. result = num1 +
num2.
5. Similarly for case '-' perform subtraction and store result in some variable i.e. result =
num1 - num2.
6. Repeat the process for multiplication and division.
7. Finally print the value of result.

Program:
#include <stdio.h>

int main()
{
char op;
float num1, num2, result=0.0f;
/* Print welcome message */
printf("WELCOME TO SIMPLE CALCULATOR\n");
printf("----------------------------\n");
printf("Enter [number 1] [+ - * /] [number 2]\n");
/* Input two number and operator from user */
scanf("%f %c %f", &num1, &op, &num2);
/* Switch the value and perform action based on operator*/
switch(op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
printf("Invalid operator");
}
/* Prints the result */
printf("%.2f %c %.2f = %.2f", num1, op, num2, result);
return 0;
}

Output :
WELCOME TO SIMPLE CALCULATOR
----------------------------
Enter [number 1] [+ - * /] [number 2]
22 * 6
22.0 6.00 = 132.00
Exercise 3:
a) AIM: Write a C program to find the sum of individual digits of a positive integer and
also find the reverse of the given number.
Algorithm:
Step 1: Start
Step 2: Read num as integer
Step 3: while (num > 0)
begin
dig ← num MOD 10;
sumOfDigits ← sumOf Digits + dig;
num ← num DIV 10;
end
Step 4: Print sumOfDigits
Step 5: Stop

Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main ()
{
int number = 0, digit = 0, sumOfDigits = 0;
clrscr();
printf("Enter any number\n ");
scanf("%d", &number);
while (number != 0)
{
digit = number % 10;
sumOfDigits = sumOfDigits + digit;
number = number / 10;
}
printf ("Sum of individual digits of a given number is %d", sumOfDigits);
getch();
}

Output:
Enter any number
1234
Sum of individual digits of a given number is 10

b) AIM: Write a C program to generate the first n terms of the Fibonacci sequence.
Algorithm:
Step 1: The first term in the sequence is 0
Step 2: The second term in the sequence is 1
Step 3: The sub sequent terms 1 found by adding the preceding two terms in the sequence
Step 4: Formula: let t1, t2, ………… tn be terms in fibinacci sequence
t1 = 0, t2 = 1
tn = tn – 2 + tn – 1 …… where n > 2

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 0, b = 1, lengthOfSeries = 0, counter, sum = 0;
clrscr();
printf("Enter the length of series \n ");
scanf("%d", &lengthOfSeries);
printf("Fibonacci series\n");
printf("%d %d", a, b);
for(counter = 2; counter < lengthOfSeries; counter++)
{
sum = a + b;
printf(" %d",sum);
a = b;
b = sum;
}
getch();
}

Output:
Enter the length of series
15
Fibonacci series
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

c) AIM:Write a C program to generate all the prime numbers between 1 and n,where n is a
value supplied by the user.
Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i = 1, c = 0
Step 4: if i <= n goto step 5
If not goto step 10
Step 5: initialize j = 1
Step 6: if j <= 1 do as the follow. If no goto step 7
i)if i%j == 0 increment c
ii) increment j
iii) goto Step 6
Step 7: if c == 2 print i
Step 8: increment i
Step 9: goto step 4
Step 10: stop

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, j, count;
clrscr();
printf("Prime no.series\n");
printf("Enter any number\n");
scanf("%d", &n);
printf("The prime numbers between 1 to %d\n",n);
for(i = 1; i <= n; i++)
{
count = 0;
for(j = 1; j <=i; j++)
if(i % j == 0)
{
count++;
}
if(count == 2)
{
printf("%d\t", i);
}
}
getch();
}

Output:
Prime no. series
Enter any number
10
The prime numbers between 1 to 10
2 3 5 7
Exercise 4:
a) AIM: Write a C program to print the Multiplication table of a given number.
Algorithm:
Step 1: Input a number from user to generate multiplication table. Store it in some variable say
num.
Step 2: To print multiplication table we need to iterate from 1 to 10. Run a loop from 1 to 10,
increment 1 on each iteration. The loop structure should look like for(i=1; i<=10; i++).
Step 3: Inside loop generate multiplication table using num * i and print in specified format.

Program :

#include <stdio.h>
int main()
{
int i, num;
/* Input a number to print table */
printf("Enter number to print table: ");
scanf("%d", &num);
for(i=1; i<=10; i++)
{
printf("%d * %d = %d\n", num, i, (num*i));
}
return 0;
}

Output:
Enter number to print table of: 5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

b) AIM: Write a C program to read a decimal number and find it’s equivalent binary
number.

Algorithm:
1. Store the remainder when the number is divided by 2 in an array.
2. Divide the number by 2
3. Repeat the above two steps until the number is greater than zero.
4. Print the array in reverse order now.
or

Example:
If the binary number is 10.
Step 1: Remainder when 10 is divided by 2 is zero. Therefore, arr[0] = 0.
Step 2: Divide 10 by 2. New number is 10/2 = 5.
Step 3: Remainder when 5 is divided by 2 is 1. Therefore, arr[1] = 1.
Step 4: Divide 5 by 2. New number is 5/2 = 2.
Step 5: Remainder when 2 is divided by 2 is zero. Therefore, arr[2] = 0.
Step 6: Divide 2 by 2. New number is 2/2 = 1.
Step 7: Remainder when 1 is divided by 2 is 1. Therefore, arr[3] = 1.
Step 8: Divide 1 by 2. New number is 1/2 = 0.
Step 9: Since number becomes = 0. Print the array in reverse order. Therefore the equivalent
binary number is 1010.

Program:

#include <stdio.h>
#include <math.h>
long convertDecimalToBinary(int n);
int main()
{
int n;
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("%d in decimal = %lld in binary", n, convertDecimalToBinary(n));
return 0;
}
long long convertDecimalToBinary(int n)
{
long binaryNumber = 0;
int remainder, i = 1, step = 1;
while (n!=0)
{
remainder = n%2;
printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n/2);
n /= 2;
binaryNumber += remainder*i;
i *= 10;
}
return binaryNumber;
}

Output:
Enter a decimal number: 19

Step 1: 19/2, Remainder = 1, Quotient = 9

Step 2: 9/2, Remainder = 1, Quotient = 4

Step 3: 4/2, Remainder = 0, Quotient = 2

Step 4: 2/2, Remainder = 0, Quotient = 1

Step 5: 1/2, Remainder = 1, Quotient = 0

19 in decimal = 10011 in binary


c) AIM: Write a C program to check whether the given number is Armstrong number or
not.
Algorithm:
Step 1: Input a number from user. Store it in some variable say num. Make a temporary copy of
the value to some another variable for calculation purposes, say originalNum = num. Count total
digits in the given number, store result in a variable say digits.
Step 2: Initialize another variable to store the sum of power of its digits ,say sum = 0.
Step 3: Run a loop till num > 0. The loop structure should look like while(num > 0).
Step 4: Inside the loop, find last digit of num. Store it in a variable say lastDigit = num % 10.
Step 5: Now comes the real calculation to find sum of power of digits. Perform sum = sum +
pow(lastDigit, digits).
Step 6: Since the last digit of num is processed. Hence, remove last digit by performing num =
num / 10.
Step 7: After loop check if(originalNum == sum), then it is Armstrong number otherwise not.

Program:
#include <stdio.h>
#include <math.h>
int main()
{
int originalNum, num, lastDigit, digits, sum;
/* Input number from user */
printf("Enter any number to check Armstrong number: ");
scanf("%d", &num);
sum = 0;
/* Copy the value of num for processing */
originalNum = num;
/* Find total digits in num */
digits = (int) log10(num) + 1;
/* Calculate sum of power of digits */
while(num > 0)
{
/* Extract the last digit */
lastDigit = num % 10;
/* Compute sum of power of last digit */
sum = sum + round(pow(lastDigit, digits));
/* Remove the last digit */
num = num / 10;
}
/* Check for Armstrong number */
if(originalNum == sum)
{
printf("%d is ARMSTRONG NUMBER", originalNum);
}
else
{
printf("%d is NOT ARMSTRONG NUMBER", originalNum);
}
return 0;
}

Output:
Enter any number to check Armstrong number: 371
371 is ARMSTRONG NUMBER

Exercise 5:
a) AIM: Write a C program to interchange the largest and smallest numbers in the given
array.
Algorithm:
Step 1: Input the array elements.
Step 2: Initialize small = large = arr[0]
Step 3: Repeat from i = 2 to n
Step 4: if(arr[i] > large)
large = arr[i]
if(arr[i] < small)
small = arr[i]
Step 5: Print small and large.

Program:
#include<stdio.h>
int main()
{
int a[50],i,n,large,small;
printf(“\nEnter the number of elements : “);
scanf(“%d”,&n);
printf(“\nInput the array elements : “);
for(i=0;i<n;++i)
scanf(“%d”,&a[i]);
large=small=a[0];
for(i=1;i<n;++i)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf(“\nThe smallest element is %d\n”,small);
printf(“\nThe largest element is %d\n”,large);

Output:
Enter the number of elements: 5
Input the array elements: 1 2 3 4 5
The smallest element is 1
The largest element is 5

b) AIM: Write a C program to implement Towers of Hanoi.

Program:
#include <stdio.h>
#include <conio.h>
void toh(int, char, char, char);
void main()
{
int n;
printf("Enter the number of disk : ");
scanf("%d", &n);
printf("Here is sequence of moves of tower of hanoi :\n");
toh(n, 'A', 'C', 'B');
}
void toh(int no, char source, char destination, char spare)
{
if (no == 1)
{
printf("\n move disk 1 from source %c to destination %c", source, destination);
return;
}
toh(no - 1, source, spare, destination);
printf("\n move disk %d from source %c to destination %c", no, source, destination);
toh(no - 1, spare, destination, source);
}

Output:
The out put of tower of hanoi c program is :
Enter the number of disk : 3
Below are sequence of moves of tower of hanoi :
move disk 1 from source A to destination C
move disk 2 from source A to destination B
move disk 1 from source C to destination B
move disk 3 from source A to destination C
move disk 1 from source B to destination A
move disk 2 from source B to destination C
move disk 1 from source A to destination C
Exercise 6:
a) AIM: Write a C program to implement sorting an array of elements.

Algorithm:
STEP 1: START
STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }..
STEP 3: SET temp =0
STEP 4: length= sizeof(arr)/sizeof(arr[0])
STEP 5: PRINT "Elements of Original Array"
STEP 6: SET i=0. REPEAT STEP 7 and STEP 8 UNTIL i<length
STEP 7: PRINT arr[i]
STEP 8: i=i+1.
STEP 9: SET i=0. REPEAT STEP 10 to STEP UNTIL i<n
STEP 10: SET j=i+1. REPEAT STEP 11 UNTIL j<length
STEP 11: if(arr[i]>arr[j]) then
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
STEP 12: j=j+1.
STEP 13: i=i+1.
STEP 14: PRINT new line
STEP 15: PRINT "Elements of array sorted in ascending order"
STEP 16: SET i=0. REPEAT STEP 17 and STEP 18 UNTIL i<length
STEP 17: PRINT arr[i]
STEP 18: i=i+1.
STEP 19: RETURN 0.
STEP 20: END.

PROGRAM:

#include <stdio.h>
int main()
{
//Initialize array
int arr[] = {5, 2, 8, 7, 1};
int temp = 0;
//Calculate length of array arr
int length = sizeof(arr)/sizeof(arr[0]);
//Displaying elements of original array
printf("Elements of original array: \n");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
//Sort the array in ascending order
for (int i = 0; i < length; i++) {
for (int j = i+1; j < length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("\n");

//Displaying elements of array after sorting


printf("Elements of array sorted in ascending order: \n");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output:

Elements of original array:


52871
Elements of array sorted in ascending order:
1 2578

b) AIM: Write a C program to implement matrix addition and multiplication.


Algorithm:
Matrix addition:
Step 1: Input the order of the matrix.
Step 2: Input the matrix 1 elements.
Step 3: Input the matrix 2 elements.
Step 4: Repeat from i = 0 to m
Step 5: Repeat from j = 0 to n
Step 6: mat3[i][j] = mat1[i][j] + mat2[i][j]
Step 7: Print mat3.

Matrix multiplication:
Step 1: Input the order of the matrix1 ( m * n).
Step 2: Input the order of matrix2 (p * q).
Step 3: Input the matrix 1 elements.
Step 4: Input the matrix 2 elements.
Step 5: Repeat from i = 0 to m
Step 6: Repeat from j = 0 to q
Step 7: repeat from k = 0 to p
Step 8: sum=sum+ mat1[c][k] * mat2[k][d];
Step 9: mat3[c][d]=sum
Step 10: Print mat3.

Program:
#include <stdio.h>
int main()
{
int m, n;
scanf(“%d %d”,&m,&n);
int i, j;
int mat1[m][n], mat2[m][n], mat3[m][n];
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat1[i][j]);
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat2[i][j]);
}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
}

Output:
2 2 (order of the matrix)
1 2 3 4 (matrix 1 elements)
2 3 4 5 (matrix 2 elements)
3 5 (resultant matrix)
79
Exercise 7:
c) AIM: To replace a character of a string either from beginning or ending or at a specified
location.

Algorithm:
Step 1: Read the entered string using gets(s) function and store the string into the variable ‘s’.
Step 2: Read the character which we want to replace all its occurrences in the string and store in
the variable c1.
Step 3: Read the character by which we replace all occurrences of the element, store in the
variable c2.
Step 4: The for loop iterates through the string until the last character of the string becomes to
null. replace each occurrence of the character c1 with c2.

Step 5: Print the string after replacing all occurrences of the character with another character in
the string.

Program:
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000],c1,c2;
int i;
printf("Enter the string : ");
gets(s);
printf("Enter a character replace: ");
c1=getchar();
getchar();
printf("\nEnter character to replace with %c : ",c1);
c2=getchar();
printf("\n before replace:%s",s);
for(i=0;s[i];i++)
{
if(s[i]==c1)
{
s[i]=c2;
}
}
printf("\nafter replace:%s",s);
return 0;
}

Output:

Enter the string: hello world


Enter a character replace: l
Enter the string: hello world
Enter a character replace: o
Enter character to replace with o : 0
before replace: hello world
after replace:hell0 w0rld
Exercise 8:

AIM: Write a C program that uses functions to perform the following operations using
Structure:
a. Reading a complex number
b. Writing a complex number
c. Addition of two complex numbers
d. Multiplication of two complex numbers

Program:
#include <stdio.h>
typedef struct complex {
float real;
float imag;
} complex;
complex add(complex n1, complex n2);
int main() {
complex n1, n2, result;
printf("For 1st complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);
result = add(n1, n2);
printf("Sum = %.1f + %.1fi", result.real, result.imag);
return 0;
}
complex add(complex n1, complex n2) {
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return (temp);
}

Output:
For 1st complex number
Enter the real and imaginary parts: 2.1
-2.3
For 2nd complex number
Enter the real and imaginary parts: 5.6
23.2
Sum = 7.7 + 20.9i
Exercise 9:
AIM: Write a C program for the following string operations without using the built-in
functions.
a. To concatenate two strings
b. To append a string to another string
c. To compare two strings

Given two strings str1 and str2, the task is to write a C Program to concatenate these two strings
without using the strcat() function

Examples:

Input: str1 = "hello", str2 = "world"


Output: helloworld

Input: str1 = "Geeks", str2 = "World"


Output: GeeksWorld

Program:
#include <stdio.h>
int main()
{
// Get the two Strings to be concatenated
char str1[100] = "Geeks", str2[100] = "World";
// Declare a new Strings
// to store the concatenated String
char str3[100];
int i = 0, j = 0;
printf("\nFirst string: %s", str1);
printf("\nSecond string: %s", str2);
// Insert the first string in the new string
while (str1[i] != '\0') {
str3[j] = str1[i];
i++;
j++;
}
// Insert the second string in the new string
i = 0;
while (str2[i] != '\0') {
str3[j] = str2[i];
i++;
j++;
}
str3[j] = '\0';
// Print the concatenated string
printf("\nConcatenated string: %s", str3);
return 0;
}

Output:
First string: Geeks
Second string: World
Concatenated string: GeeksWorld
Exercise 10:
a) AIM: Write a C program to find the number of characters in a given string including
and excluding spaces.

Algorithm:
Step 1: Define a string.
Step 2: Define and initialize a variable count to 0.
Step 3: Iterate through the string till the end and for each character except spaces, increment the
count by 1.
Step 4: To avoid counting the spaces check the condition i.e. string[i] != ' '.

Program:
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "The best of both worlds";
int count = 0;
//Counts each character except space
for(int i = 0; i < strlen(string); i++) {
if(string[i] != ' ')
count++;
}
//Displays the total number of characters present in the given string
printf("Total number of characters in a string: %d", count);
return 0;
}

Output:
Total number of characters in a string: 19

b) AIM: Write a C program to copy the contents of one string to another string without
using string handling functions.
Program:
#include <stdio.h>
int main()
{
int c = 0;
char s[1000], d[1000] = "What can I say about my programming skills?";
printf("Before copying, the string: %s\n", d);
printf("Input a string to copy\n");
gets(s);
while (s[c] != '\0') {
d[c] = s[c];
c++;
}
d[c] = '\0';
printf("After copying, the string: %s\n", d);
return 0;
}
Output :

Before copying, the string: What can I say about my programming skills?
Input a string to copy
My programming skills are improving.
After copying, the string: My programming skills are improving.

c) AIM: Write a C program to find whether a given string is palindrome or not.

Algorithm:
Step 1: If the original string is equal to reverse of that string, then the string is said to be a
palindrome.
Step 2: Read the entered string using gets(s).
Step 3: Calculate the string length using string library function strlen(s) and store the length
into the variable n.
Step 4: i=0,c=0.
Compare the element at s[i] with the element at s[n-i-1].If both are equal then increase the c
value.
Compare the remaining characters by increasing i value up to i<n/2.
Step 5: If the number of characters compared is equal to the number of characters matched then
the given string is the palindrome.

Program:
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000];
int i,n,c=0;
printf("Enter the string : ");
gets(s);
n=strlen(s);
for(i=0;i<n/2;i++)
{
if(s[i]==s[n-i-1])
c++;
}
if(c==i)
printf("string is palindrome");
else
printf("string is not palindrome");
return 0;
}

Output:

Enter the string: WELCOME


before reverse = WELCOME
after reverse = EMOCLEW
Exercise 11:
a) AIM: Write a C program using recursion for the following:
a. To display sum of digits of a given number
b. To find the factorial of a given integer
c. To find the GCD (Greatest Common Divisor) of two given integers.
d. To find Fibonacci sequence.

Program:
#include <stdio.h>
int sum (int a);
int main()
{
int num, result;

printf("Enter the number: ");


scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}

int sum (int num)


{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}

Output :
Enter the number: 2345
Sum of digits in 2345 is 14

b) AIM: To find the factorial of a given integer

Program:
#include<stdio.h>
int find_factorial(int);
int main()
{
int num, fact;
//Ask user for the input and store it in num
printf("\nEnter any integer number:");
scanf("%d",&num);
//Calling our user defined function
fact =find_factorial(num);
//Displaying factorial of input number
printf("\nfactorial of %d is: %d",num, fact);
return 0;
}
int find_factorial(int n)
{
//Factorial of 0 is 1
if(n==0)
return(1);

//Function calling itself: recursion


return(n*find_factorial(n-1));
}
Output:

Enter any integer number: 4


factorial of 4 is: 24

c) AIM: To find the GCD (Greatest Common Divisor) of two given integers.

Program:
#include<stdio.h>
// recursive function to find gcd of two number
int gcd(int a, int b)
{
if(b!=0)
return gcd(b, a%b); // general case
else
return a; // base case
}
int main()
{
int n1, n2, result;
printf("Enter two numbers: ");
scanf("%d %d",&n1,&n2);
result = hcf(n1,n2);
printf("GCD of %d and %d = %d",n1,n2,result);
return 0;
}

Output:

Enter two numbers: 48 18


GCD of 48 and 18 = 6
Enter two numbers: 50 75
GCD of 50 and 75 = 25

d) AIM: To find Fibonacci sequence.


Program:
#include<stdio.h>
int fibonacci(int);
int main(void)
{
int terms;
printf("Enter terms: ");
scanf("%d", &terms);
for(int n = 0; n < terms; n++)
{
printf("%d ", fibonacci(n));
}
return 0; // return 0 to operating system
}
int fibonacci(int num)
{
//base condition
if(num == 0 || num == 1)
{
return num;
}
else
{
// recursive call
return fibonacci(num-1) + fibonacci(num-2);
}
}

Output:
Enter terms: 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Exercise 12:
a) AIM: Write a C program to reverse a string using pointers.
Program:
#include <stdio.h>
#include <conio.h>
void main()
{
char *s;
int len,i;
clrscr();
printf("\nENTER A STRING: ");
gets(s);
len=strlen(s);
printf("\nTHE REVERSE OF THE STRING IS:");
for(i=len;i>=0;i--)
printf("%c",*(s+i));
getch();
}

Output:
ENTER A STRING : lab
THE REVERSE OF THE STRING IS : bal

b) AIM: Write a C program to compare two 2D arrays using pointers.


Program:
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
void compare(int *a1, int *a2, int n)
{
int i, flag = 0;
for(i = 0; i < n; i++)
{
if(*a1 != *a2)
{
flag = 1;
break;
}
a1++;
a2++;
}
if(flag == 1)
printf("\nBoth arrays are not equal");
else
printf("\nBoth arrays are equal");
}
int main(int argc, char **argv)
{
int a1[10], a2[10];
int n, i;
printf("Enter a number between 1 and 10: ");
scanf("%d", &n);
printf("Enter %d numbers for array 1: ", n);
for(i = 0; i < n; i++)
scanf("%d", &a1[i]);
printf("Enter %d numbers for array 2: ", n);
for(i = 0; i < n; i++)
scanf("%d", &a2[i]);
compare(a1, a2, n);
getch();
return 0;
}

Output:
Enter a number between 1 and 10: 5
Enter 5 numbers for array 1: 1 4 5 2 3
Enter 5 numbers for array 2: 2 3 1 4 5

Both arrays are not equal

c) AIM: Write a C program consisting of Pointer based function to exchange value of two
integers using passing by address.

Program:
# include < stdio.h >
int main( )
{
int a, b, temp ;
int *p1, *p2 ;
printf(" Enter the first number : ") ;
scanf("%d ",& a) ;
printf("\n Enter the second number : ") ;
scanf("%d ",& b) ;
printf("\n Two Number before swapping :%d, %d ",*p1, *p2) ;
temp = *p1 ;
*p1 = *p2 ;
*p2 = temp ;
printf("\n Two Number after swapping :%d, %d ",*p1, *p2) ;
return ( 0 );
}

Output:
Enter the first number : 10
Enter the second number : 15
Two Number before swapping :10, 15
Two Number after swapping :15, 10
Exercise 13:
a) AIM: Write a C program to find both the largest and smallest number of an array of
integers using call by value and call by reference.
Program:
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int i, max, min, size;
/* Input size of the array */
printf("Enter size of the array: ");
scanf("%d", &size);
/* Input array elements */
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/* Assume first element as maximum and minimum */
max = arr[0];
min = arr[0];
/*
* Find maximum and minimum in all array elements.
*/
for(i=1; i<size; i++)
{
/* If current element is greater than max */
if(arr[i] > max)
{
max = arr[i];
}
/* If current element is smaller than min */
if(arr[i] < min)
{
min = arr[i];
}
}
/* Print maximum and minimum element */
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
return 0;
}

Output:
Enter size of the array: 10
Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10
Maximum element = 100
Minimum element = -10
b) AIM: Write a C program to implement student details using Structures.
Program:
#include <stdio.h>
struct student {
char firstName[50];
int roll;
float marks;
} s[5];
int main() {
int i;
printf("Enter information of students:\n");
// storing information
for (i = 0; i < 5; ++i) {
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", s[i].firstName);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n\n");
// displaying information
for (i = 0; i < 5; ++i) {
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].firstName);
printf("Marks: %.1f", s[i].marks);
printf("\n");
}
return 0;
}

Output:
Enter information of students:
For roll number1,
Enter name: Tom
Enter marks: 98
For roll number2,
Enter name: Jerry
Enter marks: 89
.
.
.
Displaying Information:

Roll number: 1
Name: Tom
Marks: 98

Exercise 14:
a) AIM: Write a C program which copies one file to another.
Program:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
char ch;// source_file[20], target_file[20];
FILE *source, *target;
char source_file[]="x1.txt";
char target_file[]="x2.txt";
source = fopen(source_file, "r");
if (source == NULL) {
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
target = fopen(target_file, "w");
if (target == NULL) {
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(source)) != EOF)
fputc(ch, target);
printf("File copied successfully.\n");
fclose(source);
fclose(target);
return 0;
}
Input:
sourcefile = x1.txt
targefile = x2.txt
Output: File copied successfully.

b) AIM: Write a C program to count the number of characters and number of lines in a file.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
printf("Enter source file path: ");
scanf("%s", path);
file = fopen(path, "r");
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
if (ch == '\n' || ch == '\0')
lines++;
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
if (characters > 0)
{
words++;
lines++;
}
printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
fclose(file);
return 0;
}

Suppose if data\file3.txt contains


I love programming.
Working with files in C programming is fun.
I am learning C programming at Codeforwin.

Output:
Enter source file path: data\file3.txt
Total characters = 106
Total words = 18
Total lines =3

c) AIM: Write a C program to merge two files into a third file. The names of the files must
be entered using command line arguments.
Algorithm:
Step 1: Start
Step 2: open a empty file in write mode.
Step 3: if it is not end of file
Step 4: write data into that file.
Step 5: close the write mode operation
Step 6: repeat the above process for second file.
Step 7: now use concatenation operation to combine the files.
Step 8: the contents of the file will be displayed in the third file.
Step 9: Stop

Program:
#include<stdio.h>
void concatenate(FILE *fp1, FILE *fp2, char *argv[], int argc);
int main(int argc, char *argv[]){
FILE *fp1, *fp2;
concatenate(fp1, fp2, argv, argc);
return 0;
}
void concatenate(FILE *fp1, FILE *fp2, char **argv, int argc){
int i, ch;
fp2 = fopen("files", "a");
for(i = 1; i < argc - 1; i++){
fp1 = fopen(argv[i], "r");
while((ch = getc(fp1)) != EOF)
putc(ch, fp2);
}
}

Output:
File1:
studentboxoffice.in.
File2:
This is Computer Programming Lab.
File 3:
studentboxoffice.in. This is Computer Programming Lab.

Exercise15:
AIM: Write a C program to implement Different Storage classes.
a. Auto
b. Static
c. Register
d. External
Program:
#include <stdio.h>

// declaring the variable which is to be made extern


// an initial value can also be initialized to x
int x;

void autoStorageClass()
{
printf("\nDemonstrating auto class\n\n");

// declaring an auto variable (simply


// writing "int a=32;" works as well)
auto int a = 32;

// printing the auto variable 'a'


printf("Value of the variable 'a'" " declared as auto: %d\n", a);
printf("--------------------------------");
}
void registerStorageClass()
{
printf("\nDemonstrating register class\n\n");
// declaring a register variable
register char b = 'G';
// printing the register variable 'b'
printf("Value of the variable 'b'" " declared as register: %d\n", b);
printf("--------------------------------");
}
void externStorageClass()
{
printf("\nDemonstrating extern class\n\n");

// telling the compiler that the variable


// x is an extern variable and has been
// defined elsewhere (above the main
// function)
extern int x;
// printing the extern variables 'x'
printf("Value of the variable 'x'"
" declared as extern: %d\n",
x);
// value of extern variable x modified
x = 2;

// printing the modified values of


// extern variables 'x'
printf("Modified value of the variable 'x'"
" declared as extern: %d\n",
x);

printf("--------------------------------");
}
void staticStorageClass()
{
int i = 0;
printf("\nDemonstrating static class\n\n");
// using a static variable 'y'
printf("Declaring 'y' as static inside the loop.\n"
"But this declaration will occur only"
" once as 'y' is static.\n"
"If not, then every time the value of 'y' "
"will be the declared value 5"
" as in the case of variable 'p'\n");
printf("\nLoop started:\n");
for (i = 1; i < 5; i++) {
// Declaring the static variable 'y'
static int y = 5;
// Declare a non-static variable 'p'
int p = 10;
// Incrementing the value of y and p by 1
y++;
p++;
// printing value of y at each iteration
printf("\nThe value of 'y', "
"declared as static, in %d "
"iteration is %d\n",
i, y);
// printing value of p at each iteration
printf("The value of non-static variable 'p', "
"in %d iteration is %d\n",
i, p);
}
printf("\nLoop ended:\n");
printf("--------------------------------");
}
int main()
{
printf("A program to demonstrate"
" Storage Classes in C\n\n");
// To demonstrate auto Storage Class
autoStorageClass();
// To demonstrate register Storage Class
registerStorageClass();
// To demonstrate extern Storage Class
externStorageClass();

// To demonstrate static Storage Class


staticStorageClass();
// exiting
printf("\n\nStorage Classes demonstrated");
return 0;
}

Output:
A program to demonstrate Storage Classes in C
Demonstrating auto class
Value of the variable ‘a’ declared as auto: 32
——————————–
Demonstrating register class
Value of the variable ‘b’ declared as register: 71
——————————–
Demonstrating extern class
Value of the variable ‘x’ declared as extern: 0
Modified value of the variable ‘x’ declared as extern: 2
——————————–
Demonstrating static class
Declaring ‘y’ as static inside the loop.
But this declaration will occur only once as ‘y’ is static.
If not, then every time the value of ‘y’ will be the declared value 5 as in the case of variable ‘p’
Loop started:
The value of ‘y’, declared as static, in 1 iteration is 6
The value of non-static variable ‘p’, in 1 iteration is 11
The value of ‘y’, declared as static, in 2 iteration is 7
The value of non-static variable ‘p’, in 2 iteration is 11
The value of ‘y’, declared as static, in 3 iteration is 8
The value of non-static variable ‘p’, in 3 iteration is 11
The value of ‘y’, declared as static, in 4 iteration is 9
The value of non-static variable ‘p’, in 4 iteration is 11
Loop ended:
——————————–
Storage Classes demonstrated

You might also like