C-Tutorial: Command line arguments

Latest

Showing posts with label Command line arguments. Show all posts
Showing posts with label Command line arguments. Show all posts

Friday, 11 November 2016

Arrays of Variable Length (or) Variable length arrays

Friday, November 11, 2016 0
Arrays of Variable Length (or) Variable length arrays

Variable-length automatic arrays are allowed in C99, C90 mode.
Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size.

  • C supports variable sized arrays from C99 standard. For example, the below program compiles and runs fine in C.

In variable length arrays dimensions of the array can also be specified by an valid expression.
Values to the arguments can be specified at run time.

/* Example-1 program for variable length array */

#include<stdio.h>
#include<conio.h>

void action(int);
main()
{
int n;
clrscr();
printf("\n Enter n value:");
scanf("%d",&n);
action(n);
}

void action(int n)
{
int i, a[n];
printf("\n Enter the array elements: ");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
printf("\n The given array elements are: ");
for(i=0; i<n; i++)
printf("%d",a[i]);
}

Read More

Thursday, 20 October 2016

Command line arguments in C

Thursday, October 20, 2016 0
Command line arguments in C


     It is possible to pass some arguments from the command line to your C programs when they are executed. These arguments are called command line arguments. They are,
  • argc
  • argv[]
where,
argc      -->  Number of arguments in the command line including program name
argv[]   –>  This is carrying all the arguments
  • In real time application, it will happen to pass arguments to the main program itself.  These arguments are passed to the main () function while executing binary file from command line.

Example1:
#include<stdio.h>
#include<conio.h>                        

main(int argc, char *argv[])
{
int  i;
clrscr();
if(argc==1)
{
printf("\n Pass the arguments more than one");
exit(1);
}
for(i=1; i<argc; i++)
printf("%s",argv[i]);
}

Example2:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

main(int argc, char *argv[])
{
int  i, n, sum=0;
clrscr();
if(argc==1)
{
printf("\n Pass the arguments more than one");
exit(1);
}
for(i=1; i<argc; i++)
{
n=atoi(argv[i]);
sum=sum+n;
} 
printf("\n Total  Sum is = %d",sum);

}
Read More