C program that takes two integers as command line arguments and divide the first argument by the second argument
Posted by Samath
Last Updated: May 04, 2016
  1981

Write a simple C program (mydivide.c) that takes two integers as command line arguments and divide the first argument by the second argument. You should do all possible checks on the input so that your program does not crash. You should also ensure that the first argument is always bigger than the second argument. In addition to printing the result of the division. You should also print the number of arguments that this program takes and the list of arguments.
NB: Printing the number of arguments and the list of arguments, should still work if we decide
to take an arbitrary number of arguments.

Solution:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
	int num1;
	int num2;
	int div;
	int i = 0;

    if(argc > 1)
    {
    	num1 = atoi(argv[0]);
    	num2 = atoi(argv[1]);
    }
    else
    {
    	printf("\nPlease enter two integers as command line arguments.");
    	exit(0);
    }
    
   	if(num2 == 0)
	{
		printf("\nDemoninator cannot be 0...");
	}
		
	if(num1 <= num2)
	{
		printf("\n First number should be greater than the second...");
		exit(0);
	}
			
	div = num1/num2;
	
	printf("\nResult: %d",div);
	printf("\nNumber of Arguments: %d",argc);
	
    for (i = 0; i < argc; i++) {
        printf("\nargv[%d] = %s\n", i, argv[i]);
    }
    
	return 0;
}