Tuesday 27 January 2015

Arrays using Command - Line Arguments

Introduction :

In many system it is possible to pass argument from the command line (known as command line argument) to an application by including a parameter of type string[] (i.e. an array of string) in the parameter list of Main. We named this parameter args. When an application is executed from the the command prompt, the execution environment the command-line argument that appear after the application name the application's main method as string in the one dimensional array args. The Number of argument passed from the command line is obtained from the accessing the arrays length property. For example the command  "MyApplication a b"  passes two command line argument to application MyApplication. Note that command line argument separated by white space not commas.

Example

  1. using System;  
  2. public class InitArray  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         if(args.Length != 3)  
  7.             Console.WriteLine("Please re-enter the entire command including\n An array size, Initial Value and Increament");  
  8.   
  9.         else  
  10.         {  
  11.             int arrayLength = Convert.ToInt32( args[0] );  
  12.             int[] array = new int[ arrayLength ];  
  13.   
  14.             int initialValue = Convert.ToInt32( args[1] );  
  15.             int increament = Convert.ToInt32( args[2] );  
  16.   
  17.             forint counter = 0; counter<array.Length; counter++ )  
  18.                 array[counter] = initialValue + increament * counter;  
  19.   
  20.             Console.WriteLine( "{0}{1,8}""Index""Value" );  
  21.   
  22.             for(int counter = 0; counter < array.Length; counter++)  
  23.   
  24.             Console.WriteLine("{0,3}{1,8}", counter, array[counter]);  
  25.         }  
  26.     }  
  27. }  


In the above example it takes three command line arguments to initialize the array. First is the length of the array Second is the initial value of the array third is the Increment between values in the array.


Output of Command line argument
Fig: Screenshot of output


In this Output the size of array is 5 the initial value of array is 0 and there is increment of 8.