C Lab Answers

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 24
At a glance
Powered by AI
The document discusses various algorithms and programs in C language including: printing sum of digits of a number, reversing a string, adding matrices, checking palindromes, factorials, GCD, fibonacci series etc.

To print sum of individual digits: 1) Take input number. 2) Divide it by 10 to extract last digit & store remainder in new variable. 3) Increment sum with remainder. 4) Repeat steps 2-3 until quotient becomes 0.

To reverse a string in C without libraries: 1) Take input string. 2) Use two index variables from beginning and end of string. 3) Swap characters at both indices. 4) Decrement end index and increment beginning index in each loop iteration.

1. Write a program to print sum of individual digits of a given number.

Algorithm:
1. Take the integer as input.
2. Divide the input integer by 10, obtain its remainder and quotient.
3. Increment the new variable with the remainder got at step 2.
4. Repeat the step 2 & 3 with the quotient obtained until the qoutient becomes zero.
5. Print the output and exit.

1. #include <stdio.h>
2.
3. void main()
4. {
5. long num, temp, digit, sum = 0;
6.
7. printf("Enter the number \n");
8. scanf("%ld", &num);
9. temp = num;
10. while (num > 0)
11. {
12. digit = num % 10;
13. sum = sum + digit;
14. num /= 10;
15. }
16. printf("Given number = %ld\n", temp);
17. printf("Sum of the digits %ld = %ld\n", temp, sum);
18. }

Output:
Enter the number
300
Given number = 300
Sum of the digits 300 = 3

Enter the number


16789
Given number = 16789
Sum of the digits 16789 = 31

2. Write a program to reverse a given string without using library


functions.

#include<stdio.h>
#include<string.h>

int main() {
char str[100], temp;
int i, j = 0;

printf("\nEnter the string :");


gets(str);

i = 0;
j = strlen(str) - 1;

while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}

printf("\nReverse string is :%s", str);


return (0);
}

Output :

1 Enter the string : Pritesh


2 Reverse string is : hsetirP

3. Write a program to perform addition of two matrices.

1. #include <stdio.h>
2.
3. int main()
4. {
5. int m, n, c, d, first[10][10], second[10][10], sum[10][10];
6.
7. printf("Enter the number of rows and columns of matrix\n");
8. scanf("%d%d", &m, &n);
9. printf("Enter the elements of first matrix\n");
10.
11. for (c = 0; c < m; c++)
12. for (d = 0; d < n; d++)
13. scanf("%d", &first[c][d]);
14.
15. printf("Enter the elements of second matrix\n");
16.
17. for (c = 0; c < m; c++)
18. for (d = 0 ; d < n; d++)
19. scanf("%d", &second[c][d]);
20.
21. printf("Sum of entered matrices:-\n");
22.
23. for (c = 0; c < m; c++) {
24. for (d = 0 ; d < n; d++) {
25. sum[c][d] = first[c][d] + second[c][d];
26. printf("%d\t", sum[c][d]);
27. }
28. printf("\n");
29. }
30.
31. return 0;
32. }

Output:

4. Write a program to print factorial of a given number using


functions.

1. #include <stdio.h>
2.
3. int main()
4. {
5. int c, n, fact = 1;
6.
7. printf("Enter a number to calculate its factorial\n");
8. scanf("%d", &n);
9.
10. for (c = 1; c <= n; c++)
11. fact = fact * c;
12.
13. printf("Factorial of %d = %d\n", n, fact);
14.
15. return 0;
16.}

Output:

5. Write a program to print GCD of two numbers using non-recursion.

(pending).

6. Write a program to check whether a given string is palindrome or


not.

#include <stdio.h>
#include <string.h>

int main(){
char string1[20];
int i, length;
int flag = 0;

printf("Enter a string:");
scanf("%s", string1);

length = strlen(string1);

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


if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}
}

if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}

Output:

7. Write a program to print factorial of a given number using


recursion.

1. #include <stdio.h>
2. long int multiplyNumbers(int n);
3.
4. int main()
5. {
6. int n;
7. printf("Enter a positive integer: ");
8. scanf("%d", &n);
9. printf("Factorial of %d = %ld", n, multiplyNumbers(n));
10. return 0;
11.}
12.long int multiplyNumbers(int n)
13.{
14. if (n >= 1)
15. return n*multiplyNumbers(n-1);
16. else
17. return 1;
18.}
Output
Enter a positive integer: 6
Factorial of 6 = 720
8. Write a program to print GCD of 2 numbers using recursion.

