tochka
tochka

Reputation: 29

program returns odd number

I am exploring c++ and I have a task to write a function that takes four integers and check which is the biggest of them and then returns the result

The problem that I am facing is that the program returns a different number every time

I am using an online compiler (web based) to check my code output with gcc 7.2

#include <iostream>
#include <cstdio>
using namespace std;

/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/

int max_of_four(int a, int  b, int  c, int  d){
    int num;
    // printf ("hello world ");
    int nums[] = {a,b,c,d};
    for (int i = 0; i < 4; i++){

        if ( nums[i]< num ){
          //  cout << nums[i] << endl;
            ;
        }
        else if (nums[i] > num ) {
            num = nums[i];
        }
    }
    return num;
}



int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    //cout << max_of_four(a,b,c,d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);

    return 0;
}

Upvotes: 0

Views: 72

Answers (1)

robthebloke
robthebloke

Reputation: 9682

You haven't initialized num with a value, so the later checks inside the loop are against a random indeterminate number.

int num = a;

Upvotes: 2

Related Questions