Open In App

How to Create a 2D Array of a Specific Size and Value in C++?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a 2D array is an array of arrays that stores data in the form of a grid with rows and columns. In this article, we will learn how to create a 2D array of a specific size and fill it with some value in C++.

Example

Input: 
rows = 3;
columns = 3;
value = 1;

Output:
2D Array: { {1, 1, 1},
           {1, 1, 1},
           {1, 1, 1} }

Create a 2D Array of a Specific Size and Value in C++

We can create a 2D array of the given size by specifying the size of the rows as the first dimension size and the column size as second dimension size as shown below:

Syntax to Create 2D Array

The syntax for creating and initializing a 2D array in C++ is as follows:

datatype array_name[row_size][column_size];
  • datatype: Specifies the type of elements in the array.
  • array_name: The name of 2D array.
  • row_size: The number of rows in 2D array.
  • column_size: The number of columns in each row of 2D array.

We can then use nested loops to fill the values in a 2D array.

C++ Program to Create a 2D Array of a Specific Size and Value

The below example demonstrates how we can create a two dimensional array and fill it with values in C++.

C++
// C++ Program to illustrate how to create a 2D array of a
// specific size and fill it with values
#include <iostream>
using namespace std;

int main()
{
    // Specify the size of the 2D array
    const int rows = 3;
    const int cols = 3;

    // Initialize a 2D array
    int array[rows][cols];

    // Fill the 2D array with values
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            array[i][j] = 1;
        }
    }

    // Print the 2D array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << array[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

Output
1 1 1 
1 1 1 
1 1 1 


Time Complexity: O(n*m) , here n and m are rows and columns respectively
Auxilliary Space: O(n*m)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads