Finding Largest and Smallest Array Elements in C

CCBeginner
Practice Now

Introduction

Finding the largest and smallest element in an array is a common problem in programming. In this lab, you will learn how to write a C program to find the largest and the smallest elements in an array using a step-by-step approach.

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

Start by declaring necessary variables in your program. We need an integer array, its size, and integer variables 'big' and 'small'.

int a[50], size, i, big, small;

Ask User to Enter Array Elements

Next, ask the user to enter the elements of the array.

printf("Enter the size of the array: ");
scanf("%d", &size);

printf("\nEnter %d elements of the array: \n", size);
for(i = 0; i < size; i++)
    scanf("%d", &a[i]);

Loop Through Array to Find the Largest Element

We will now loop through the array to find the largest element in it.

big = a[0]; // initialize
for(i = 1; i < size; i++)
{
    if(big < a[i])
    {
        big = a[i];
    }
}
printf("The largest element is %d\n", big);

Loop Through Array to Find the Smallest Element

We will now loop through the array again to find the smallest element in it.

small = a[0]; // initialize
for(i = 1; i < size; i++)
{
    if(small > a[i])
    {
        small = a[i];
    }
}
printf("The smallest element is %d\n", small);

Write Full Code

Now that you have seen the individual code blocks, let's see the entire code in one place.

#include<stdio.h>

int main()
{
    int a[50], size, i, big, small;

    printf("Enter the size of the array: ");
    scanf("%d", &size);

    printf("\nEnter %d elements of the array: \n", size);
    for(i = 0; i < size; i++)
        scanf("%d", &a[i]);

    big = a[0]; // initialize
    for(i = 1; i < size; i++)
    {
        if(big < a[i])
        {
            big = a[i];
        }
    }
    printf("The largest element is %d\n", big);

    small = a[0]; // initialize
    for(i = 1; i < size; i++)
    {
        if(small > a[i])
        {
            small = a[i];
        }
    }
    printf("The smallest element is %d\n", small);

    return 0;
}

Summary

In this lab, you learned how to write a C program to find the largest and smallest elements in an array using a step-by-step approach. By understanding these basic programming concepts, you can move on to more advanced topics in C programming.

Other C Tutorials you may like