1. #include <stdio.h>
2. int hcf(int n1, int n2);
3. int main()
4. {
5. int n1, n2;
6. printf("Enter two positive integers: ");
7. scanf("%d %d", &n1, &n2);
8.
9. printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1,n2));
10. return 0;
11. }
12.
13. int hcf(int n1, int n2)
14. {
15. if (n2 != 0)
16. return hcf(n2, n1%n2);
17. else
18. return n1;
19. }

Output

Enter two positive integers: 366


60
G.C.D of 366 and 60 is 6.

9. Write a program to print employee details (empname, empno,


salary) using structures.

#include <stdio.h>

/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};

int main()
{
/*declare structure variable*/
struct employee emp;

/*read employee details*/


printf("\nEnter details :\n");
printf("Name ?:"); gets(emp.name);
printf("ID ?:"); scanf("%d",&emp.empId);
printf("Salary ?:"); scanf("%f",&emp.salary);

/*print employee details*/


printf("\nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);
return 0;
}

Output

Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543

Entered detail is:


Name: Mike
Id: 1120
Salary: 76543.000000

10. Write a program to read contents from a file.

#include <stdio.h>
#include <stdlib.h> // For exit()

int main()
{
FILE *fptr;

char filename[100], c;

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


scanf("%s", filename);

// Open file
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}

// Read contents from file


c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}

fclose(fptr);
return 0;
}
Output:
Enter the filename to open
a.txt
/*Contents of a.txt*/

11. Write a program to count number of lines in a file.


1. #include <stdio.h>
2.
3. int main()
4. {
5. FILE *fileptr;
6. int count_lines = 0;
7. char filechar[40], chr;
8.
9. printf("Enter file name: ");
10. scanf("%s", filechar);
11. fileptr = fopen(filechar, "r");
12. //extract character from file and store in chr
13. chr = getc(fileptr);
14. while (chr != EOF)
15. {
16. //Count whenever new line is encountered
17. if (chr == 'n')
18. {
19. count_lines = count_lines + 1;
20. }
21. //take next character from file.
22. chr = getc(fileptr);
23. }
24. fclose(fileptr); //close file.
25. printf("There are %d lines in %s in a file\n", count_lines, filechar);
26. return 0;
27. }
$ cc pgm49.c
$ a.out
Enter file name: pgm2.c
There are 43 lines in pgm2.c in a file

12. Write a program to read and display 3 students information using


array of structures.

1. #include <stdio.h>
2. struct student
3. {
4. char name[50];
5. int roll;
6. float marks;
7. } s[10];
8.
9. int main()
10. {
11. int i;
12.
13. printf("Enter information of students:\n");
14.
15. // storing information
16. for(i=0; i<10; ++i)
17. {
18. s[i].roll = i+1;
19.
20. printf("\nFor roll number%d,\n",s[i].roll);
21.
22. printf("Enter name: ");
23. scanf("%s",s[i].name);
24.
25. printf("Enter marks: ");
26. scanf("%f",&s[i].marks);
27.
28. printf("\n");
29. }
30.
31. printf("Displaying Information:\n\n");
32. // displaying information
33. for(i=0; i<10; ++i)
34. {
35. printf("\nRoll number: %d\n",i+1);
36. printf("Name: ");
37. puts(s[i].name);
38. printf("Marks: %.1f",s[i].marks);
39. printf("\n");
40. }
41. return 0;
42. }
43.
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
.
.
.

13. Write a program to check whether a given number is palindrome


or not.

1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. int n, num, digit, rev = 0;
7.
8. cout << "Enter a positive number: ";
9. cin >> num;
10.
11. n = num;
12.
13. do
14. {
15. digit = num % 10;
16. rev = (rev * 10) + digit;
17. num = num / 10;
18. } while (num != 0);
19.
20. cout << " The reverse of the number is: " << rev << endl;
21.
22. if (n == rev)
23. cout << " The number is a palindrome.";
24. else
25. cout << " The number is not a palindrome.";
26.
27. return 0;
28. }
Output

Enter a positive number: 12321


The reverse of the number is: 12321
The number is a palindrome.

14. Write a program to perform sum of two numbers using call by


value method.

#include <stdio.h>

