EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

2D Arrays in C++

Home » Software Development » Software Development Tutorials » C ++ Programming Tutorial » 2D Arrays in C++

2D Arrays in C++

Introduction about 2D arrays in C++

2D Array is considered to be one of the simplest form under the multidimensional array. You can consider the 2D array to be an array of a 1D array so as to comprehend it easily. In this topic, we are going to learn about 2D Arrays in C++.

How 2D arrays defined in C++?

In an easier manner in C++, you can define the multidimensional arrays to be an array of arrays. In a 2D-array you can store the data in the tabular format and also in the row-major order.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The basic form of declaration of N-dimensional arrays :

datatype  arrayname [size1][size2]....[sizeN];
where,
datatype: Type of data that has to be stored in an array.
the datatype is considered to be a valid C++ data type.
arrayname : Name of the array, and
size1, size2, ,... ,sizeN : Sizes of dimensions.

For example:

  • Two dimensional array : int twoarray[10][20];
  • Three dimensional array : int threearray[10][20][30];

Multidimensional arrays size

The total number of elements that we can store in the multidimensional array can be calculated through the multiplication of the size of each and every dimension.

For example:

Array int y[20][10] is able to store 20*10 = 200 elements.
In a simple manner, array int y[10][5][20] can store total (10*5*20) = 1000 elements.

How to create 2D arrays in C++?

Two-dimensional arrays elements can be referred to as y[i][j] wherein i is considered to be the row number and j is considered to be column number.

Popular Course in this category
C++ Training (4 Courses, 5 Projects, 4 Quizzes)4 Online Courses | 5 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.5 (4,890 ratings)
Course Price

View Course

Related Courses
Java Training (40 Courses, 29 Projects, 4 Quizzes)C Programming Training (3 Courses, 5 Project)

Two–dimensional array can be predicted as the table that has got ‘x’ rows and ‘y’ columns. Here row number is from 0 to x-1 and column number is from 0 to y-1.

2D array y with 4 rows and 4 columns is as follows :

Initialization of 2D Arrays: We have got 2 ways wherein the 2D array can get initialized.

First Way:

int y[4][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15}

The above array has 4 rows and 4 columns. The numbers that are in the braces from left to right are stored in the table too in the same fashion. These elements get filled in the array in this way: first 4 elements from the left in the first row, next 4 elements in the second row and similar for the next two rows.

Second Way:

int y[4][4] = {{0, 1, 2, 3}, {4, 5, 6, 7},  {8, 9, 10, 11}, {12, 13, 14, 15}};

This kind of initialization uses nested braces. Every set in these inner braces denotes one row. As we can see in the above example there are in total four rows therefore there exists three sets of inner braces.

Accessing 2D array elements: Elements in the 2D arrays can be accessed through row indexes and column indexes.

For example:

int y[3][1];

This example denotes the element present in the third row and first column.

How to insert elements of 2D arrays in C++?

Below C++ program prompts the user to enter size of the array and then it asks to user to enter array elements and then ask the user to enter element or the number to be inserted, then finally it would be asking the user to enter the position or index where they want to insert the desired element in the array. Thus this program would be inserting the desired element and then displaying the new array after insertion of the element:

// C++  Program : Insert Element in Array
#include<iostream>
using namespace std;
int main()
{
int a[50], size, num, i, pos;
cout << "Enter the array Size : ";
cin >> size;
cout<<"Enter array elements : ";
for(i=0; i<size; i++)
{
cin>>a[i];
}
cout<<"Enter element you want to insert : ";
cin>>num;
cout<<"Where do you want to insert ? ";
cin>>pos;
// now create place at the required position
for(i=size; i>pos; i--)
{
a[i]=a[i-1];
}
a[pos]=num;
cout<<"Element got inserted successfully!\n";
cout<<"New array is : \n";
for(i=0; i<size+1; i++)
{
cout<<a[i]<<" ";
}
return 0;
}

Output:

2D Arrays in C++ output 1

How to update elements of 2D arrays in C++?

Function Template is as below for std::replace_if in C++  :

void replace_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred, const T& newvalue)

