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

Data Warehousing - An Overview

Anurag Information Technology (IT) has historically influenced organizational performance and competitive standing. The increasing processing power and sophistication of analytical tools and techniques have put the strong foundation for the product called data warehouse. There are a number of reasons that any organization should consider a data warehouse, which can be the critical tool for maximizing the organization’s investment in the information it has collected and stored throughout the enterprise. IT managers need to understand the rationale and benefits of data warehouses because they may need to design and implement, or procure this kingpin of business intelligence. The data warehouses are supposed to provide storage, functionality and responsiveness to queries beyond the capabilities of today's transaction-oriented databases. Also data warehouses are set to improve the data access performance of databases. Traditional databases balance the requirement of data access w...

Normalization in DBMS: 1NF, 2NF, 3NF and BCNF in Database

Normalization   is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly.  Anomalies in DBMS There are three types of anomalies that occur when the database is not normalized. These are – Insertion, update and deletion anomaly. Let’s take an example to understand this. Example : Suppose a manufacturing company stores the employee details in a table named employee that has four attributes: emp_id for storing employee’s id, emp_name for storing employee’s name, emp_address for storing employee’s address and emp_dept for storing the department details in which the employee works. At some point of time the table looks like this: emp_id emp_name emp_address emp_dept 101 Nikhil Kangra D001 101 Nikhil Kangra D002 123 Ashish Shimla D890 166 Rahul Pathankot D900 166 Rahul Pathankot D004 The above table is not normalized.  Update anomaly : In the above table we have two rows for employee Nikhil as he belongs ...