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 <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i,ld=-1,sd=10,n,d;
cout<<"Enter a number ";
cin>>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;
}
}
cout<<"Largest Digit = "<<ld<<endl;
cout<<"Smallest Digit = "<<sd;
return 0;
}
Output
Enter a number 521964 Largest Digit = 9 Smallest Digit = 1