Find largest of n numbers

Find Largest of n Numbers

C program to find largest of n numbers

In this program, we find the largest element present in the array. We will do this by first saving the value of the first element in the variable ‘largest’. Then we will compare with remaining elements of the array and store the value if another larger number is found in this array. This will go on N-1 times and the program ends.

#include<stdio.h>
#include<conio.h>
void main()
{

    int num, i;
    float c,largest;
    clrscr();
    printf("...Welcome To EduNews.Tech");

    printf("\n\nEnter the number of elements : ");
    scanf("%d", &num);
    printf("\nEnter %d numbers :", num);

    printf("\nElement 1: ");

    //Important step- always initialize largest to the first element
    scanf("%f", &largest);

    for(i = 2; i <= num; i++)
    {
    printf("\nElement %d  : ", i);
        scanf("%f", &c);
        /* 
            if input number is larger than the 
            current largest number
        */
        if(largest < c)  
            largest = c;    // update largest to the larger value
    }

    printf("\nThe largest of the %d numbers is  %f ", num, largest);
    printf("\n\n\n\n\t\t\tThankyou for Joining Us !");
    printf("\n\t\t\t!Regards EduNews !");
    getch();
}

Program Output:

largest of n numbers

Program Explanation

  1. Take the size of the array as input from the user.
  2. Then, initialize an array of size given by the user.
  3. Using for loop, take array element as input from users and insert them into the array.
  4. After inserting all the elements of the array, consider the very first element of array to be the largest.
  5. Run a for loop, from 1 to array size-1, extracting array element one by one and comparing it to the largest element.
  6. If the largest element is smaller than the element being compared, then the largest element is updated with the value of the current element of the array.
  7. In the end, the largest element will hold the actual largest value present in the array.

I hope this post helps you to understand the “Largest of n Numbers” and its implementation in C programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *