Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the Largest Digit in C++ [duplicate]

Tags:

c++

math

  1. Input a 3-digit integer.
  2. Print the largest digit in the integer (Tip: use % 10 to get the rightmost digit, and / 10 to remove the rightmost digit).
Input: 173
Expected Output: 7

We were given this activity 2 days old and still couldn't solve this mystery. Here's my own code which doesn't match the given expected output above:

#include<iostream>
using namespace std;

int main() {

   int num, result;

   cin >> num;
    if(num > 0) {
        result = num % 10;
        num / 10;
        cout << result;
    }

   return 0;
}
like image 571
Julian Williams Avatar asked Jan 25 '23 05:01

Julian Williams


1 Answers

You separate only the last digit, but need to check all - just add a loop. Also num / 10 does nothing.

 maxdigit = 0;
 while (num > 0) {
      maxdigit = max(maxdigit, num % 10);
      num /= 10;
  }
 cout << maxdigit;
like image 96
MBo Avatar answered Feb 08 '23 08:02

MBo