Largest digit in four variables inputted by the user

Sep 5, 2019 at 3:22pm
Trying to solve basic programming problem (logic based).
finding the largest digit in four variables.
i have done the program w/ several inputs but when it comes to specifically
6 13 9 10 instead of 13 being the output. 10 becomes it output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
 int max_of_four(int a, int b, int c, int d) {
     int largest = a;
     if (b > a)
     {
         largest = b;
     }
     if (c > b) {
         largest = c;
     }
     if (d > c){
         largest = d;
     }
    cout << largest;
     }
int main() {
    int num1,num2,num3,num4;
    cin >> num1 >> num2 >> num3 >> num4;

    max_of_four(num1,num2,num3,num4);
    return 0;
    }

Sep 5, 2019 at 3:28pm
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
 void max_of_four(int a, int b, int c, int d) {
     int largest = a;
     if (b > a)
     {
         largest = b;
     }
     if (c > largest) {
         largest = c;
     }
     if (d > largest){
         largest = d;
     }
    cout << largest;
     }
int main() {
    int num1,num2,num3,num4;
    cin >> num1 >> num2 >> num3 >> num4;

    max_of_four(num1,num2,num3,num4);
    return 0;
    }
Sep 5, 2019 at 3:33pm
the largest digit is 9 in your example.
what I suggest is to avoid all the comparisons etc ..
bool digits[10] = {false};
for all the numbers
get a digit
digits[numbers_digit] = true

then back iterate it
for(i = 9; i >=0; i--)
if digits[i] //this is your answer, stop loop and tell user all about it

can you do this? The least digit in a number is num%10. You can then remove that digit by num /= 10. Do this until num == 0.

fun stuff: you can stop looking if you ever find a 9 anywhere.
Last edited on Sep 5, 2019 at 3:35pm
Sep 5, 2019 at 3:35pm
its fixed. but how did it work just by changing the data type of the function?
Sep 5, 2019 at 3:43pm
he changed other stuff. Read it again. line 9

is your problem description wrong, or your code? Do you know what a digit is?
Last edited on Sep 5, 2019 at 3:44pm
Topic archived. No new replies allowed.