Find the Largest Number Among N Numbers

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to write a C program to find the largest number among n user input numbers. We will use a simple for loop to iterate through all the input numbers and compare each number with a variable 'big' that will store the largest number found so far.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Declare variables

We need two variables- n to store the number of input numbers and big to store the largest number.

int n;
float big;

Prompt the user

Prompt the user to enter the total number of elements they wish to find the greatest element of.

printf("Enter the number of elements you wish to find the greatest element of: ");
scanf("%d", &n);

Set the initial value of big

Initialize the variable big with the first input number.

printf("Enter %d numbers :\n", n);
scanf("%f", &big);

Compare each number with big

Iterate through all the remaining input numbers using a for loop. In each iteration, prompt the user to input the new number.

float c; //variable to store the current number

for(int i = 2; i <= n; i++)
{
    printf("Enter element %d: ", i);
    scanf("%f", &c);
    /*
        if input number is larger than the
        current largest number
    */
    if(big < c)
        big = c;    //update the value of big
}

Output the result

Display the final output to the user.

printf("The largest of the %d numbers is  %f ", n, big);

Summary

In this lab, we've learned how to write a C program to find the largest number among n user input numbers. We used a simple for loop to iterate through all the input numbers and compare each number with a variable 'big' that stores the largest number found so far. We hope that this tutorial has provided you with a better understanding of C programming and helped you to develop your coding skills.

Full code

#include <stdio.h>

int main()
{
    int n;
    float big;

    printf("Enter the number of elements you wish to find the greatest element of: ");
    scanf("%d", &n);

    printf("Enter %d numbers :\n", n);
    scanf("%f", &big);

    for(int i = 2; i <= n; i++)
    {
        float c;
        printf("Enter element %d: ", i);
        scanf("%f", &c);
        /*
            if input number is larger than the
            current largest number
        */
        if(big < c)
            big = c;  //update the value of big
    }

    printf("The largest of the %d numbers is  %f ", n, big);

    return 0;
}

Other C Tutorials you may like