DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

2D Array in C++

C++ 2D Array:

We will create 2 D array and will set the value then get the values from it.

source code:

/*
Program: 2D array
Author: Alpha Master
Date: 14 Nov 2021
*/

//Header File
#include<iostream>


const static int size = 5;

int main()
{
 	std::cout<<"2D Array"<<std::endl;
	
	//allocate memory
	int** p = new int*[size];
	for(int i =0; i<size; i++)
	{
		p[i] = new int[size];
	}

	//set the value
	int count = 0;
	for(int j =0; j<size; j++)
	{
		for(int z =0; z<size; z++)
		{
			count++;
			p[j][z] = count; 
		
		}
	}

	//display
	for(int m =0; m<size; m++)
        {
                for(int n =0; n<size; n++)
                {
			std::cout<<p[m][n]<<" ";
                }
		std::cout<<std::endl;
        }

	//delete the heap memory otherwise it will be memory leak
        //its programmer responsibility
	for(int g =0; g<size; g++)
	{
		delete[] p[g];
	}

	
    	return 0;
}

Output:

2D Array
1 2 3 4 5 
6 7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 
21 22 23 24 25 

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer