Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
433 views

C Programming (Project)

In this C Programming (Project), Array, structure, string, loops, switch case, if-else, micros and other parts of C programming.

Uploaded by

Design India
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
433 views

C Programming (Project)

In this C Programming (Project), Array, structure, string, loops, switch case, if-else, micros and other parts of C programming.

Uploaded by

Design India
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

1|Page

C Programming
1. WAP to print the sum and product of digits of an integer.
Sol:
// C program to Print Sum and Product of Digits of an integer

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

int main()
{
int n,n1; //type declaration // n=integer input by user
int dig, sum,pro;

printf("\nEnter any integer number :: "); //user input


scanf("%d",&n);

n1=n;

//Calculating Sum and Product


sum=0;
pro=1;

while(n>0) //condition
{
dig=n%10; //get digit
sum+=dig; //sum of digits
pro*=dig; //product of digits
n=n/10;
}

printf("\nSUM of Digits of Number [ %d ] : [ %d ].\n",n1,sum); //output


printf("\nPRODUCT of digits of Number [ %d ] : [ %d ].\n",n1,pro); //output

getch();
return 0;
}
2|Page

2. WAP to reverse a number.


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

int main()
{
int n, reversedNumber = 0, remainder; //type declaration //n=integer

printf("Enter an integer: "); //user input


scanf("%d", &n);

while(n != 0) //condition
{
remainder = n%10; //digit separation
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}

printf("Reversed Number = %d", reversedNumber); //output

getch();
return 0;
}
3|Page

3. WAP to compute the sum of the first n terms of the following series,
S=1+1/2+1/3+1/4+……
Sol:
/* C Program to find the Sum of Series 1 + 1/2 + 1/3 + 1/4 + ... + 1/N*/
#include<stdio.h>
#include<conio.h>

int main()
{
double number, sum = 0, i; //type declaration

printf("\n enter the number "); //user input


scanf("%lf", &number); //lf=long float
for (i = 1; i <= number; i++) //conditional loop
{
sum = sum + (1 / i);
if (i == 1)
printf("\n 1 +");
else if (i == number)
printf(" (1 / %lf)", i);
else
printf(" (1 / %lf) + ", i);
}
printf("\n The sum of the given series is %.2lf", sum); //output
getch();
return 0;
}
4|Page

4. WAP to compute the sum of the first n terms of the following series,
S =1-2+3-4+5…………….
Sol:
#include<stdio.h>
#include<conio.h>

int series_sum(int n)
{
if (n%2==0)
return (-(n/2));
else
return ((n+1)/2);
}

int main ()
{
int num;
printf("Enter the number of terms : ");
scanf("%d", &num);

series_sum(num);

printf("\The sum of the given series is %d", series_sum(num));

getch();
return 0;
}

1-2+3-4+5
5|Page

5. Write a function that checks whether a given string is Palindrome or not. Use
this function to find whether the string entered by user is Palindrome or not.
Sol:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main ()
{
char string1 [20];
int i, length; //type declaration
int h=0;
printf("Enter a string : "); //user input
scanf("%s", string1);
length = strlen (string1);
for(i=0; i<length; i++) //conditional loop
{
if ( string1[i] != string1[length-i-1])
{
h=1;
break;
}
}
if(h)
printf("%s is not a palindrome", string1);
else
printf("%s is a palindrome", string1); //output

getch ();
return 0;
}
6|Page

6. Write a function to find whether a given no. is prime or not. Use the same to
generate the prime numbers less than 100.
Sol:
//find whether a given no. is prime or not
#include <stdio.h>
#include<conio.h>
int main()
{
int n, i, flag = 0; //flag = Boolean variable
printf("Enter a positive integer: "); //user input
scanf("%d", &n);
for(i = 2; i <= n/2; ++i) //conditional loop
{
// condition for nonprime number
if(n%i == 0)
{
flag = 1; //if the number is even then flag is set to 1 (true)
break;
}
}
if (n == 1)
{
printf("1 is neither a prime nor a composite number.");
}
else
{
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}

return 0;
}
7|Page

//Generate the prime numbers less than 100


