program is runing but giving me wroung output.plz corrct me

how to initilize (N*N) matrix with random number in the range 1-9.

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
#include<iostream>
#include<conio.h>
#include <stdlib.h>
#include <time.h>
const int n=9;
using namespace std;
void initilization (int arr[3][5],int n)
{
for (int i=0;i<n;i++){
for(int j=0;j<n;j++)

arr[i][j] = (rand()%9) + 1;
{
cout<<arr[i]<<" ";}
cout<<endl;
}}
int main(){
int arr[3][5];
cout<<"the random no are"<<endl;
initilization(arr,n);
getch();


}
First of all the syntax of the syntax of your custom functiin must be
void initilization (int arr[][cols],int n);
Also, the reason for that output is because you constant n=9 and your array has max elements(columns) of 5. This amounts to diplaying other content in memory which are not in your array's scope.

Aceix.
Last edited on
And not just displaying, but also updating, which is worse, as it could have unpredictable side-effects.

Here I've separated out the array initialisation from the displaying of the contents.
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
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>

using namespace std;

const int rows = 3;
const int cols = 5;

void initialization (int arr[][cols])
{
    for (int i=0; i<rows; i++)
        for(int j=0; j<cols; j++)
            arr[i][j] = (rand()%9) + 1;
}

void display(int arr[][cols])
{
    for (int i=0; i<rows; i++)
    {
        for(int j=0; j<cols; j++)
            cout << arr[i][j] <<" ";
        cout<<endl;
    }
}

int main()
{
    int arr[rows][cols];
    initialization(arr);
    cout << "the random no are" << endl;
    display(arr);
    
    getch();
}
Last edited on
thank you dear
Topic archived. No new replies allowed.