Write a program to find the sum of two numbers using command line argument
//definition of main in command-line arguments
int main(int argc, char *argv[])
{
//some coding
}
- argc – It is known as argument count, it stores the count of the number of arguments.
- argv[] – Pointer, contains location of all the values(arguments).
- *argv[] – Array of values of all the arguments
Approach
C
#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]){int firstNum, secondNum;int factorial = 1;if (argc!= 3){printf("Please enter two numbers ");return -1;}else{firstNum = atoi(argv[1]);secondNum = atoi(argv[2]);int sum = firstNum + secondNum;printf("Sum is %d", sum);}return 0;}
To Run a Program
- Go to the location/directory where your program is present.
- g++ proramName.c -o out
- ./out 2 4
Example:
Input: firstNum=2, secondNum=4 Output:Sum is 6
No comments:
Post a Comment