skip to content

Find the Largest of 10 Numbers in C

2 min read

This page was translated by AI

Today in class, I wrote a program that reads 10 numbers and finds the largest one. It took a few revisions, but I finally got it working!

#include <stdio.h>
int main()
{
printf ("Please type a number:");
int a,n,max;
n=1;
scanf("%d",&a);
max=a;
while(n<=9)
{
printf ("Please type a number again:");
scanf("%d",&a);
if (a>max)
max=a;
n++;
}
printf("Ten numbers have been entered and the maximum is being output\n");
printf("max=%d\n",max);
return 0;
}

This simple C program reads 10 numbers from the user and finds the largest one. Here is a detailed explanation:

  1. #include <stdio.h>: This preprocessor directive tells the compiler to include the standard input/output header file, stdio.h. It provides functions such as printf() and scanf(), which the program uses for input and output.
  2. int main(): This defines the main function. The program begins execution here.
  3. printf ("Please type a number:");: This function call displays a message asking the user to enter a number.
  4. int a,n,max;: This line declares three integer variables: a, n, and max.
  5. n=1;: This initializes n to 1.
  6. scanf("%d",&a);: This line waits for the user to enter a number and stores it in a.
  7. max=a;: This assigns the first number entered, which is currently stored in a, to max.
  8. while(n<=9): This loop runs nine times. Since n starts at 1, the program accepts 10 numbers in total. During each iteration, the user is asked to enter another number.
  9. printf ("Please type a number again:");: At the beginning of every loop iteration, this line prompts the user to enter another number.
  10. scanf("%d",&a);: This line waits for the user to enter a number and stores it in a.
  11. if (a>max) max=a;: If the number entered is larger than the current maximum, it is assigned to max.
  12. n++;: This increments n. It increases by 1 on every iteration, so the loop continues until n reaches 10.
  13. printf("Ten numbers have been entered and the maximum is being output\n");: Once the loop ends, this prints a message saying that 10 numbers have been entered and the maximum is about to be displayed.
  14. printf("max=%d\n",max);: This prints the largest value.
  15. return 0;: This indicates that the main function completed successfully. In C, returning 0 usually means the program finished its task successfully.
  16. In this context, max is a variable, not a function. In the declaration int a, n, max;, max is an integer variable. You can think of it as a container for the current largest value. a and n are variables as well. Nothing indicates that max is a function.