Write a program which reads two integer values from the command line. If the first is less than the second, print the message up. If the second is less than the first, print the message down. If the numbers are equal, print the message equal. If there is an error reading the data, print a message containing the word Error and perform exit(0);

Source code

Brief explanation is provided after the source code.

#include <stdio.h>

int main(int argc, char ** argv) {

    if (argc < 3 ) {
        printf("Error\n");
        exit(0);
    }

    if(atoi(argv[1]) < atoi(argv[2]))
        printf("up\n");
    else if (atoi(argv[1]) > atoi(argv[2]))
        printf("down\n");
    else
        printf("equal\n");
    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

$ cc -o 2.4 2.4.c
$ ./2.4
Error
$ ./2.4 5 6
up
$ ./2.4 6 5
down
$ ./2.4 6 6
equal

Brief Explanation

  • Given that the program is executed as ./2.4 1 2, in this case we have 3 arguments from the command-line. i.e argc = 3
  • If the number of arguments entered from the command-line is less than 3, the program prints "Error".
  • argv is an array of pointers to char. The contents of this array are the command line arguments themselves.
  • The function atoi() converts string to integer.

Add comment


Security code
Refresh