Problem 6.1: Given a number, write a program using while loop to reverse the digits of the number.For example ,the number
12345
should be written as
54321.
Solution: #include <stdio.h>
int main()
{
int n;
printf(“enter your number to revice\n”);
scanf(“%d”,&n);
printf(“reverse of your number %d is : “,n);
while(n!=0)
{
printf(“%d”,n%10);
n=n/10;
}
printf(“\n”);
}
Problem 6.2: The factorial of an integer m is the product of consecutive integers from 1 to m. That is, factorial m=m!=m x (m-1) x …….. x 1.
Write a program that computes and prints a lable of factorials for any given m.
Solution: #include <stdio.h>
int main()
{
int m,i,f=1;
printf(“enter the number=\n”);
scanf(“%d”,&m);
for(i=m; i>=1; i–)
{
f=f*i;
}
printf(“Factorial=%d\n”,f);
}
Problem 6.3: Write a program to compute the sum of the digits of a given integer number.
Solution: #include<stdio.h>
void main()
{
int n,digit,sum=0,temp;
printf(“enter your number \n”);
scanf(“%d”,&n);
temp=n;
while(n!=0)
{
digit=n%10;
sum=sum+digit;
n=n/10;
}
printf(“sum of all digit %d is: %d\n”,temp,sum);
}
Problem 6.4: The numbers in the sequence
1 1 2 3 5 8 13 21 ………………
Solution: #include <stdio.h>
int main()
{
int i, n, a = 0, b = 1, c,sum=0;
printf(“Enter the number: “);
scanf(“%d”, &n);
printf(“Fibonacci Series is till %d: “,n);
for (i = 1; i <= n; i++)
{
sum=sum+a;
printf(“%d “,a );
c = a + b;
a = b;
b = c;
}
printf(“\nsum of this series is :%d\n”,sum);
return 0;
}
Problem 6.5: Rewrite a program of the example 6.1 using the for statement.
Solution: #include <stdio.h>
int main()
{
int i,n;
printf(“enter your number to reverce\n”);
scanf(“%d”,&n);
printf(“reverce of %d is :”,n);
for(i=0;n!=0;i++)
{
printf(“%d”,n%10);
n=n/10;
}
return 0;
}
Problem 6.7: write a program to print the following outputs using for loop
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Solution: #include <stdio.h>
int main()
{
int i,j,n;
printf(“enter your num=\n”);
scanf(“%d”,&n);
for(i=1; i<=n; i++)
{
for (j=1; j<=i; j++)
printf(“%d “,i);
printf(“\n”);
}
return 0;
}
Are these exercises from K&R?
LikeLiked by 1 person
Ref. Book: Programming in ANSI C
LikeLike
Ref. Book: Programming in ANSI C
LikeLike