What does the program below do?

Study the source code below and determine what the program does

#include<stdio.h>
main(){
    float largest, number;
    largest = 0;
    printf("\nEnter a number (0 to end): ");
    scanf("%f",&number);
    while(number != 0){
        if(number > largest) largest = number;
        printf("\nEnter a number (0 to end): ");
        scanf("%f",&number);
    }
    printf("\nThe largest is %6.2f\n",largest);
}

Explanation

  • The program works out the largest number from a set of inputted numbers.
  • The program starts by initializing the variable largest to 0.
  • Next, the program requests the user to enter a number, with 0 as the end signal for the while loop.
  • Using the function scanf, the inputted number is read into the variable number.
  • Both number and largest are of type float. Float is short for "floating point." Float is a fundamental type built into the compiler and used to define numeric values with decimal points, which accommodate fractions.
  • Using the while loop, the program keeps requesting the user to enter a number until 0 is pressed on the keyboard to terminate the loop.
  • If the number entered by the user is greater than largest, then the number is assigned as new largest.
  • At the end of the loop (remember 0 to end), the function printf is used to print the largest number from the set of inputted numbers to the standard output.

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

Enter a number (0 to end): 2

Enter a number (0 to end): 4

Enter a number (0 to end): 1

Enter a number (0 to end): 10

Enter a number (0 to end): 20

Enter a number (0 to end): 50

Enter a number (0 to end): 6

Enter a number (0 to end): 60

Enter a number (0 to end): 2

Enter a number (0 to end): 1

Enter a number (0 to end): 0

The largest is  60.00

Add comment


Security code
Refresh