where,

  • first, last is the forward iterators to the initial and final position respectively in a list of numbers.
  • pred is the unary function which can accept the element in the range as an argument and then
  • returns a value that can be converted to Boolean.
  • oldvalue: Value that needs to be replaced.
  • newvalue: Replacement value.

Examples are as below:

Input: 1 2 3 4 5 6 7 8 9 10

Output: 0 2 0 4 0 6 0 8 0 10  //Here, we have replaced all odd values to 0.

OR

Input: 10 20 30 30 20

Output: 10 4 30 30 4 // Here, we have replaced all numbers divisible by 4 to 4.

// C++ code that finds all the elements which are odd
// and then replace them with 0.
// using std::replace_if
#include <bits/stdc++.h>
using namespace std;
// Function that is used in std::replace_if
// If the number is odd return 1 otherwise return 0
// 1,that is, true means replace the number
// 0,that is, false means do not replace
bool IsOdd(int i)
{
return ((i % 2) == 1);
}
// Driver/Main code
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
int n = sizeof(a) / sizeof(a[0]);
// print old array
cout << "Original Array:";
for (int i = 0; i < n; i++)
cout << ' ' << a[i];
cout << '\n';
// replacement value
int newval = 0;
// replace_if function
replace_if(a, a + n, IsOdd, newval);
// new array after using std::replace
cout << "New Array:";
for (int i = 0; i < n; i++)
cout << ' ' << a[i]; cout << '\n';
return 0;
}

Output:

2D Arrays in C++ output 2

Conclusion

Thus we can conclude that we know that in order to be able to use any value later, we need to store it into a variable. The variable will have a reference to the memory where this value will be stored so that we are able to use it whenever we want to. Similarly, consider a case where we have hundreds and thousands of such data which needs to be stored in a variable for future reference.

It is not practically possible to store all of these values into variables as we will have to create hundreds and thousands of variables for it. These variables will not even be easy to remember. Thus comes the concept of an array. One type of array is the multidimensional array and is also known as rectangular arrays in C++. Depending on the requirement, it can be a two-dimensional array or a three-dimensional array. The values are stored in a table format, also known as a matrix in the form of rows and columns. The syntax to declare a multidimensional array is –

<data type> <name of array>[number of rows][number of columns] int two_dim[2][2]; // rows = 2 , columns = 2

Recommended Articles

This is a guide to 2D Arrays in C++. Here we discuss how to insert and update elements of 2D arrays in C++ along with the examples. You may also have a look at the following articles to learn more –

  1. Multi-Dimensional Arrays in C++
  2. 2D Arrays in PHP
  3. Arrays in Python
  4. Arrays in Matlab

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

