Finding larger and smaller numbers in c

Guys, please help me understand why comparing the first index of the input to the rest of the inputs can give you the larger and smaller number.

I am struggling to grasp the idea.

Here is the code:

#include <stdio.h>
#include <stdbool.h>

#define MAX 10
int main(){
    int num[MAX];
    int n, a, b, smallest=0, largest=0;
    for(int i=0; i < sizeof(num)/sizeof(num[0]); i++) {
        printf("Enter a number: ");
        scanf("%d", &num[i]);

    largest = num[0];
    smallest = num[0];

    for(int i=0; i < sizeof(num)/sizeof(num[0]); i++) {
         if(num[i] > largest) {
         if(num[i] < smallest) {

     printf("Smallest: %d", smallest);
     printf("\nLargest: %d", largest);

    return 0;

The num is array with numbers, so num[0] is the first number. Then it’s one-by-one compared to other numbers, and if any of them is smaller or larger, then that value is replaced by another number.


You are not comparing the first value, you are comparing all values “starting” with the first.
You start with the first because you need to make sure, that smallest/largest are numbers actually present in the array.

Imagine you have both initialized with 0, but the array is [1,2,3,4,5] → suddenly “smallest” would still have the initial value of 0, despite the array not having any 0.

1 Like

Ohh I think I get it now. Thank you

Thank you for this explanation. Still trying to absorb this.


I think to get correct results it is safe to initiate smallest and largest variables with the first element of an array.
like this,

int smallest = num[0];
int largest = num[0];

Okay, I will do it next time.

That’s already happening in the code.
Except largest/smalles are initialized at the beginning of the program and then overwritten with num[0] after the input.

It’s common practice to create all variables at the start, that are used throughout the program.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.