- Write a function that takes as parameter an integer n and returns the largest digit in n.
Example 1: If n = 3091, your function must return 9
Example 2: If n = 1385201, your function must return 8 - Write a main program that asks the user to enter a positive integer number n. Then find and print out the largest digit in n.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
int largest(int n)
{
int max=0;
while(n)
{
if(n%10>max)
max=n%10;
n/=10;
}
return max;
}
void main()
{
int n;
do{
printf("Enter a positive integer: ");
scanf("%d",&n);
}while(n<0);
printf("Largest digit in %d is %d\n", n , largest(n));
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Maximum value in a Binary tree of integers