Blog

  • C# Jagged Arrays

    Jagged Arrays are also known as “array of arrays” that is because the elements are arrays themselves. Their dimensions and sizes may be different.

    Declaration of jagged array in C#.

    Jagged array can be declared and created in a following way.

    //declaration
    int [][] marks;
    
    //creating to allocate memory
    int[][] marks = new int[5][];

    Initialization of Jagged array in C#

    As told above, a jagged array can be a different size. As the elements inside the arrays are the arrays themselves so they may vary in dimension. Let us see an example.

    You can initialize array in different ways, one of which is:

    //Initializing in single line
    int[][] marks = new int[2][]{
                   new int[]{88,90,60},
                   new int[]{45,80,55,92}
                 };

    As you can see, we initialize it in a single line with a new operator for each array element with a different dimension. One has 3 integers while the other have 4 integers.

    You can also separately initialize them with index number such as:

    marks[0] = new int[3] { 88,90,60 };         
    marks[1] = new int[4] { 45,80,55,92 };  

    Let us understand with an example:


    C# program illustrates using a jagged array

    Nested for loop is used to traverse through jagged array.

    using System;
    
    namespace Arrays
    {
       class JaggedArrays
       {
          static void Main(string[] args)
          {
             //jagged arrays initialization
             int[][] arr = new int[][]
             {
                new int[]
                   { 0, 1 },
                   new int[]
                   { 2, 3 },
                   new int[]
                   { 4, 5 },
                   new int[]
                   { 6, 7 }
             };
    
             //displaying
             for (int i = 0; i < 4; i++)
                for (int j = 0; j < 2; j++)
                   Console.WriteLine("arr[{0}][{1}] = {2}", i, j, arr[i][j]);
    
          }
       }
    }

    Output:

    arr[0][0] = 0
    arr[0][1] = 1
    arr[1][0] = 2
    arr[1][1] = 3
    arr[2][0] = 4
    arr[2][1] = 5
    arr[3][0] = 6
    arr[3][1] = 7

  • C# Multidimensional Arrays

    C# allows multi-dimensional arrays. This could be of 2D or 3D (two-dimensional or three-dimensional) Array. These arrays are stored in the form of a table (with rows and columns) which is also known as a matrix.

    In C#, multidimensional array is also known as rectangular arrays.

    To declare an array of multi-dimensions, we need to use comma (,) inside the brackets []. Such as:

    //Two Dimensional array (2D)
    int arr[,];
    
    //Three Dimensional array (3D)
    int arr[, ,];

    Initialization of Multi Dimensional Array in C#

    We can initialize a Multi-Dimensional Array (two-dimensional or three-dimensional) in the following ways in C#.

    1. Initialization of two-dimensional array:

    2D array is the simplest of multi-dimensional array. It has rows and column like a table.

    The following is the 2 by 3 matrix array that is array with 2 rows and 3 columns.

    int [,] arr = new int [2,3] {
       {0, 1, 2} ,   
       {3, 4, 5}     
    };

    2. Initialization of three-dimensional array:

    int[,, ] arr= new int[2, 2, 3]
    {  {
    	{ 1, 2, 3 },
    	{ 4, 5, 6 }  },
       {
    	{ 7, 8, 9 },
    	{ 10, 11, 12} }
    };

    You can also declare and initialize multi-dimensional array in three different ways .

    //Method 1
    int[,] arr = new int[2,2]= { { 1, 2 }, { 3, 4 } };  
    
    //Method 2: Omitting the array size 
    int[,] arr = new int[,]{ { 1, 2 }, { 3, 4 } };  
    
    //Method 3 Omitting new operator
    int[,] arr = { { 1, 2 }, { 3, 4 } };

    Accessing two Dimensional array in C#

    Accessing 2d Array:

    Subscripts are used to access the 2D array element. It can be achieved by placing the particular index number within the two brackets [][] (that is the row index and column index). Such as:

    arr[2,3]; //accessing in 4D
    OR
    int val = arr[2,3]; // assigning the element to val

    Accessing 3d Array:

    Accessing a 3-dimensional array is also as same as a two-dimensional array, the only difference is that in a 3d array we have to specify 3 subscripts with a required index number.

    //Accessing 3D Array
    arr[2,1,1]; 

    Example of C# Multi Dimensional Array:

    Example: Two Dimensional Array in C#

    C# Program to display all elements in a 2D array. We need to use a nested loop in order to iterate through a multi-dimensional array.

    using System;
    
    namespace Arrays
    {
       class Program2D
       {
          static void Main(string[] args)
          {
             // array with 4 rows and 3 columns
             int[, ] arr = new int[4, 3]
             {
                { 0, 1, 2 },
                { 3, 4, 5 },
                { 6, 7, 8 },
                { 9, 10, 11 }
             };
    
             //displaying
             for (int i = 0; i < 4; i++)
             {
                for (int j = 0; j < 3; j++)
                {
                   Console.WriteLine("arr[{0},{1}] = {2}", i, j, arr[i, j]);
                }
             }
          }
       }
    }

    Output:

    arr[0,0] = 0
    arr[0,1] = 1
    arr[0,2] = 2
    arr[1,0] = 3
    arr[1,1] = 4
    arr[1,2] = 5
    arr[2,0] = 6
    arr[2,1] = 7
    arr[2,2] = 8
    arr[3,0] = 9
    arr[3,1] = 10
    arr[3,2] = 11

    Example: Three Dimensional Array in C#

    C# Program to display all elements in an 3D array

    using System;
    
    namespace Arrays
    {
       class Program3D
       {
          static void Main(string[] args)
          {
             // 3D array with 2,2,3 dimension
             int[,, ] arr = new int[2, 2, 3]
             {
                {
                   { 1, 2, 3 },
                   { 4, 5, 6 }
                },
                {
                   { 7, 8, 9 },
                   { 10, 11, 12 }
                }
             };
    
             //displaying
             for (int i = 0; i < 2; i++)
             {
                for (int j = 0; j < 2; j++)
                {
                   for (int k = 0; k < 3; k++)
                   {
                      Console.WriteLine("arr[{0},{1},{2}] = {3}", i, j, k, arr[i, j, k]);
                   }
                }
             }
          }
       }
    }

    Output:

    arr[0,0,0] = 1
    arr[0,0,1] = 2
    arr[0,0,2] = 3
    arr[0,1,0] = 4
    arr[0,1,1] = 5
    arr[0,1,2] = 6
    arr[1,0,0] = 7
    arr[1,0,1] = 8
    arr[1,0,2] = 9
    arr[1,1,0] = 10
    arr[1,1,1] = 11
    arr[1,1,2] = 12

    As we saw the examples of 2D and 3D arrays, in a similar we can create any number dimension as required. However, the most used multidimensional array is a two-dimensional array.


  • C# Arrays

    You must have learned C, C++, Java, etc and like any other programming language, an array in C# is also a group or a fixed-size sequential collection of data having the same data-type stored in a contiguous memory location.

    The are used to store multiple values in a single variable instead of creating multiple variable for each value. It is a simple data structure format where the primitive type of data such as int, char, double, float, etc are stored and accessed randomly through their index number such as array[0], array[1], etc.

    Elements are arranged inside the array with index numbers starting from zero as the first elements.

    There are 3 types of arrays in C#:

    1. Single Dimensional Array
    2. Multidimensional Array
    3. Jagged Array

    Arrays are objects in C# whose allocation of memory is done dynamically in a program. Since they are objects, we can use predefined functions in C# to find the size of an array.


    Declaration of array in C#

    For declaration of an array in C#, the user needs to specify the type of element and number of elements in an array. Below is the declaration of the single-dimensional Array.

    data-type array_name[arraySize];

    The data type must be a valid C# data type, a unique name must be specified to each array and the arraySize must be of an integer constant. Let see an example for an integer array with 20 elements.

    int arr[20];

    Initialization of array in C#

    Declaration doe not mean that the array is initialized in a memory. Initialization of an array means assigning the value to an array.

    An array is a reference type that is it deals with the address of the elements. And since it is a reference type, we need to use new keyword in order to initialize the array variable.

    Syntax and Example:

    //syntax
    data-type [] <array_name> = new <data-type>[size];
    
    //Example
    int[] numbers = new int[10];

    This way an instance of an array is created with a new keyword.

    You can initialize an array in various ways as follows:

    1. Create and initialize an array.

    int[] num = new int[5]  {12,  88, 4, 32, 48};

    2. Omit the size of array.

    int[] num = new int[] {12,  88, 4, 32, 48}; 

    3. Initialize an array at the time of declaration.

    int[] num= {12,  88, 4, 32, 48}; 

    Initialize the array after multiple array declaration. Example:

    // Declaration of multiple integer array 
    int[] num1, num2;
    
    
    // Initialization of arrays
    num1 = new int[5] {12,  88, 4, 32, 48};
    
    num2 = new int[5] {14,  45, 6, 64, 99};

    Accessing Array Elements in C#

    As told above, that each array elements are associated with specific number that is the index numbers.

    An array element can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket []. Such as:

    //Accessing single-dimensional Array
    arr[3]; //the 4th element is accessed
    arr[7]; //the 8th element is accessed

    You can also assign the value by accessing each of the position through index number. Example:

    int[] num= new int[5];
    num[0] = 45; //assigning 45 to the 1st element
    num[2] = 34; //assigning 34 to the 3rd element

    C# program for initialization, declaration and accessing an array

    In the program below we will initialize an array by the user input that is we will take an element of array from the user input.

    using System;
    
    namespace Arrays 
    {
       class Program 
       {
          static void Main(string[] args) 
          {
             //declaration and initialization an array
             int[] arr = {5, 10, 15, 20, 25};
             
             //displaying an array.
             for (int i = 0; i < arr.Length; i++)  
            {  
                Console.WriteLine("Element[{0}] = {1}", i, arr[i]);  
            }  
          }
       }
    }

    Output:

    Element[0] = 5
    Element[1] = 10
    Element[2] = 15
    Element[3] = 20
    Element[4] = 25

    Example: C# array initializing an array by accessing an array with an index number.

    using System;
    
    namespace Arrays 
    {
       class Program 
       {
          static void Main(string[] args) 
          {
            //Array declaration
            int[] arr;
      
            //allocation of memory for 5 integers
            arr = new int[5];
            
            //Initialization of an array.
            arr[0] = 5;
            arr[1] = 10;
            arr[2] = 15;
            arr[3] = 20;
            arr[4] = 25;
            //5 elements, index starts from 0 so index is till 4
            
             //displaying an array.
            for (int i = 0; i < arr.Length; i++)  
               Console.WriteLine("Element[{0}] = {1}", i, arr[i]);  
              
          }
       }
    }

    Output:

    Element[0] = 5
    Element[1] = 10
    Element[2] = 15
    Element[3] = 20
    Element[4] = 25

    Using the foreach Loop

    We used for loop above to display an element of an array one by one. Now we will do the same with foreach loop in C#. Traversal using foreach loop

    using System;
    
    namespace Arrays 
    {
       class Program 
       {
          static void Main(string[] args) 
          {
             //creating and initializing an array
             int[] arr = {5, 10, 15, 20, 25}; 
       
            int j = 0;
            //traversing to display with foreach
            foreach (int i in arr)  
            {  
                Console.WriteLine("arr[{0}] = {1}", j, i);
                j++;
            }  
          }
       }
    }

    Output:

    arr[0] = 5
    arr[1] = 10
    arr[2] = 15
    arr[3] = 20
    arr[4] = 25

    C# Arrays in Detail

    here is more to the arrays in C#. The above understanding mostly for 2D arrays. Click on the topic below to learn in detail about arrays in C#.

    C# Multidimensional Arrays
    C# Jagged Arrays
    C# Passing Array to Function
    C# Params Array
    C# Array Class

  • C++ Return Array from Functions

    C++ allows us to return the arrays from a function. However the actual array values cannot be returned, so we return the array from the function with the help of pointers.

    Pointers are the variables that hold an address. With the help of pointers, the address of the first element is returned from a function. The name of the array is itself points to the first element.

    In order to return the array from the function, we need to declare a function returning a pointer in a one-dimensional array. Example: syntax of returning function

    data-type * function_name() {
       .....
       .....
       .....
    }

    Also, C++ does not allow to return the address of the local variable from the function, so we need to declare the local variable as static in a function.


    Example of C++ Return Array from Functions

    #include <iostream>
    using namespace std;
    
    int *return_func()
    {
       // static declaration of array
       static int arr[10];
       for (int i = 0; i < 10; i++)
       {
          arr[i] = i;
       }
    
       //address of array returned
       return arr;
    }
    
    int main()
    {
       //pointer declaration
       int *ptr;
    
       ptr = return_func();	//address of a
    
       cout << "Printing an returned array: " << endl;
       for (int i = 0; i < 10; i++)
          cout << ptr[i] << " ";	//ptr[i] = *(ptr + i)
    
       return 0;
    }

    Output:

    Printing an returned array: 
    0 1 2 3 4 5 6 7 8 9 

  • C++ Multidimensional Arrays

    C++ allows Multi-Dimensional Arrays. This could be of 2D or 3D (two-dimensional or three-dimensional) Array. These arrays are stored in the form of a table (with rows and columns) which is also known as a matrix.

    In C++, multidimensional array is also known as rectangular arrays.

    Syntax of multi-dimensional array:

    data-type array_name[size1][size2]...[sizeN];

    The data-type must be a valid C++ data type, a unique name must be specified to each array and the size must be of an integer constant.

    //Two Dimensional array (2D)
    int arr[2][3];
    
    //Three Dimensional array (3D)
    int arr[2][4][6];

    Initialization of Multi Dimensional Array in C++

    We can initialize a Multi-Dimensional Array (two-dimensional or three-dimensional) in the following ways in C++.

    1. Initialization of two-dimensional array:

    The following is the 2 by 3 matrix array that is array with 2 rows and 3 columns.

    //Method 1
    int arr[2][3] = { {4, 5, 7}, {8, 3, 20} };
    
    OR
    
    //Method 2
    int arr[2][3] = {4, 5, 7, 8, 3, 20};

    There are two ways shown above to initialize an 2D array. However the method 1 is not preferred.

    2. Initialization of three-dimensional array:

    //Method1
    int arr[2][3][4] = {
        {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
        {{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}
        };
    OR
    //method2
    int arr[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
                     11, 12, 13, 14, 15, 16, 17, 18, 19,
                     20, 21, 22, 23};

    Accessing two Dimensional array in C++

    Accessing 2d Array:

    An array can be accessed by using a specific index number. It can be achieved by placing the particular index number within the two brackets [][]. Such as:

    arr[2][3]; //the 4th element of the third row is accessed
    arr[3][2]; //the 3rd element of the fourth row is accessed
    OR
    int val = arr[2][3]; // assigning the element to val

    Accessing 3d Array:

    Accessing 3-dimensional array is also as same as a two-dimensional array, the only difference is that in 3d array we have to specify 3 subscripts with a required index number.


    Example of C++ Multi Dimensional Array:

    Example: Two Dimensional Array in C++

    C++ Program to display all elements in an 2D array

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int arr[3][2] = {
    		{ 10, 55 },
                    { 5, 7 },
                    { 18, -8 }
           };
    
       cout << "Displaying each element" << endl;
       //using nested loop to access 2D Array element
       for (int row = 0; row < 3; ++row)
       {
          for (int col = 0; col < 2; ++col)
          {
             cout << "arr[" << row << "][" << col << "] = " << arr[row][col] << endl;
          }
       }
    
       return 0;
    }

    Output:

    Displaying each element
    arr[0][0] = 10
    arr[0][1] = 55
    arr[1][0] = 5
    arr[1][1] = 7
    arr[2][0] = 18
    arr[2][1] = -8

    Example: Three Dimensional Array in C++

    C++ Program to display all elements in an 3D array

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int arr[2][3][2] = {
    		{
             { 4, 8 },
             { 2, 4 },
             { 1, 6 }
          },
          {
             { 3, 6 },
             { 5, 4 },
             { 9, 3 }
          }
       };
    
       cout << "Displaying each element" << endl;
       //using nested loop to access 3D Array element
       for (int i = 0; i < 2; ++i)
       {
          for (int j = 0; j < 3; ++j)
          {
             for (int k = 0; k < 2; ++k)
             {
                cout << "arr[" << i << "][" << j << "][" << k << "] = " << arr[i][j][k] << endl;
             }
          }
       }
    
       return 0;
    }

    Output:

    Displaying each element
    arr[0][0][0] = 4
    arr[0][0][1] = 8
    arr[0][1][0] = 2
    arr[0][1][1] = 4
    arr[0][2][0] = 1
    arr[0][2][1] = 6
    arr[1][0][0] = 3
    arr[1][0][1] = 6
    arr[1][1][0] = 5
    arr[1][1][1] = 4
    arr[1][2][0] = 9
    arr[1][2][1] = 3

    As we saw the examples of 2D and 3D arrays, in a similar we can create any number dimension as required. However, the most used multidimensional array is a two-dimensional array.


  • Passing Array to a Function in C++

    In C++, passing an array to a function in the one-Dimensional array is done through an actual parameter and array variables with subscript are passed as formal arguments. While passing the array only the name of the array is passed to the function.

    Same method is applied for the multi-dimensional array.

    The syntax for passing an array to a function: There are three methods that can be used to pass an array to a function.

    First Way: As a unsized array

    return_type function(type arrayname[])
    {
      .....    
    }

    Second Way: As a sized array

    return_type function(type arrayname[SIZE])
    {
      .....    
    }

    Third Way: As a pointer

    return_type function(type *arrayname)
     {
      .....    
     }

    C++ Program for Passing One-dimensional Array to a Function

    The following program find the sum of all the numbers present in an array of one-dimensional.

    // C++ Program to find the sum of all the numbers
    
    #include <iostream>
    using namespace std;
    
    // function to add and return result
    int sumFunc(int arr[], int size)
    {
       int sum = 0;
    
       for (int i = 0; i < size; ++i)
          sum += arr[i];
    
       return sum;
    
    }
    
    int main()
    {
       // declaring and initializing an array
       int num_array[5] = { 20, 55, 18, 68, 10 };
       int result;
    
       //aclling a function by passing array and size
       result = sumFunc(num_array, 5);
    
       cout << "The sum of all numbers: " << result << endl;
    
       return 0;
    }

    Output:

    The sum of all numbers: 171

    C++ Program for Passing Multidimensional Array to a Function

    // C++ Program to display the 2D array elements
    
    #include <iostream>
    using namespace std;
    
    void displayFunc(int arr[][2], int row, int col)
    {
       cout << "Elements present in an Array: " << endl;
       for (row = 0; row < 3; ++row)
       {
          for (col = 0; col < 2; ++col)
          {
             cout << "arr[" << row << "][" << col << "]: " << arr[row][col] << endl;
          }
       }
    }
    
    int main()
    {
       // initialize 2d array
       int num[3][2] = {
    		{ 6, 9 },
          { 5, 4 },
          { 3, 2 }
       };
    
       // call the function
       displayFunc(num, 3, 2);
    
       return 0;
    }

    Output:

    Elements present in an Array: 
    arr[0][0]: 6
    arr[0][1]: 9
    arr[1][0]: 5
    arr[1][1]: 4
    arr[2][0]: 3
    arr[2][1]: 2

    Note: It is mandatory to give the column value in formal parameters but it is not necessary to give a row value. That is why int arr[][2] is written. We inserted 2 in the column value.


  • C++ Arrays

    An array is a group or a fixed-size sequential collection of data having the same data-type stored in a contiguous memory location. It is a simple data structure format where the primitive type of data such as int, char, double, float, etc are stored and accessed randomly through their index number such as array[0], array[1], etc.

    It can also store the collection of derived data types, such as pointers, structure, etc. Elements are arranged inside the array with index numbers starting from zero as the first elements.

    Types of Array in C++:

    • One Dimensional Array
    • Multi-Dimensional Array

    C++ Array Declaration

    For declaration of an array in C++, the user needs to specify the type of element and number of elements in an array. Below is the declaration of the single-dimensional Array.

    type array_name[arraySize];

    The data type must be a valid C++ data type, a unique name must be specified to each array and the arraySize must be of an integer constant. Let see an example for an integer array with 20 elements.

    int arr[20];

    C++ Array Initialization

    An array can be initialized by using a single statement or one by one. The Initialization is done within the curly braces {}. The example below is the initialization of single-dimensional Array.

    int arr[5] = {20, 50, 77, 13, 48};
    OR
    int arr[] = {20, 50, 77, 13, 48};

    In the second one of the above example, the array size is not declared so that you can initialize as much value as you want.

    Users can also directly assign the value to the particular element in an array by specifying the index number such as: below shows how to assign the value 20 to the 3rd element of an array.

    arr[2] = 20;

    NOTE:
    In the above example, number 2 means the 3rd element as the array index starts from 0.


    Accessing Array Elements in C++

    As told above, that each array elements are associated with specific number that is the index numbers.

    An array element can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket []. Such as:

    //Accessing single-dimensional Array
    arr[3]; //the 4th element is accessed
    arr[7]; //the 8th element is accessed

    We can also assign the value particular index number to other variable but their data type must be the same such as:

    int numb = arr[3];

    In the above, the value of 4th element from an array arr[] is assigned to the numb variable.


    Example: C++ Program to show the declaration, initialization and accessing of an array

    #include <iostream>
    using namespace std;
    
    int main() 
    {
        //initialization and declaration
        int arr[5] = {20, 50, 77, 13, 48};
    
        cout << "The elements are: " << endl;
        for (int i = 0; i < 5; ++i) {
            cout << arr[i] << endl;
        }
    
        cout << "Accessing 4th element: " << arr[3]; //accessing 4th element
    
    
        return 0;
    }

    Output:

    The elements are: 
    20
    50
    77
    13
    48
    Accessing 4th element: 13

    Empty Members in an array – C++

    When we declare an array of size n, that means we can store the n number of elements of in that array. But what happens if we were to store less than n number of elements.

    Consider an example below:

    //size=10
    //stored = 6 elements
    int arr[10] = {19, 10, 8, 45, 2, 87};

    As you can see, the size of an array is 10 but we initialized it with only 6 elements. However, a 10 contiguous memory location is already allocated to this array. What will happen to the remaining un-initialized arrays?

    Now in such cases, random values are assigned by the compiler to the remaining places. And often these random values are 0.


    Index Out of bound : Accessing elements out of it bound.

    Out of bound means, suppose you declare an array with 5 number of elements (index between 0 to 4) and you try to access the 7th element, which is not present in that array such as:

    .........
    ........
    {
       int arr[5];
     
       cout << arr[7] << endl;
       .......
    }

    In the above program, the 7th element is not present but we are trying to print that element. In such cases, the program may run fine but you may get an unexpected output (undefined behavior) from a program.

    There is no index out of bounds checking in C++.


    Advantages of Array in C++

    • Less line of codes that is a single array with multiple elements, specifying code optimization.
    • Elements of an array can be accessed randomly with the index number.
    • The elements in an array can be easily traversed.
    • Array’s data are easy to manipulate.
    • Sorting becomes easy in an array with fewer lines of codes.

    Disadvantages of Array in C++

    • The array is of fixed size once initialized. We cannot add new elements after initialization.
    • The number of elements you need to store in an array must be known in advance.
    • There may be a wastage of space if more memory is allocated than the required amount.

    Arrays in C++

    There is more to the arrays, click on the below to learn them separately in detail.

    C ++ Multi-dimensional Array
    C++ Passing Array to a Function
    C++ Return Array from Functions

  • C++ Recursion

    Recursion refers to the process when a function calls itself inside that function directly or indirectly or in a cycle. And such functions are called recursive functions. However, the crucial part is the termination condition, if not handled properly then it might go into an infinite loop.

    void recursion()
    {
        ......
        recursion(); //calling itself
        ......
    }
    
    int main()
    {
        ......
        recursion();
        ......
    }
    Recursion

    We can use the if…else statement to stop it from going into an infinite loop. Using the if…else statement, one branch of if-else can call the function itself and the other can give the condition to end the function.


    Example: C++ Recursion Program

    Program to find the factorial of a number in C++ using recursion.

    #include <iostream>
    using namespace std;
    
    int factorialFunc(int);
    
    int main()
    {
       int fact, num;
    
       cout << "Enter a positive integer: ";
       cin >> num;
    
       //calling factorial function
       fact = factorialFunc(num);
    
       cout << "Factorial of " << num << " is: " << fact << endl;
       return 0;
    }
    
    int factorialFunc(int n)
    {
       if (n == 0)
          return (1);  //base condition
       else
       {
          return (n* factorialFunc(n - 1));	//recursion
       }
    }

    Output:

    Enter a positive integer: 5
    Factorial of 5 is: 120

    If you want to learn more about recursion in detail, click here. Although it is for C programming but the theory concept of recursion is the same for all programming languages.


  • C++ Storage Classes

    What is Storage Class in C?

    Storage class is used to define the scope and lifetime of a variable. It tells the compiler where to allocate memory for a variable.

    Every variable in C++ has a type and the storage class. The type defines its data types such as int, float, etc. While storage defines two features such as scope and lifetime of a variable.

    A lifetime of a variable refers to the period of its activeness and visibility refers to the accessibility of a variable in a program.

    C++ program uses the following storage class:

    • Automatic
    • Register
    • Static
    • External
    • Mutable

    Automatic(auto) Storage class:

    A variable defined within a function or block with an auto specifier belongs to the automatic storage class. Auto variables can only be accessed within the block/function where they have been declared and not outside them which defines their scope.

    These are also referred to as local variables. By default, the variable declared in a program is auto storage variables and if they are not assigned then they hold a garbage value.

    auto keyword is used to defined an auto storage class in a program.
    Example:

    auto int number;
    //Example
    
    {
       auto int num;  
       float num = 3.45;  
    }

    The above defines a auto variable that are only accessible within those curly braces.

    C++ Program for auto storage class

    #include <iostream>
    using namespace std;
    
    //user-defined funciton
    void autoStorage()
    {
       // auto variables
       auto x = 20;
       auto y = 50;
    
       //displaying
       cout << "x: " << x << " \n";
       cout << "y: " << y << " \n";
    }
    
    int main()
    {
       //calling a function
       autoStorage();
    
       return 0;
    }

    Output:

    x: 20 
    y: 50 

    Now if you try to access the x or y variables through the main function, you will get an error indicating the scope of x and y is within the autoStorage() function only.


    Register Storage class:

    Register storage class is only for those variables that are being used very often in a program. The reason is, there are very few CPU registers at our disposal and many of them might be busy processing or something else. A typical application of the register storage class is loop counters, which get used a number of times in a program.

    Just like auto storage, it has the scope to a limited block where it is used. The difference is that the variables declared with a register keyword are stored in the register memory instead of RAM memory for quick access.

    It also means that the variable size is equal to the register size, usually one word.

    Note: We cannot get the memory location when dealing with the CPU register. If you use pointers to access the memory location, the program will through an error.

    Registers are declared as:

    register int variable_name;

    Static Storage Class:

    The keyword static is used to declare this type of variables in a c++ program. The name static is given to variables that can hold their values between calls of a function. They are allocated only once and their values are preserved between any number of function calls.

    Space is allocated for static variables in the program code itself and hence no new memory is allocated to it as they are not re-declared in the program.

    Their scope is local to the function where they are defined. Also, a global static variable can be accessed anywhere throughout the program.

    The static variable has the default value 0 which is provided by compiler.

    NOTE: Every global variable, defined outside functions has the type static automatically. The opposite of static is auto.

    C++ program of static storage class

    #include <iostream>
    using namespace std;
    
    //global variable
    static int count = 5;
    
    // Function
    void staticFunc(void)
    {
       // local static variable
       static int temp = 1;
       temp++;
       cout << "temp is: " << temp << ",  count is: " << count << endl;
    }
    
    
    int main()
    {
       while (count--)
       {
          staticFunc();
       }
    
       return 0;
    }

    Output:

    temp is: 2,  count is: 4
    temp is: 3,  count is: 3
    temp is: 4,  count is: 2
    temp is: 5,  count is: 1
    temp is: 6,  count is: 0

    External(extern) Storage Class:

    Extern stands for external storage class. The principal use of extern is to specify that a variable is declared with external linkage elsewhere in the program. In general, it is used to declare a variable to be used in a module that is not the one in which the corresponding variable is defined.

    extern keyword is used to define the global variable whose scope is within the whole program, which means these variables are accessible throughout the program.

    The main purpose of using extern is that they can be accessed between two different files which are located apart in a large program providing the reference of the variable. Check the program below to understand clearly.

    extern int variable_name;

    C++ program for extern storage class

    We will create two C++ file and access the variable/function of one file to another with static keyword.

    First file: main.cpp

    #include <iostream>
    
    int temp;
    
    //accessed using extern
    extern void extern_example();
     
    main() 
    {
       temp = 10;
       write_extern();
    }

    Second file: test.cpp

    #include <iostream>
    using namespace std;
    
    //this count variable is declared in main.cpp
    //here it accessed by using extern
    extern int temp;
    
    //some user-defined function
    void extern_example(void) 
    {
       cout << "Count is " << temp << endl;
    }

    Output:

    10

    As you can see, the variable of main.cpp file is accessed in test.cpp file using extern keyword and extern_example() function of test.cpp file is accessed in main.cpp file.


    mutable Storage Class

    mutable keyword is used for some specific task such as to modify one or more data members of class/struct through const function. This specifier is applied to only class objects.

    If we summarize all of the in a table, we will get,

    Storage ClassLifetimeVisibilityDefault Value
    Automatic (auto)Function BlockLocalGarbage
    Register (register)Function BlockLocalGarbage
    External (extern)different program
    files
    GlobalZero
    Static (static)Whole ProgramLocalZero
    Mutable (mutable)ClassLocalGarbage

  • C# Out Parameter

    This method is Passing Parameters by Output. Unlike other methods that return only a single value from the method, the Out Parameter can return multiple values from a function.

    They are similar to reference type, except the data are transferred out rather than into it. C# provide out keyword for the out parameter type.


    Example: C# Out Parameter

    using System;
    
    namespace Programs
    {
       class Swapping
       {
          // function (user-defined)
          public void valueFunc(out int val)
          {
             int temp = 20;
             val = temp;
          }
    
          //main method
          static void Main(string[] args)
          {
             Swapping swapObj = new Swapping();
    
             int a = 10;
    
             Console.WriteLine("Before calling a method, a: {0}", a);
    
             //calling funciton with out keyword
             swapObj.valueFunc(out a);
    
             Console.WriteLine("After method called, a: {0}", a);
    
          }
       }
    }

    Output:

    Before calling a method, a: 10
    After method called, a: 20