2 Shares
Share
Tweet
Share
Primary Sidebar
C plus plus Programming Tutorial
  • Array
    • Arrays in C++
    • 2D Arrays in C++
    • 3D Arrays in C++
    • Multi-Dimensional Arrays in C++
    • C++ Array Functions
    • String Array in C++
    • C++ Length of Array
    • C++ arraylist
  • Basic
    • Introduction To C++
    • What is C++
    • Features of C++
    • Applications of C++
    • Best C++ Compiler
    • C++ Data Types
    • C++ Double
    • C++ unsigned int
    • User Defined Data Types in C++
    • Variables in C++
    • C++ Keywords
    • Pointers in C++
    • C++ Void Pointer
    • Function Pointer in C++
    • Iterator in C++
    • C++ Commands
    • Object in C++
    • C++ Literals
    • C++ Reference
    • C++ Undefined Reference
    • String in C++
    • C++ Programming Language (Basics)
    • C++ Identifiers
    • C++ Header Files
    • Type Casting in C++
    • C++ Formatter
  • Operators
    • C++ Operators
    • Arithmetic Operators in C++
    • Assignment Operators in C++
    • Bitwise Operators in C++
    • Relational Operators in C++
    • Boolean Operators in C++
    • Unary Operators in C++
    • C++ Operator[]
    • Operator Precedence in C++
    • C++ operator=()
  • Control Statements
    • Control Statement in C++
    • if else Statement in C++
    • Else If in C++
    • Nested if in C++
    • Continue Statement in C++
    • Break Statement in C++
    • Switch Statement in C++
    • goto Statement in C++
    • C++ Struct
    • Loops in C++
    • Do While Loop in C++
    • Nested Loop in C++
  • Functions
    • C++ String Functions
    • Math Functions in C++
    • Friend Function in C++
    • Recursive Function in C++
    • Virtual Functions in C++
    • strcat() in C++
    • swap() in C++
    • strcmp() in C++
    • ceil function in C++
    • C++ begin()
    • size() in C++
    • C++ test()
    • C++ any()
    • C++ Bitset
    • C++ find()
    • C++?Aggregation
    • C++?String append
    • C++ String Copy
    • C++ end()
    • C++ endl
    • C++ push_back
    • C++ shuffle()
    • malloc() in C++
    • C++ reserve()
    • C++ unique()
    • C++ sort()
    • C++ find_if()
    • Reflection in C++
    • C++ replace()
    • C++ search()
    • C++ Memset
    • C++ size_t
    • C++ Substring
    • C++ Max
    • C++ absolute value
    • C++ memcpy
    • C++ wchar_t
    • C++ free()
    • C++ sizeof()
    • C++ Move Semantics
  • Constuctor and Destructor
    • Constructor and Destructor in C++
    • Constructor in C++
    • Destructor in C++
    • Copy Constructor in C++
    • Parameterized Constructor in C++
  • Overloading and overriding
    • Overloading and Overriding in C++
    • Overloading in C++
    • Overriding in C++
    • Function Overloading in C++
    • Function Overriding in C++
    • Method Overloading in C++
  • Inhertiance
    • Types of Inheritance in C++
    • Single Inheritance in C++
    • Multiple Inheritance in C++
    • Hierarchical Inheritance in C++
    • Multilevel Inheritance in C++
    • Hybrid Inheritance in C++
  • Sorting
    • Sorting in C++ 
    • Heap Sort in C++
    • C++ Vector Sort
    • Insertion Sort in C++
    • Selection Sort in C++
  • Advanced
    • C++ namespace
    • Encapsulation in C++
    • Access Modifiers in C++
    • Abstract Class in C++
    • C++ Class and Object
    • What is Template Class in C++?
    • C++ Algorithm
    • Data Structures and Algorithms C++
    • C++ Garbage Collection
    • Virtual Keyword in C++
    • Access Specifiers in C++
    • Storage Class in C++
    • Call by Value in C++
    • Multimap in C++
    • C++ Multiset
    • C++ Lambda Expressions
    • Stack in C++
    • C++ Static
    • C++ static_cast
    • Deque in C++
    • C++ Vector Functions
    • C++ 2D Vector
    • C++ List
    • C++ Mutable
    • Enum in C++
    • Abstraction in C++
    • Signal in C++
    • C++ Queue
    • Priority Queue in C++
    • Regular Expressions in C++
    • C++ Hash Table
    • File Handling in C++
    • C++ Stream
    • ifstream in C++
    • C++ ofstream
    • C++ fstream
    • C++ Read File
    • C++ iomanip
    • Macros in C++
    • Templates in C++
    • C++ setprecision
    • C++ Int to String
    • C++ thread( )
    • C++ Thread Pool
    • C++ thread_local
  • Programs
    • Patterns in C++
    • Star Patterns In c++
    • Swapping in C++
    • Reverse Number in C++
    • Palindrome Program in C++
    • Palindrome in C++
    • Factorial Program in C++
    • Fibonacci Series in C++
    • Square Root in C++
    • Random Number Generator in C++
    • Prime Number in C++
    • Leap Year Program in C++
    • Anagram in C++
    • Armstrong Number in C++
    • Reverse String in C++
    • Socket Programming in C++
    • Matrix Multiplication in C++
    • C++ using vs typedef
    • C++ vector vs list
    • C++ vector vs array
  • Interview question
    • C++ Interview Questions
    • Multithreading Interview Questions C++

Related Courses

C++ Training Course

Java Training Course

C Programming Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C++ Training Course Learn More