unique, ad-free, freemium downloads

15 December 2017

How To Write a C Program To Return Largest Number From an Array

This program accepts n elements from the user, and then using the insertion sort technique; returns the largest number of the array. This program is valid for any number of any elements.


First of all, we define an array A[LIMIT] of 100 elements using a global constant LIMIT. (Note: You cannot use ordinary variables as subscript for defining arrays!)

#define LIMIT 100
int A[LIMIT];

Then we have a function getA(int A[], int n) that gets accepts two arguments: array A[] and total number of elements n. This function gets input of n elements from the user and stores it in our array. The resulting array is then sorted by the function showL(int A[], int n) in ascending order, the last of these elements i.e. A[n-1] is the largest and is returned by the before-mentioned function.


Complete Code for this program is as follows:
#include <stdio.h>
#define LIMIT 100
int i;
void getA(int A[], int n);
void ShowL(int A[], int n);
int main(){
    int n=0;
    int A[LIMIT]; //Doesn't accept more array elements than LIMIT
    printf("\n\n\t TO FIND LARGEST OF ANY NUMBER OF VALUES \t\n\n");
    printf("Please Enter Total Number of Elements : ");
    scanf("%d", &n); 
    getA(A,n);
    ShowL(A,n); //Using Insertion Sort Here
    system("pause");
}

void getA(int A[], int n){
    puts("");
    for (i=0; i < n; i++){
        printf("Enter Element %d : ", i+1);
        scanf("%d", &A[i]);
    }
    return 0;
}

void ShowL(int a[], int n){
    for (i=1; i < n; i++){
        while((a[i] < a[i-1]) && i>0){
            int temp = a[i-1];
            a[i-1] = a[i];
            a[i] = temp;
        }
    }
    printf("\nLargest : %d \n", a[n-1]);

}

This code returns following output:

         TO FIND LARGEST OF ANY NUMBER OF VALUES

Please Enter Total Number of Elements : 4

Enter Element 1 : 12
Enter Element 2 : 43
Enter Element 3 : 11
Enter Element 4 : 95

Largest : 95
Press any key to continue   . . . 


An instance of above program running on Code::Blocks is shown below

No comments:

Post a Comment