#include <stdio.h>
#include <conio.h>
int checkPrimeNumber (int n);
int main()
{
int n1, n2=100, i, flag;
printf("Enter an integer: ");
scanf("%d", &n1);
printf("Prime numbers between %d and %d are : ", n1, n2);
for (i=n1+1; i<n2; ++i)
{
flag = checkPrimeNumber(i);
if(flag == 1) //if the number is even then flag is set to 1 (true)
printf("%d", i);
}
getch();
return 0;
}
int checkPrimeNumber (int n)
{
int j, flag=1;
for(j=2; j<=n/2; ++j)
{
if (n%j == 0)
{
flag = 0;
break;
}
}
return flag;
}
8|Page

7. WAP to compute the factors of a given number.


Sol:
#include <stdio.h>
#include<conio.h>
int main()
{
int i, num;

/* Input number from user */


printf("Enter any number to find its factor: "); //user input
scanf("%d", &num);

printf("All factors of %d are: \n", num);

/* Iterate from 1 to num */


for(i=1; i<=num; i++)
{
// If num is exactly divisible by i
// Then i is a factor of num

if(num % i == 0)
{
printf("%d, ",i);
}
}

getch();
return 0;
}
9|Page

8. Write a macro that swaps two numbers. WAP to use it.


Sol.

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

// Define macro to swap two numbers


#define SWAP(x, y) (x ^= y ^= x ^= y)

int main()
{
int num1, num2;

// Input two numbers from users

printf("Enter any two number to swap: ");


scanf("%d%d", &num1, &num2);
printf("Values before swapping\n");
printf("num1 = %d, num2 = %d\n\n", num1, num2);
SWAP(num1, num2);
printf("Values after swapping\n");
printf("num1 = %d, num2 = %d\n", num1, num2);

getch ();
return 0;
}

Value before swapping


num1 = 3, num2 = 4

Value after swapping


num1 = 4, num2 = 3
10 | P a g e

9. WAP to print a triangle of stars as follows (take number of lines from user):
*
***
*****
*******
Sol:
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j,spc,rows,k;
printf("Input number of rows : "); //user input
scanf("%d",&rows);
spc=rows+4-1;
for(i=1;i<=rows;i++)
{
for(k=spc;k>=1;k--)
{
printf(" ");
}

for(j=1;j<=i;j++)
printf("* ");
printf("\n");
spc--;
}
getch ();
return 0;
}

*
***
*****
*******
11 | P a g e

10. WAP to perform following actions on an array entered by the user:


i) Print the even-valued elements
ii) Print the odd-valued elements
iii) Calculate and print the sum and average of the elements of array
iv) Print the maximum and minimum element of array
v) Remove the duplicates from the array
vi) Print the array in reverse order
The program should present a menu to the user and ask for one of the options.
The menu should also include options to re-enter array and to quit the program.
Sol:

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

int main()
{
char ch;
do
{
int n,sum=0,count=0;
float avg=0.0;
int b[100]; //integer array
printf("Enter the size of the array:");
scanf("\n%d",&n); //taking input for size
int arr[100];

printf("Enter the array elements:");

int i,j;
for(i=0;i<n;i++)
{
scanf("\n%d",&arr[i]); //taking input for array elements
}
int max=arr[0],min=arr[0];
printf("\nEnter 1. to print even valued element");
printf("\nEnter 2. to print odd valued element");
12 | P a g e

printf("\nEnter 3. to calculate sum and average of elements");


printf("\nEnter 4. to print max and min elements of array");
printf("\nEnter 5. to to remove duplicate elements of array");
printf("\nEnter 6. to print array in reverse order");
printf("\nEnter a number");
scanf("\n%d",&j);
switch (j)
{ //beginning of switch block
case 1: //to print even valued elements

printf("\nEven valued elements are:");


for(i=0;i<n;i++)
{
if(arr[i]%2==0) //checking for even valued elements
{
printf("\n%d",arr[i]);
}
}
break;

case 2: //to print odd valued elements

printf("\nOdd valued elements are:");


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

case 3: //to calculate sum and average

for(i=0;i<n;i++)
{
13 | P a g e

sum=sum+arr[i]; //calculating sum of all the elements


}
avg=(sum/n); //calculating average
printf("The sum is: %d",sum);
printf("The avg is: %f",avg);
break;

case 4: //to find maximum and minimum elements

for(i=1;i<n;i++)
{
if (arr[i]>max) //checking for maximum elements
{
max=arr[i]; //storing maximum elements
}
if (arr[i]<min) //checking minimum elements
{
min=arr[i]; //stroring minimum elements
}
}
printf("\n The maximum element is; %d",max);
printf("\n The minimum element is; %d",min);
break;

case 5: //to remove duplicate elements

for(i=0;i<n;i++)
{
for(j=0;j<count;j++)
{
14 | P a g e

if(arr[i]==b[j])
break;
}
if(j==count)
{
b[count]=arr[i];
count++;
}
}
printf("\nArray after removing duplicate elemnts is:");
for(i=0;i<count;i++)
{
printf("\n%d",b[i]);
}
break;

case 6: //to print array in reverse order


printf("\nArray in reverse order is:");

for(i=(n-1);i>=0;i--)
{
printf("\n%d",arr[i]);
}
break;
default:
printf("\nEnter a valid no.");
break;
}
printf("\n Do you want to continue:");
printf("\n Enter Y to continue and N to stop:");
scanf("\n%c",&ch);
}
while(ch=='Y'|| ch=='y');
return 0;

}
15 | P a g e

