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:
#include <stdio.h>: This preprocessor directive tells the compiler to include the standard input/output header file,stdio.h. It provides functions such asprintf()andscanf(), which the program uses for input and output.int main(): This defines the main function. The program begins execution here.printf ("Please type a number:");: This function call displays a message asking the user to enter a number.int a,n,max;: This line declares three integer variables:a,n, andmax.n=1;: This initializesnto 1.scanf("%d",&a);: This line waits for the user to enter a number and stores it ina.max=a;: This assigns the first number entered, which is currently stored ina, tomax.while(n<=9): This loop runs nine times. Sincenstarts at 1, the program accepts 10 numbers in total. During each iteration, the user is asked to enter another number.printf ("Please type a number again:");: At the beginning of every loop iteration, this line prompts the user to enter another number.scanf("%d",&a);: This line waits for the user to enter a number and stores it ina.if (a>max) max=a;: If the number entered is larger than the current maximum, it is assigned tomax.n++;: This incrementsn. It increases by 1 on every iteration, so the loop continues untilnreaches 10.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.printf("max=%d\n",max);: This prints the largest value.return 0;: This indicates that the main function completed successfully. In C, returning 0 usually means the program finished its task successfully.- In this context,
maxis a variable, not a function. In the declarationint a, n, max;,maxis an integer variable. You can think of it as a container for the current largest value.aandnare variables as well. Nothing indicates thatmaxis a function.