Author: admin

  • C# Params Array

    Sometimes a situation may arise where you do not know how many parameters you want to pass to a method or you may want the method to accept n number of parameters at runtime. In such times params type array can solve the problem. param is a keyword in C# that creates an array at runtime that receives and holds as many numbers of parameters as you want.

    The length of params will be zero if no arguments will be passed. Although only one params keyword is allowed and no other parameters are allowed after the method declaration.

    Let us see it in a program.


    C# Program to demonstrate the params Array

    Let us create two classes, one class will contain the method and another class where the main class will be present. The method will be accessed by creating an instance of the class in the main function.

    using System;
    
    namespace Arrays
    {
       class ParamsArray
       {
          public int SumElements(params int[] arr)
          {
             int sum = 0;
    
             foreach(int i in arr)
             {
                sum += i;
             }
    
             return sum;
          }
       }
    
       //main function class
       class MainClass
       {
          static void Main(string[] args)
          {
             //creating an object of ParamsArray class
             ParamsArray paramArray = new ParamsArray();
             int result = paramArray.SumElements(10, 20, 30, 40, 50);
    
             Console.WriteLine("The sum of the result: {0}", result);
          }
       }
    }

    Output:

    //Output:
    The sum of the result: 150

    Example: C# Program to pass different data-types and print them

    Let us see another example where we pass different data-type inputs and print them all with param. We will use object type params that allow us to enter as many numbers of inputs as we want of different data types.

    using System;
    
    namespace Arrays
    {
       class ParamProgram
       {
          // Print function (user-defined)
          public void DisplayFunc(params object[] elements)
          {
             Console.WriteLine("Displaying all the different types elements:");
             for (int i = 0; i < elements.Length; i++)
             {
                Console.WriteLine(elements[i]);
             }
          }
    
          // Main function
          static void Main(string[] args)
          {
             // Creating Object of class ParamProgram
             ParamProgram program = new ParamProgram();
    
             // Passing arguments of different types
             program.DisplayFunc("John Snow", 456, 30.25, "simple2code.com", 'Z', "Coder");
          }
       }
    }

    Output:

    //Output:
    The sum of the result: 150

  • C# Passing Array to Function

    In this tutorial, we will learn how to pass an array to function in C#. Before that you need to have an idea on following topics in C#.

    We use a function to reuse a block of code in a program. And we can pass an array to the function as a parameter. To pass an array, we need to provide an array name as an argument of a function. Example:

    //passing array 
    function_name(array_name); 

    C# Passing Array to Function

    Let us see it in a demonstration for passing an array to a function in C#. We will pass an array and find the largest element in a function.

    //C# program to fincd largest element in an array
    
    using System;
    
    namespace Arrays
    {
       public class ArrayToFunction
       {
          static void maxElement(int[] arr, int arr_size)
          {
             int max = arr[0];
             for (int i = 1; i < arr_size; i++)
             {
                if (max < arr[i])
                {
                   max = arr[i];
                }
             }
    
             Console.WriteLine("Largest element is: " + max);
          }
    
          public static void Main(string[] args)
          {
             int[] arr = { 77, 85, 98, 14, 50 };
    
            	//passing array to function
             maxElement(arr, 5);
          }
       }
    }

    Output:

    Largest element is: 98

    Another Example: C# Program to find the sum of all the elements present in an array.

    In the program below, we will return the sum value from the user-defined function to the main function.

    And you can see that, unlike the above example where we declared the function static, here function is non-static which means we need an object reference of the class to access a non-static function. Object obj is created as an instance of ArrayToFunc class.

    using System;
    
    namespace Arrays
    {
       class ArrayToFunc
       {
          int getSum(int[] arr, int size)
          {
             int i;
             int sum = 0;
    
             for (i = 0; i < size; ++i)
             {
                sum += arr[i];
             }
    
             return sum;
          }
    
          static void Main(string[] args)
          {
             ArrayToFunc obj = new ArrayToFunc();
    
             //ceating and initializing array
             int[] arr = new int[] { 10, 20, 30, 40, 50 };
             int result;
    
             //Passing array to a function and
             //storing the returned value in a result variable
             result = obj.getSum(arr, 5);
    
             //Display
             Console.WriteLine("Sum of all the elements: {0} ", result);
          }
       }
    }

    Output:

    Sum of all the elements: 150 

  • 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.