Enter the size of the array: 4


Enter the array elements: 1 5 3 0

Enter your choice : Enter 1 Even valued elements are : 0

Enter your choice : Enter 2 Odd in the array are : 1 5 3

The sum of element : 9


Enter your choice : Enter 3
The average of element : 2.25

Minimum of array is : 0
Enter your choice : Enter 4
Maximum of array is : 5

Enter your choice : Enter 5


Array obtained after removing duplicate elements : 1 5 3 0
Enter array : 1 5 5 3 0

Enter your choice : Enter 6 Reverse of the Array is : 0 3 5 1


16 | P a g e

11. WAP that prints a table indicating the number of occurrences of each
alphabet in the text entered as command line arguments.
Sol:

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

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


{
if ( argc != 2 ) //argc should be 2 for correct execution
{
//We print argv[0] assuming it is the program name
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );
//fopen returns 0, the NULL pointer, on failure
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
//read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned.
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
fclose( file );
}
}
}
17 | P a g e

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


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

void swap(int *x,int *y) // swapping function


{
int t;
t= *x;
*x= *y; //swapping contents using address
*y= t;
}
int main()
{ // main
int num1,num2; //declaring data variables
printf("Enter the value of num1: ");
scanf("%d",&num1); //taking input for 1st number
printf("Enter the value of num2: ");
scanf("%d",&num2); //taking input for 2nd number
printf("Before swapping: num1 is: %d, num2 is %d\n ",num1,num2);
swap(&num1,&num2); //passsing address of both variables
printf("After swapping: num1 is: %d, num2 is %d\n ",num1,num2);
getch();
return 0;
}

Enter the value of num1 : 2 Before swapping: num1 is: 2, num2 is 3


Enter the value of num2 : 3 After swapping: num1 is: 3, num2 is 2
18 | P a g e

13. Write a program in which a function is passed address of two variables


and then alter its contents.
Sol:
#include <stdio.h>

#include <conio.h>

void swap(int *, int *); //function with pointer variables

int main()

int a=10,b=20;

swap(&a,&b); //passing address of variables

printf("a=%d b=%d\n",a,b); //printing modified content

return 0;

getch();

void swap(int *x, int*y) //swapping function

int t;

t=*x; // swapping the addresses of variables

*x=*y;

*y=t;

a = 10, b = 20 a = 20, b = 10
19 | P a g e

14. 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 the circumference of
the circle and displays the value of area and circumference from the main()
function.
Sol:
#include<stdio.h>
#include<conio.h>
float area(float); //declaring the function
float cf(float);
int main()
{ //beginning of main
float r;
printf("Enter the radius of the circle : ");
scanf("\n %f",&r); //taking input for radius
float ar=area(r); //passing the radius to area function and
storing in a variable
float cr=cf(r);
printf("\nThe area is %f" ,ar);
printf("\n");
printf("\nThe perimeter is %f ",cr) ;
return 0;
getch();
}
float area(float c) //function to calculate area
{
return(3.14*c*c);
}
float cf(float d) //function to calculate circumference
{
return(2*3.14*d);
}

