Skip to main content

C++ Arrays: Passing Array to Function, Multidimensional Arrays

C++ Arrays

Like other programming languages, array in C++ is a group of similar types of elements that have contiguous memory location.

In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index starts from 0. We can store only fixed set of elements in C++ array.

Java C array 1

Advantages of C++ Array

  • Code Optimization (less code)
  • Random Access
  • Easy to traverse data
  • Easy to manipulate data
  • Easy to sort data etc.

Disadvantages of C++ Array

  • Fixed size

C++ Array Types

There are 2 types of arrays in C++ programming:

  1. Single Dimensional Array
  2. Multidimensional Array

C++ Single Dimensional Array

Let's see a simple example of C++ array, where we are going to create, initialize and traverse array.

  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.  int arr[5]={10, 0, 20, 0, 30};  //creating and initializing array    
  6.         //traversing array    
  7.         for (int i = 0; i < 5; i++)    
  8.         {    
  9.             cout<<arr[i]<<"\n";    
  10.         }    
  11. }  

Output:/p>

10
0
20
0
30

C++ Array Example: Traversal using foreach loop

We can also traverse the array elements using foreach loop. It returns array element one by one.

  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.  int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array    
  6.         //traversing array    
  7.        for (int i: arr)     
  8.         {    
  9.             cout<<i<<"\n";    
  10.         }    
  11. }  

Output:

10
20
30
40
50

C++ Passing Array to Function

In C++, to reuse the array logic, we can create function. To pass array to function in C++, we need to provide only array name.

  1. functionname(arrayname); //passing array to function    

C++ Passing Array to Function Example: print array elements

Let's see an example of C++ function which prints the array elements.

  1. #include <iostream>  
  2. using namespace std;  
  3. void printArray(int arr[5]);  
  4. int main()  
  5. {  
  6.         int arr1[5] = { 10, 20, 30, 40, 50 };    
  7.         int arr2[5] = { 5, 15, 25, 35, 45 };    
  8.         printArray(arr1); //passing array to function    
  9.         printArray(arr2);  
  10. }  
  11. void printArray(int arr[5])  
  12. {  
  13.     cout << "Printing array elements:"<< endl;  
  14.     for (int i = 0; i < 5; i++)  
  15.     {  
  16.                    cout<<arr[i]<<"\n";    
  17.     }  
  18. }  

Output:

Printing array elements:                                                              
10                                                                                    
20                                                                                    
30                                                                                    
40                                                                                    
50                                                                                    
Printing array elements:                                                              
5                                                                                     
15                                                                                    
25                                                                                    
35                                                                                    
45

C++ Passing Array to Function Example: Print minimum number

Let's see an example of C++ array which prints minimum number in an array using function.

  1. #include <iostream>  
  2. using namespace std;  
  3. void  printMin(int arr[5]);  
  4. int main()  
  5. {  
  6.    int arr1[5] = { 30, 10, 20, 40, 50 };    
  7.         int arr2[5] = { 5, 15, 25, 35, 45 };    
  8.         printMin(arr1);//passing array to function    
  9.          printMin(arr2);  
  10. }  
  11. void  printMin(int arr[5])  
  12. {  
  13.     int min = arr[0];    
  14.         for (int i = 0; i > 5; i++)    
  15.         {    
  16.             if (min > arr[i])    
  17.             {    
  18.                 min = arr[i];    
  19.             }    
  20.         }    
  21.         cout<< "Minimum element is: "<< min <<"\n";    
  22. }  

Output:

Minimum element is: 10                                                                
Minimum element is: 5   

C++ Passing Array to Function Example: Print maximum number

Let's see an example of C++ array which prints maximum number in an array using function.

  1. #include <iostream>  
  2. using namespace std;  
  3. void  printMax(int arr[5]);  
  4. int main()  
  5. {  
  6.         int arr1[5] = { 25, 10, 54, 15, 40 };    
  7.         int arr2[5] = { 12, 23, 44, 67, 54 };    
  8.         printMax(arr1); //Passing array to function  
  9.          printMax(arr2);   
  10. }  
  11. void  printMax(int arr[5])  
  12. {  
  13.     int max = arr[0];    
  14.         for (int i = 0; i < 5; i++)    
  15.         {    
  16.             if (max < arr[i])    
  17.             {    
  18.                 max = arr[i];    
  19.             }    
  20.         }    
  21.         cout<< "Maximum element is: "<< max <<"\n";    
  22. }  

Output:

Maximum element is: 54
Maximum element is: 67

C++ Multidimensional Arrays

The multidimensional array is also known as rectangular arrays in C++. It can be two dimensional or three dimensional. The data is stored in tabular form (row ∗ column) which is also known as matrix.


C++ Multidimensional Array Example

Let's see a simple example of multidimensional array in C++ which declares, initializes and traverse two dimensional arrays.

  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.   int test[3][3];  //declaration of 2D array   
  6.     test[0][0]=5;  //initialization   
  7.     test[0][1]=10;   
  8.     test[1][1]=15;  
  9.     test[1][2]=20;  
  10.     test[2][0]=30;  
  11.     test[2][2]=10;  
  12.     //traversal    
  13.     for(int i = 0; i < 3; ++i)  
  14.     {  
  15.         for(int j = 0; j < 3; ++j)  
  16.         {  
  17.             cout<< test[i][j]<<" ";  
  18.         }  
  19.         cout<<"\n"//new line at each row   
  20.     }  
  21.     return 0;  
  22. }  

Output:

5 10 0 
0 15 20 
30 0 10 


C++ Multidimensional Array Example: Declaration and initialization at same time

Let's see a simple example of multidimensional array which initializes array at the time of declaration.

  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.   int test[3][3] =  
  6.     {  
  7.         {2, 5, 5},  
  8.         {4, 0, 3},  
  9.         {9, 1, 8}  };  //declaration and initialization    
  10.     //traversal    
  11.     for(int i = 0; i < 3; ++i)  
  12.     {  
  13.         for(int j = 0; j < 3; ++j)  
  14.         {  
  15.             cout<< test[i][j]<<" ";  
  16.         }  
  17.         cout<<"\n"//new line at each row   
  18.     }  
  19.     return 0;  
  20. }  

Output:"

2 5 5 
4 0 3 
9 1 8


Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are...

Genetic Algorithm: Population, Fitness Function, Parent Selection, Cross over, Mutation

Genetic Algo Population Population is a subset of solutions in the current generation. It can also be defined as a set of chromosomes. There are several things to be kept in mind when dealing with GA population − The diversity of the population should be maintained otherwise it might lead to premature convergence. The population size should not be kept very large as it can cause a GA to slow down, while a smaller population might not be enough for a good mating pool. Therefore, an optimal population size needs to be decided by trial and error. The population is usually defined as a two dimensional array of –  size population, size x, chromosome size . Population Initialization There are two primary methods to initialize a population in a GA. They are − Random Initialization  − Populate the initial population with completely random solutions. Heuristic initialization  − Populate the initial population using a known heuristic for the problem. It has been observed that the e...

C++ (Object and Class)

The major purpose of C++ programming is to introduce the concept of object orientation to the C programming language. Object Oriented Programming is a paradigm that provides many concepts such as  inheritance, data binding, polymorphism etc. The programming paradigm where everything is represented as an object is known as truly object-oriented programming language.  Smalltalk  is considered as the first truly object-oriented programming language. OOPs (Object Oriented Programming System) Object  means a real word entity such as pen, chair, table etc.  Object-Oriented Programming  is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: Object Class Inheritance Polymorphism Abstraction Encapsulation C++ Object In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an ent...