Command Line Arguments Example Programs in C

C programming language के इस हिंदी tutorial में हम user से command line arguments input लेकर कुछ C programs बनाएंगे जैसे की two numbers का sum, string reverse print करना इत्यादि.

इस tutorial में दिए गए सभी C programs को समझने के आपको सबसे पहले ये जानकारी होना जरूरी है की command line arguments input कैसे लिए जाते हैं इसलिए आप link पर click करके पहले उस tutorial को जरूर पढ़ लें.

मैं इस tutorial में सभी C programs को command prompt पर command line arguments के साथ run करूँगा.

Sum of Two Numbers using Command Line Arguments in C

#include<stdio.h>
int main(int argc,char *argv[])
{
    int a,b,c;

    a=atoi(argv[1]);
    b=atoi(argv[2]);

    c=a+b;

    printf("Sum of %d and %d is: %d",a,b,c);

	return 0;
}

Compile and Run Program with Command Line Arguments:

gcc demo.c -o demo
demo.exe 15 25

Output:

Sum of 15 and 25 is: 40

Explanation:

जैसा की आप जानते हैं की command line से हम जो arguments input करते हैं वो सभी values string के तौर पर array argv में store हो जाती हैं.

अब क्योंकि हम string values का addition नहीं कर सकते इसलिए हमने built-in function atoi() की help से string को integer में type cast करके integer variables में assign किया है.

Sum of N Numbers using Command Line Arguments in C

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

    for(i=1;i<argc;i++)
	{
		sum=sum+atoi(argv[i]);
	}

    printf("Sum of N numbers : %d",sum);

	return 0;
}

Compile and Run Program with Command Line Arguments:

gcc demo.c -o demo
demo.exe 15 25 10 5 18 12

Output:

Sum of N numbers : 85

Reverse String Entered from Command Line Arguments in C

#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[])
{
	printf("\nString : %s\n",argv[1]);

    printf("\nReverse String : %s\n",strrev(argv[1]));

	return 0;
}

Compile and Run Program with Command Line Arguments:

gcc demo.c -o demo
demo.exe AMAN

Output:

String : AMAN
Reverse String : NAMA