Input number and print largest and smallest digit in it using for loop in C
for Loop - Question 13
In this question, we will see how to input a number and print the largest and the smallest digit in C programming using for loop. To know more about for loop click on the for loop lesson.
Q13) Write a program in C to input a number and print the largest and the smallest digit present in it using for loop.
Program
#include <stdio.h>
#include <conio.h>
int main()
{
int i,ld=-1,sd=10,n,d;
printf("Enter a number ");
scanf("%d",&n);
for(i=n; i>0; i=i/10)
{
d=i%10;
if(d>ld) // storing the largest digit
{
ld=d;
}
if(d<sd) // storing the smallest digit
{
sd=d;
}
}
printf("Largest Digit = %d\n",ld);
printf("Smallest Digit = %d",sd);
return 0;
}
Output
Enter a number 521964 Largest Digit = 9 Smallest Digit = 1