Home > Enterprise >  Using for statement to find the greatest of four given integers?
Using for statement to find the greatest of four given integers?

Time:01-02

#include <stdio.h>

int max_of_four(int, int, int, int);

int main() {
    int a, b, c, d;
    printf("Enter 4 numbers -");
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);
    return 0;
}

int max_of_four(int a, int b, int c, int d) {
    int greatest, i = 0;
    int num[4] = { a, b, c, d };
    greatest = num[0];
    while (i >= 3) {
        if (greatest <= num[i]) {
            greatest = num[i];
        }
        i  ;
    }
    return greatest;
}

So I tried using a for loop to compare every number to a variable greatest. But the answer for the greatest integer is always the first integer.

CodePudding user response:

In max_of_four:

while (i >= 3) is never true because you start with i being 0, and 0 is not greater than or equal to 3. Perhaps you meant while (i <= 3), but you would normally write this loop using for rather than while:

for (int i = 0; i < 4; i  )
    if (greatest <= num[i]) greatest = num[i];

CodePudding user response:

The problem is with the while loop condition. The condition should have been while(i<=3).

int max_of_four(int a,int b ,int c, int d) {

    int greatest,i = 0;
    int num[4] = {a, b, c, d};
    greatest = num[0];
    while(i <= 3) {
        if(greatest <= num[i]) {
            greatest = num[i];
        }
        i  ;
    }
    return greatest;
}

CodePudding user response:

The test while (i >= 3) is incorrect, you probably meant to write this instead:

while (i <= 3)

Note that for loops are much more readable as you can group the initialization, test and increment of i in a single line:

for (i = 0; i <= 3; i  ) {
    if (greatest <= num[i]) {
        greatest = num[i];
    }
}

Note also that it is more consistent to use i < 4 instead of i <= 3 to make the array length more obvious.

Also, you do not need an array with 4 entries: 3 entries suffice as you initialize greatest to the first value already.

Here is a modified version:

int max_of_four(int a, int b, int c, int d) {
    int greatest = a;
    int num[3] = { b, c, d };
    for (int i = 0; i < 3; i  ) {
        if (greatest < num[i]) {
            greatest = num[i];
        }
    }
    return greatest;
}

Finally, constructing an array to determine the maximum value among 4 integers is a bit of an overkill. If you must use a for loop, you can just wrap 3 simple tests into a dummy for statement:

int max_of_four(int a, int b, int c, int d) {
    for (;;) {
        if (a < b) a = b;
        if (c < d) c = d;
        if (a < c) a = c;
        return a;
    }
}
  • Related