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

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

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 following header files important to C++ pro