Find the largest of n numbers in C

This is an example C program for finding the largest of n numbers.

#include <stdio.h>
#include <stdlib.h>

/* This finds the largest number. */

int largest (int n, int numbers[n])
{
    int i;
    int max;

    max = numbers[0];
    for (i = 1; i < n; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    return max;
}

int main (int argc, char ** argv)
{
    int i;
    int numbers[argc];
    int n;
    const int base = 10;

    n = 0;

    /* This part turns the command line into integers. */

    for (i = 1; i < argc; i++) {

        char * end;
        int number;
        number = strtol (argv[i], & end, base);
        if (end != argv[i]) {
            numbers[n] = number;
            n++;
        }
    }
    if (n > 0) {
        printf ("The largest number is %d.\n", largest (n, numbers));
    }
    else {
        printf ("There are no numbers.\n");
    }
    return 0;
}

(download)

When run like

./lonn  -10 -9 -12 -999

the output of the example looks like this:

The largest number is -9.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer