Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i wrote a program that prints the largest digit of a number

#include <stdio.h>
int main(){
    int num ,  large = 0, rem = 0;
    scanf("%d" , &num);
    while (num > 0) {
                rem = num % 10;

                if (rem > large) {
                        large = rem;
                }

                num = num / 10;
        }

        printf("the biggest digit is %d\n", large);
        return 0;
  }


if working fine but if i input an negative number lets say -432 it prints me 0 , instead of 4. How can i correct that ?

What I have tried:

.........................................
Posted
Updated 18-Nov-22 22:52pm

C++
while (num > 0)

This will fail for numbers less than 0. Convert to an absolute number before testing will fix it:
C++
num = abs(num);
while (num > 0)
 
Share this answer
 
Comments
CPallini 19-Nov-22 5:44am    
5.
Graeme_Grant 19-Nov-22 5:45am    
thanks
Hello
First of all, you should put the WHILE on IF(num>=0), then you should make your number positive in ELSE. for example, I do (num=num-2*(num);) this. that works for me. absolutely you can write this very better with functions.
C++
#include<stdio.h>
int main()
{
    int num,r=0,max=0;
    scanf("%d",&num);
    if(num>=0)
    {
        while(num>0)
        {
            r=num%10;
            if(r>=max)
            {
                max=r;
            }
            num=num/10;
        }
    }
    else
    {
        num=num-2*(num);
        while(num>0)
        {
            r=num%10;
            if(r>=max)
            {
                max=r;
            }
            num=num/10;
        }
    }
    printf("%d",max);
    return 0;
}
 
Share this answer
 
Comments
Dave Kreskowiak 23-Jan-24 10:34am    
Talk about unnecessary duplication of code. Wow.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900