Write a program to swap 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[]){if (argc != 3){printf("Enter two numbers ");return -1;}else{int firstNum = atoi(argv[1]);int secondNum = atoi(argv[2]);printf("Numbers before swap:\n");printf("First = %d, Second = %d\n", firstNum, secondNum);int temp = firstNum;firstNum = secondNum;secondNum = temp;printf("Numbers after swap:\n");printf("First = %d, Second = %d", firstNum, secondNum);}return 0;}
To Run a Program
- Go to the location/directory where your program is present.
- g++ proramName.c -o out
- ./out 5 4
Example:
Input: firstNum=5, secondNum=4 Output: Numbers before swap: First = 5, Second = 4 Numbers after swap: First = 4, Second = 5
No comments:
Post a Comment