long addTwoNumbers(long *, long *);

int main()

long fno, sno, *ptr, *qtr, sum;

printf("\n\n Pointer : Add two numbers using call by reference:\n");

printf("-------------------------------------------------------\n");

printf(" Input the first number : ");

scanf("%ld", &fno);

printf(" Input the second number : ");

scanf("%ld", &sno);

sum = addTwoNumbers(&fno, &sno);

printf(" The sum of %ld and %ld is %ld\n\n", fno, sno, sum);

return 0;

}
long addTwoNumbers(long *n1, long *n2)

long sum;

sum = *n1 + *n2;

return sum;

Copy
Sample Output:

Pointer : Add two numbers using call by reference:


-------------------------------------------------------
Input the first number : 5
Input the second number : 6
The sum of 5 and 6 is 11

15. Write a program to swap two numbers using functions.

#include<stdio.h>

void swap(int *,int *);

int main()

int n1,n2;

printf("\n\n Function : swap two numbers using function :\n");

printf("------------------------------------------------\n");

printf("Input 1st number : ");

scanf("%d",&n1);

printf("Input 2nd number : ");

scanf("%d",&n2);
printf("Before swapping: n1 = %d, n2 = %d ",n1,n2);

//pass the address of both variables to the function.

swap(&n1,&n2);

printf("\nAfter swapping: n1 = %d, n2 = %d \n\n",n1,n2);

return 0;

void swap(int *p,int *q)

//p=&n1 so p store the address of n1, so *p store the value of n1

//q=&n2 so q store the address of n2, so *q store the value of n2

int tmp;

tmp = *p; // tmp store the value of n1

*p=*q; // *p store the value of *q that is value of n2

*q=tmp; // *q store the value of tmp that is the value of n1

Copy
Sample Output:

Function : swap two numbers using function :


------------------------------------------------
Input 1st number : 2
Input 2nd number : 4
Before swapping: n1 = 2, n2 = 4
After swapping: n1 = 4, n2 = 2

16. Write a program to perform arithmetic operations using switch


statement.
#include<stdio.h>
int main()
{
int n,m,t;
char c;
printf("Enter two numbers and operator :\n");
scanf("%d %d %c", &n, &m, &c);

switch(c)
{
case '+' : printf("Addition is : %d", n+m);
break;
case '-' : printf("Substraction is %d", n-m);
break;
case '*' : printf("Multiplication is %d", n*m);
break;
case '/' : printf("Division is %f", (float)n/m);
break;
default : printf("Not valid");
}

getch();
return 0;
}

Output

0
1 Enter two numbers and operator :
228/
3 Division is 0.250000
4
17. Write a program to copy contents of one file to another file.

#include <stdio.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;
}
Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
Contents copied to b.txt

18. Write a program to merge contents of two files to another.

1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. FILE *fs1, *fs2, *ft;
7.
8. char ch, file1[20], file2[20], file3[20];
9.
10. printf("Enter name of first file\n");
11. gets(file1);
12.
13. printf("Enter name of second file\n");
14. gets(file2);
15.
16. printf("Enter name of file which will store contents of the two files\n");
17. gets(file3);
18.
19. fs1 = fopen(file1, "r");
20. fs2 = fopen(file2, "r");
21.
22. if (fs1 == NULL || fs2 == NULL)
23. {
24. perror("Error ");
25. printf("Press any key to exit...\n");
26. exit(EXIT_FAILURE);
27. }
28.
29. ft = fopen(file3, "w"); // Opening in write mode
30.
31. if (ft == NULL)
32. {
33. perror("Error ");
34. printf("Press any key to exit...\n");
35. exit(EXIT_FAILURE);
36. }
37.
38. while ((ch = fgetc(fs1)) != EOF)
39. fputc(ch,ft);
40.
41. while ((ch = fgetc(fs2)) != EOF)
42. fputc(ch,ft);
43.
44. printf("The two files were merged into %s file successfully.\n", file3);
45.
46. fclose(fs1);
47. fclose(fs2);
48. fclose(ft);
49.
50. return 0;
51. }

Download merge files program.

Output of program:
19. Write a program to print largest number from an array of values.