Enter the radius of the The area is 113.040001


circle : 6 The perimeter is 37.680000
20 | P a g e

15. Write a program to find sum of n elements entered by the user. To write
this program, allocate memory dynamically using malloc() / calloc() functions
or new operator.
Sol:
#include<stdio.h>
#include<stdlib.h>
#include <conio.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements:");
scanf("\n%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //Allocating memory dynamically
//If memory not allocated
if(ptr==NULL)
{
printf("\nMemory not allocated");
exit(0);
}
printf("\nEnter the elements:");
for(i=0;i<n;i++)
{
scanf("\n%d",ptr+i); //taking input
sum+=*(ptr+i); // calculating and storing sum
}
printf("\nThe sum is %d",sum);
return 0;
}

Enter the elements: 4 5 3 2 8 9 6 2 5 7


Enter the number of elements: 10
The Sum is : 51
21 | P a g e

16. Write a menu driven program to perform following operations on strings:


a) Show address of each character in string
b) Concatenate two strings without using strcat function.
c) Concatenate two strings using strcat function.
d) Compare two strings
e) Calculate length of the string (use pointers)
f) Convert all lowercase characters to uppercase
g) Convert all uppercase characters to lowercase
h) Calculate number of vowels
i) Reverse the string
Sol:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
int choise;
int i,j;
printf("Enter 1 to Show address of each character in string.\n");
printf("Enter 2 to Concatenate two strings without using strcat function.\n");
printf("Enter 3 to Concatenate two strings using strcat function.\n");
printf("Enter 4 to Compare two strings.\n");
printf("Enter 5 to Calculate length of the string (use pointers).\n");
printf("Enter 6 to Convert all lowercase characters to uppercase.\n");
printf("Enter 7 to Convert all uppercase characters to lowercase.\n");
printf("Enter 8 to Calculate number of vowels.\n");
printf("Enter 9 to Reverse the string.\n");
printf("\nEnter your choice\n");
scanf("%d",&choise);
switch(choise)
{
case 1:
{
char str[100];
int i = 0;

printf("\n Please Enter any String : ");


scanf("%s", str);

while (str[i] != '\0')


{
printf("The Character at %d Index Position = %c and Address position =
%d \n", i, str[i], &str[i]);
i++;
}
break;
}
22 | P a g e

case 2:
{

char s1[100], s2[100];


printf("Enter First string");
scanf("%s", &s1);
printf("Enter Second string");
scanf("%s", &s2);
for (i = 0; s1[i] != '\0'; ++i)

// concatenating each character of s2 to s1


for (j = 0; s2[j] != '\0'; ++j, ++i)
{
s1[i] = s2[j];
}
// terminating s1 string
s1[i] = '\0';
printf("After concatenation: ");
puts(s1);

break;
}
case 3:
{

char a[100], b[100];

printf("Enter the first string\n");


scanf("%s", a);

printf("Enter the second string\n");


scanf("%s", b);

strcat(a,b);

printf("String obtained on concatenation is %s\n",a);


break;
}
case 4:
{
char a[100], b[100];
printf("Enter the first string\n");
scanf("%s", a);

printf("Enter the second string\n");


scanf("%s", b);

if( strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
23 | P a g e

printf("Entered strings are not equal.\n");


break;
}
case 5:
{
char str[100], *pt;
int i = 0;
printf("Pointer Example Program : Find or Calculate
Length of String \n");
scanf("%s", str);
pt = str;
while (*pt != '\0')
{
i++;
pt++;
}
printf("Length of String : %d", i);
break;
}
case 6:
{
char s[100];
printf("\nEnter a string : ");
scanf("%s", s);

for (i = 0; s[i]!='\0'; i++)


{
if(s[i] >= 'a' && s[i] <= 'z')
{
s[i] = s[i] - 32;
}
}
printf("\nString in Upper Case = %s", s);
break;
}
case 7:
{

char s[100];
printf("\nEnter a string : ");
scanf("%s", s);

for (i = 0; s[i]!='\0'; i++)


{
if(s[i] >= 'A' && s[i] <= 'Z')
{
s[i] = s[i] + 32;
}
}
printf("\nString in Lower Case = %s", s);
24 | P a g e

break;
}
case 8:
{
int c = 0, count = 0;
char s[100];

printf("Input a string\n");
scanf("%s", s);

while (s[c] != '\0')


{
if (s[c] == 'a' || s[c] == 'A' || s[c] == 'e' || s[c] == 'E'
|| s[c] == 'i' || s[c] == 'I' || s[c] =='o' || s[c]=='O' || s[c] == 'u' ||
s[c] == 'U')
count++;
c++;
}

printf("Number of vowels in the string: %d", count);


break;
}
case 9:
{

char s[100];
printf("Enter a string to reverse\n");
scanf("%s", s);
strrev(s);
printf("Reverse of the string: %s\n", s);
break;
}
default:
printf("Wrong choice !!!");
break;
}
getch ();
return 0;
}
25 | P a g e

The character at 0 Index Position = c and address passion =2358892


The character at 1 Index Position = o and address passion =2358893
Enter your choice : The character at 2 Index Position = m and address passion =2358894
Enter 1 The character at 3 Index Position = p and address passion =2358895
Please enter any string: The character at 4 Index Position = u and address passion =2358896
Computer The character at 5 Index Position = t and address passion =2358897
The character at 6 Index Position = e and address passion =2358898
The character at 7 Index Position = r and address passion =2358899
Without using strcat
Enter your choice : Enter 2
Enter First string: computer
After concatenation: computerscience
Enter Second string: Science

Enter your choice : Enter 3 By using strcat


Enter First string: computer
Enter Second string: Science After concatenation: computerscience
Enter your choice : Enter 4
Enter First string: computer Entered String are not equal
Enter Second string: Science

Enter your choice : Enter 5

Pointer Example Program : Find


or calculate the length of
string : computer Length of string : 8
Enter your choice : Enter 6
String in Upper case = COMPUTER
Enter a string : computer
Enter your choice : Enter 7
String in Upper case = computer
Enter a string: COMPUTER

Enter your choice : Enter 8


Numbers of vowels in the string : 3
Input a string : computer

Enter your choice : Enter 9


Reverse of the string : retupmoc
Enter a string to reverse : computer
26 | P a g e

17. Given two ordered arrays of integers, write a program to merge the two-
arrays to get an ordered array.
Sol:
#include<stdio.h>
#include <conio.h>
int main()
{
int arr1[30], arr2[30], res[60];
int i, j, k, n1, n2;
printf("\nEnter no of elements in 1st array :");
scanf("%d", &n1);
for (i = 0; i < n1; i++)
{
scanf("%d", &arr1[i]);
}
printf("\nEnter no of elements in 2nd array :");
scanf("%d", &n2);
for (i = 0; i < n2; i++)
{
scanf("%d", &arr2[i]);
}
i = 0;
j = 0;
k = 0;

// Merging starts
while (i < n1 && j < n2)
{
if (arr1[i] <= arr2[j])
{
res[k] = arr1[i];
i++;
k++;
}
else
{
res[k] = arr2[j];
k++;
j++;
}
}

/* Some elements in array 'arr1' are still remaining


27 | P a g e

where as the array 'arr2' is exhausted */

while (i < n1)


{
res[k] = arr1[i];
i++;
k++;
}

/* Some elements in array 'arr2' are still remaining


where as the array 'arr1' is exhausted */

while (j < n2)


{
res[k] = arr2[j];
k++;
j++;
}
//Displaying elements of array 'res'
printf("\nMerged array is :");
for (i = 0; i < n1 + n2; i++)
printf("%d ", res[i]);
getch();
return 0;
}

Enter no. of elements in 1st array : 5


43216
Merged array is: 4 3 2 1 6 5 6 8
Enter no. of elements in 1st array : 3
568
28 | P a g e

18. WAP to display Fibonacci series (i)using recursion, (ii) using iteration.
Sol:
// Using Recursion

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

int Fibonacci(int); //declaration of the function

int main()
{
int n, i=0, c; //n is the number of terms in fibonacci series

printf("Enter the number of terms");


scanf("%d",&n); //taking input for n
printf("Fibonacci series\n");

for ( c=1 ; c<=n ; c++ ) // loop to print the series


{
printf("%d\t", Fibonacci(i)); //function call
i++;
}

return 0;
}

int Fibonacci(int n) //function to print the Fibonacci series


{
if ( n==0 )
return 0;
else if ( n==1 )
return 1;
else
return ( Fibonacci(n-1)+Fibonacci(n-2) );
}

Enter the number of terms : 5 Fibonacci Series are : 0 1 1 2 3

// Using Iteration

#include<stdio.h>
#include<conio.h>
int main()
{
int n, first = 0, second = 1, next, c;
29 | P a g e

printf("Enter the number of terms\n");


scanf("%d",&n); //taking input for n

printf("First %d terms of Fibonacci series are :-\n",n);

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


{
if ( c <= 1 )
next = c; //updating the value of c into next
else
{
next = first + second; /*adding the value assigned in first
and second and updating it in next*/
first = second; //updating the value of second into first
second = next; //updating the value of next into second
}
printf("%d\t",next); //printing the series
}
getch();
return 0;
}

Enter the number of terms : 5 First 5 terms of Fibonacci Series are : 0 1 1 2 3


30 | P a g e

19. WAP to calculate Factorial of a number (i) using recursion, (ii) using
iteration.
Sol:
//Using Recursion
#include<stdio.h>
#include<conio.h>
long int factorial (int n); //declaration of the function

int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n); //taking value of n from user
printf("Factorial of %d = %ld", n, factorial(n)); //function call
return 0;
}
long int factorial(int n) //function to calculate the factorial
{
if (n>=1)
return n*factorial(n-1);
else
return 1;
}

Enter a positive integer : 4 Factorial of 4 : 24

// Using iteration

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

int main()
{
int c, n, f = 1;

printf("Enter a positive number to calculate its factorial\n");


scanf("%d", &n); //taking value of n from user

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


{
f = f * c; /*multiplying the value assigned in f and c and
updating it in f*/
printf("Factorial of %d is = %d\n", n, f);
}
getch();
return 0;
}

Enter a positive integer : 4 Factorial of 4 is = 24


31 | P a g e

20. WAP to calculate GCD of two numbers (i) with recursion (ii) without
recursion.
Sol:
// Using Recursion
#include <stdio.h>
#include <conio.h>
int hcf (int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2) // recursive function to calculate GCD
{
if (n2 != 0)
return hcf(n2, n1 % n2); /*calculating the highest
common factor*/
else
return n1;
}

Enter two positive integer : 4 2 G.C.D. of 4 and 2 is = 2

#include <stdio.h> // Without Recursion


#include <conio.h>
int main()
{
int n1, n2, i, gcd;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
{
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
getch();
return 0;
}

Enter two positive integer : 4 2 G.C.D. of 4 and 2 is = 2


32 | P a g e

21. Create Matrix class using templates. Write a menu-driven program to


perform following Matrix operations (2-D array implementation):
a) Sum b) Difference c) Product d) Transpose
Sol:
#include <stdio.h>
#include <conio.h>

int main ()
{
int n;
printf("Enter the options Given Below");
printf("\n1. Sum of Matrices\n");
printf("\n2. Difference of Matrices\n");
printf("\n3. Product of Materices\n");
printf("\n4. Transpose of Matrices\n");
scanf("%d", &n);
switch (n)
{
case 1:
{
int r, c, a[100][100];
int b[100][100];
int sum[100][100];
int i, j;
printf("Enter the number of rows (between 1 and 100):");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100):");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
{
for (j = 0; j < c; ++j)
{
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
{
for (j = 0; j < c; ++j)
{
33 | P a g e

printf("Enter element a%d%d: ", i + 1, j + 1);


scanf("%d", &b[i][j]);
}
}
// adding two matrices
for (i = 0; i < r; ++i)
{
for (j = 0; j < c; ++j)
{
sum[i][j] = a[i][j] + b[i][j];
}
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
{
for (j = 0; j < c; ++j)
{
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
break;
}
case 2:
{
int a[3][3],b[3][3],s[3][3],i,j;
printf("Enter Elements for First 3*3 Matrix:\n\n");
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
{
scanf("%d",&a[i][j]);
}
printf("\nFirst Matrix :\n\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("\nEnter Elements for Second 3*3 Matrix: \n\n");
34 | P a g e

for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\nSecond Matrix :\n\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%d ",b[i][j]);
}
printf("\n");
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
s[i][j]=a[i][j]-b[i][j];
}
}
printf("\nDifference Between Matrices :\n\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%3d ",s[i][j]);
}
printf("\n");
}
break;
}

case 3:
{

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
35 | P a g e

printf("enter the first matrix element=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
break;
}

case 4:

{
36 | P a g e

int a[10][10], transpose[10][10], r, c, i, j;


printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
// Assigning elements to the matrix
printf("\nEnter matrix elements:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
// Displaying the matrix a[][]
printf("\nEntered matrix: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}
// Finding the transpose of matrix a
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
// Displaying the transpose of matrix a
printf("\nTranspose of the matrix:\n");
for (i = 0; i < c; ++i)
for (j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
break;
}

default:
printf("Please enter the correct option");
}

getch ();
return 0;
}
OUTPUT:
Enter the options Given Below
1. Sum of Matrices
37 | P a g e

2. Difference of Matrices
3. Product of Materices
4. Transpose of Matrices
Enter-1
Enter the number of rows (between 1 and 100): 3
Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:


Enter element a11: 33
Enter element a12: 34
Enter element a13: 35
Enter element a21: 36
Enter element a22: 37
Enter element a23: 38
Enter element a31: 39
Enter element a32: 40
Enter element a33: 41
Enter elements of 2nd matrix:
Enter element a11: 42
Enter element a12: 43
Enter element a13: 44
Enter element a21: 45
Enter element a22: 46
Enter element a23: 47
Enter element a31: 48
Enter element a32: 49
Enter element a33: 50

Sum of two matrices:


75 77 79

81 83 85

87 89 91
38 | P a g e

22. Copy the contents of one text file to another file, after removing all whitespaces.
Sol:
#include <stdio.h>
#include<conio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);

// Open one file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

printf("Enter the filename to open for writing \n");


scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

// Read contents from file


c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);

fclose(fptr1);
fclose(fptr2);
return 0;
}
39 | P a g e

23. Write a function that reverses the elements of an array in place. The
function must accept only one pointer value and return void.
Sol:
#include<stdio.h>
#include <conio.h>
// Function to reverse arr[] from start to end
void reverseArray(int arr[], int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

// Utility that prints out an array on a line


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);

printf("\n");
}

// Driver function to test above functions


int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
reverseArray(arr, 0, n-1);
printf("Reversed array is \n");
printArray(arr, n);
return 0;
}

