/* As we are assigning random value during the run time, we just have to dynamically allocate the memory and use the pointer as a 2D array directly and assign random values to this 2D array. Here the memory
allocated is only for the columns, now for the rows we just need a for
loop and assign the value for every row a dynamic memory. We can use
the pointer just the way we use a 2D array.*/
// Assigning random values to a 2D array #include<iostream> #include<iomanip>#include<stdlib.h> using namespace std; int main() { int x = 3, y = 3; //user can also ask these value during runtime int **ptr = new int *[x]; for(int i = 0; i<y; i++) { ptr[i] = new int[y]; } srand(time(0)); for(int j = 0; j<x; j++) { for(int k = 0; k<y; k++) { int a = rand()%10; ptr[j][k] = a; cout<<ptr[j][k]<<" "; } cout<<endl; } system("pause");rerutn 0;}
ScreenShot:
![C++ Program to Assign random values to a 2D array through "rand()" Function C++ Program to Assign random values to a 2D array through "rand()" Function](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjC58AFIIInJK2siemUWuUXATwZ35f8k3_20ULaRccuVz9ZRB0diT23nKKMyvm6rlL1_ASqYcrpzwQAJdVMmVY5yjcgwERfPYFMqTRrN81QjeWGEug40fypxeVfx5-Ja5RsWRzhOf_Nsi_a/s1600/random.png)
0 comments:
Post a Comment