1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. int i, n;
7. float arr[100];
8.
9. cout << "Enter total number of elements(1 to 100): ";
10. cin >> n;
11. cout << endl;
12.
13. // Store number entered by the user
14. for(i = 0; i < n; ++i)
15. {
16. cout << "Enter Number " << i + 1 << " : ";
17. cin >> arr[i];
18. }
19.
20. // Loop to store largest number to arr[0]
21. for(i = 1;i < n; ++i)
22. {
23. // Change < to > if you want to find the smallest element
24. if(arr[0] < arr[i])
25. arr[0] = arr[i];
26. }
27. cout << "Largest element = " << arr[0];
28.
29. return 0;
30. }
Output

Enter total number of elements: 8

Enter Number 1: 23.4


Enter Number 2: -34.5
Enter Number 3: 50
Enter Number 4: 33.5
Enter Number 5: 55.5
Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5

Largest element = 55.5

20. Write a program to print odd numbers from 1 to 100 using FOR
loop.

#include <stdio.h>

int main()
{
int i, n;

/* Input upper limit from user */


printf("Print odd numbers till: ");
scanf("%d", &n);

printf("All odd numbers from 1 to %d are: \n", n);

/* Start loop from 1 and increment it by 1 */


for(i=1; i<=n; i++)
{
/* If 'i' is odd then print it */
if(i%2!=0)
{
printf("%d\n", i);
}
}

return 0;
}
Output:

Print odd numbers till: 100


All odd numbers from 1 to 100 are:
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99

21. Write a program to print odd numbers from 1 to 100 using do-
while loop.
(pending)

22. Write a program to print given number in words using switch case.
(Note: Read number in to a character array or in the form of string.
Example: If input is “123” then output must be ONE TWO THREE).
#include<stdio.h>

int main()

int n,rem=0,sum=0;

printf("enter the no");

scanf("%d",&n);

while(n!=0)

rem=n%10;

sum=sum*10+rem;

n=n/10;

printf("The reverse is %d\n",sum);//just to ensure that the reverse is correct or not

while(sum!=0)

rem=sum%10;

switch(rem)

case 1: printf("One");

break;

case 2: printf("Two");

break;

case 3: printf("Three");

break;

case 4: printf("Four");

break;
case 5: printf("Five");

break;

case 6: printf("Six");

break;

case 7: printf("Seven");

break;

case 8: printf("Eight");

break;

case 9: printf("Nine");

break;

case 10:printf("Ten");

break;

default: printf("please enter valid no ");

sum=sum/10;

return 0;

23. Write a program to print the sum of array elements.

#include <bits/stdc++.h>

// function to return sum of elements


// in an array of size n
int sum(int arr[], int n)
{
int sum = 0; // initialize sum

// Iterate through all elements


// and add them to sum
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}

int main()
{
int arr[] = {12, 3, 4, 15};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Sum of given array is %d", sum(arr, n));
return 0;
}

Output :
Sum of given array is 34

24. Write a program to find length of a given string without using


library functions.

#include<stdio.h>

int main() {
char str[100];
int length;

printf("\nEnter the String : ");


gets(str);

length = 0; // Initial Length

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


length++;

printf("\nLength of the String is : %d", length);


return(0);
}

25. Write a program to check whether a given number is prime or not


using functions.

1. #include <iostream>
2. using namespace std;
3.
4. int checkPrimeNumber(int);
5.
6. int main()
7. {
8. int n;
9.
10. cout << "Enter a positive integer: ";
11. cin >> n;
12.
13. if(checkPrimeNumber(n) == 0)
14. cout << n << " is a prime number.";
15. else
16. cout << n << " is not a prime number.";
17. return 0;
18. }
19. int checkPrimeNumber(int n)
20. {
21. bool flag = false;
22.
23. for(int i = 2; i <= n/2; ++i)
24. {
25. if(n%i == 0)
26. {
27. flag = true;
28. break;
29. }
30. }
31. return flag;
32. }
33.
Output

Enter a positive integer: 23


23 is a prime number.

26. Write a program to print fibonocci series upto given ‘n’ value.

#include <stdio.h>

// Function to print first n Fibonacci Numbers


void printFibonacciNumbers(int n)
{
int f1 = 0, f2 = 1, i;

if (n < 1)
return;

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


{
printf("%d ", f2);
int next = f1 + f2;
f1 = f2;
f2 = next;
}
}
// Driver Code
int main()
{
printFibonacciNumbers(7);
return 0;
}

Output:
1 1 2 3 5 8 13

You might also like