Array Element : 1 2 3 4 5 6 Reverse array : 6 5 4 3 2 1


40 | P a g e

24. Write a program that will read 10 integers from user and store them in an
array. Implement array using pointers. The program will print the array
elements in ascending and descending order.
Sol:

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

int main()
{
int a[100],n,i,j;
printf("Array size: ");
scanf("%d",&n);
printf("Elements: ");

for(i=0;i<n;i++)
{
scanf("%d",a+i);
}
for (i = 0; i < n; i++) //Loop for ascending ordering
{
for (j = 0; j < n; j++) //Loop for comparing other values
{
if (a[j] > a[i]) //Comparing other array elements
{
int tmp = a[i]; /*Using temporary variable for storing
last value*/
a[i] = a[j]; //replacing value
a[j] = tmp; //storing last value
}
}
}
printf("\n\nAscending : "); //Printing message
for (i = 0; i < n; i++)//Loop for printing array data after sorting
{
printf(" %d ", a[i]);
}
for (i = 0; i < n; i++) //Loop for descending ordering
{
for (j = 0; j < n; j++) //Loop for comparing other values
{
if (a[j] < a[i]) //Comparing other array elements
{
int tmp = a[i]; /*Using temporary variable for storing
last value*/
a[i] = a[j]; //replacing value
a[j] = tmp; //storing last value
}
}
41 | P a g e

}
printf("\n\nDescending : "); //Printing message
for (i = 0; i < n; i++) /*Loop for printing array data after
sorting*/
{
printf(" %d ", a[i]); //Printing data
}

getch();
return 0; //returning 0 status to system
}

Array Size : 8 Ascending : 2 2 3 4 5 6 8 9


Elements: 4 5 3 2 8 9 6 2 Descending : 9 8 6 5 4 3 2 2

You might also like