0

I made a program which allows the user to enter the dimension of an array and the array values itself. The code runs fine however whenever the first row of the array seems to repeat itself.

E.g For the A[n][n] Array when n = 2, and I enter values for array such as 1,6,4 and 3, the code outputs an array of [1,6][1,6].

Might be easier to understand if you ran the code yourself:

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

void v_in();
// void v_out;

void v_in()
{
    int i,j,n;
    int A[n][n];


    cout << "Enter the dimension of your matrix. Enter a value between 1-20.\n";
    cin >> n;
    if(n < 1)
    {
        cout << "\nValue enter is out of range. The value of n is now 1.\n";
        n = 1;
    }
    else if(n > 20)
    {
        cout << "\nValue enter is out of range. The value of n is now 20.\n";
        n = 20;
    }

    cout << "Enter values the array A[" << n << "][" << n << "].\n";
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            cin >> A[i][j];
        }
    }

    cout << "\n\nA = \n";
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            cout << A[i][j] << "\t";
        }
        cout << "\n";
    }

}

int main()
{
    string answer;

    cout << "\nWould you like to run the matrix program?\n";
    cin >> answer;

    if(answer == "yes" || answer == "Yes" || answer == "YES")
    {
        v_in();


        cout << "\nEnd of program.\n";
    }
    else
    {
        cout << "\nEND.\n";
    }
    return 0;
}
  • `int i,j,n; int A[n][n];` -- Sigh. Another new programmer gets taken in by this piece of non-C++ code. First, `n` isn't initialized to a value. Second, even if `n` were initialized `A[n][n]` is not legal C++. Blame g++ or whatever your compiler you're using that allows this syntax. Arrays in C++ must have their sizes denoted by a constant expression, not a variable. – PaulMcKenzie Nov 13 '18 at 01:05
  • *I made a program which allows the user to enter the dimension of an array and the array values itself* -- Use `std::vector> A(n, std::vector(n));` That is how you declare dynamic arrays in C++. – PaulMcKenzie Nov 13 '18 at 01:08

1 Answers1

0

Consider replacing

int A[n][n];

with

int A[20][20];

I think you'd be better off using std::vector or std::array, but you certainly can't initialize an c-style array with an uninitialized local variable.