Write a program that works out the largest and smallest values from a set of 10 inputted numbers.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int main(int argc, char ** argv) {
    int largest, smallest, number, i = 1;

    printf("Input 10 numbers:\n");
    scanf("%d", &number);
    largest = smallest = number; // Assign the 1st number to max and min

    while(i++ < 10 ) {
        scanf("%d", &number);
        if ( number > largest)
            largest = number;
        else if (number < smallest)
            smallest = number;
    }
    printf("The largest number is %d\n", largest);
    printf("The smallest number is %d\n", smallest);

    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Input 10 numbers:
20
1
0
-3
-6
0
24
30
14
23
The largest number is 30
The smallest number is -6

Brief Explanation

  • The program gets the first number from the user and assign it as both the largest and smallest.
  • Using a 'while' loop, the program request for the remaining numbers while testing each number if it is greater than the largest in which case it becomes the new largest. If it's less than the smallest, it becomes the new smallest.
  • Once the 'while' loop is exited, the program displays the largest and the smallest number using the printf() function.

Add comment


Security code
Refresh