This is the code and here is the image of output , i need these output to be only n's and 0 but i have these numbers for some reason. How to fix that and replace these numbers by 0's?
#include <iostream>
using namespace std;
int main()
{
int n = 9;
int matrix[n][n];
int x = 1;
// output array element's value
for (int i = 0; i < 9; i )
{
for (int j = 0; j < 9; j )
{
matrix[i][0] = x;
matrix[i][n - 1] = x;
matrix[i][i] = x;
}
}
for (int i = 0; i < 9; i )
{
for (int j = 0; j < 9; j )
{
std::cout << matrix[i][j] << " ";
}
std: cout << "\n";
}
return 0;
}
CodePudding user response:
The code does not initialise the values of the matrix, apart from a few places. You need to write zeros everywhere else, otherwise you get whatever data was in the memory beforehand (strictly this is 'undefined behaviour', and the program could do anything, but in practice you will print out whatever happened to be in the memory the program uses before it ran)
CodePudding user response:
i need these output to be only n's and 0
- For
0
to be guaranteed to appear, you need to initializematrix
(or explicitly assign0
to the rest of the elements). This is simply done withint matrix[n][n]{};
(zero initialization). Reading uninitialized values, like you currently do, makes the program have undefined behavior and printing "garbage" values is one possible outcome. - For
n
s to appear, you need to assign the elements the value held byn
. You currently assign the value ofx
to the elements inmatrix
. - The inner assigning loop,
j
, doesn't do anything but repeating the same thing 9 times. Just remove it.
#include <iostream>
int main() {
constexpr int n = 9; // int n = 9; makes `matrix` a non-standard VLA
int matrix[n][n]{}; // zero initialization
for (int i = 0; i < 9; i ) {
matrix[i][0] = n; // n
matrix[i][n - 1] = n; // n
matrix[i][i] = n; // n
}
for (int i = 0; i < 9; i ) {
for (int j = 0; j < 9; j ) {
std::cout << matrix[i][j] << ' ';
}
std::cout << '\n';
}
}
Output:
9 0 0 0 0 0 0 0 9
9 9 0 0 0 0 0 0 9
9 0 9 0 0 0 0 0 9
9 0 0 9 0 0 0 0 9
9 0 0 0 9 0 0 0 9
9 0 0 0 0 9 0 0 9
9 0 0 0 0 0 9 0 9
9 0 0 0 0 0 0 9 9
9 0 0 0 0 0 0 0 9
CodePudding user response:
As already pointed out, this is undefined behavior, C doesn't have variable-length arrays, and the program is displaying whatever junk is left in memory. I'd suggest defining the matrix in Globals, outside main.
#include <iostream>
using namespace std;
int matrix[9][9];
int main(){
int n = 9;
//int matrix[n][n];
int x = 1;
// output array element's value
for (int i = 0 ; i < 9 ; i )
{
for(int j = 0 ; j < 9 ; j )
{
matrix[i][0] = x;
matrix[i][n-1] = x;
matrix[i][i] = x;
}
}
for (int i = 0 ; i < 9 ; i )
{
for(int j = 0 ; j < 9 ; j )
{
std::cout << matrix[i][j]<< " ";
}
std:cout << "\n";
}
return 0;
}