Is there an error in my program?

I'm writing a c++ program that averages integers in rows using a nested FOR loop, but it's giving me an error? it's saying I need a constant in line 21 where int matrix [rows][columns]. My tutor sees nothing wrong and its compiling for them? I'm confused, do yall see an error?
My program:
1.asking user to first enter the number of rows, then the number of columns
2.In a nested FOR loop, asks the user to enter the column data for each row
3.Adds up the data for each row and derives an average for each row
4.Also adds up all the data in a total and derive an average


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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
  Put the code you need help with here.#include <iostream>
using namespace std;

int main()

{
    // intializing number of rows, coloumns and the total
    int rows, coloumns, total = 0;

    // variable for the average
    float average = 0;

    // asking user for the number of rows and coloumns
    cout << " Enter the number of rows: ";
    cin >> rows;

    cout << " Enter the number of coloumns: ";
    cin >> coloumns;

    // intializing the 2D matrix array ie the table
    int matrix[rows][coloumns];

    // looping through i and j for getting each value of the table
    for (int i = 0; i < rows; i++)

    {

        for (int j = 0; j < coloumns; j++)

        {

            cout << "Enter data for " << i << "  " << j << ":";

            cin >> matrix[i][j];

        }

    }

    // looping through each element to find the row sum
    for (int i = 0; i < rows; i++)

    {

        // resetting row variable for each row
        int rowAverage = 0;

        for (int j = 0; j < coloumns; j++)

        {

            // adding each value to the row and total
            rowAverage += matrix[i][j];

            total += matrix[i][j];

        }

        // printing the average of each row
        cout << "Row Average is:" << (float)rowAverage / coloumns << "\n";

    }

    // printing the average of total table
    cout << " Average of all data is " << (float)total / (rows * coloumns);

    return 0;

}
Standard C++ doesn't allow variable length arrays.

But some compilers will accept them 'as an extension'.

1
2
3
4
5
6
7
8
9
10
11
$ g++ -Wall -pedantic foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:21:30: warning: ISO C++ forbids variable length array ‘matrix’ [-Wvla]
     int matrix[rows][coloumns];
                              ^
foo.cpp:21:30: warning: ISO C++ forbids variable length array ‘matrix’ [-Wvla]
foo.cpp:11:11: warning: unused variable ‘average’ [-Wunused-variable]
     float average = 0;
           ^
$ 
$ g++  foo.cpp


Knowing the difference between what the standard guarantees and what your current compiler will let you get away with is vital.
Something your tutor needs to learn as well.


https://howtodiscuss.com/t/iso-c-forbids-variable-length-array/45286
https://en.wikipedia.org/wiki/Variable-length_array

So... VLA (Variable Length Arrays) are seen as optional in many languages, including C. They may be less efficient than constant length arrays, or at least produce overly complex assembly code (someone could test this point). The key point is that C++ never adopted it, so they should be avoided in good C++ code.

This is a very interesting aspect of the differences in the standards, and how C++ has forked away from C standards, thank you BlueCOCO1, I never knew about this.
at the worst case, a VLA would be replaced by a vector quietly, costing the construction (memory allocation and destruction) and microscopic performance hits. I mean it could try to do it some other way, but that would get it done with minimal chaos.
@jonnin - Keep in mind that VLAs are allocated on the stack, not the heap. vector uses the heap.

The usual C compiler implementation of a VLA of type T is:
1. Compiler reserves a pointer of type T on the stack
2. ptr = top of stack
3. top of stack is extended by n * sizeof(T)
No special cleanup is necessary of the VLA when the function exits. It is simply popped off the stack along with the reset of the local variables when the previous frame is restored.

Hello BlueCOCO1,


My tutor sees nothing wrong and its compiling for them?


If your tutor sees nothing wrong with this code then get a new tutor.

To start with there are no "#include"s, so the program will not compile or run.

It is best not to use using namespace std;, but for now keep thinking it is really great until it gives you a problem.

The comment on line 7 is misleading.

Line 8 defines "rows" and "columns", but "total" is the only variable initialized.

Line 11 is defined as a "float". It would be better as a "double". Then you initialize it with an "int".

From C++11 on you have the uniform initializer, the {}s. Empty {}s the compiler will initialize the the variable with the proper type of zero based in the variables type. As an example: double average{}; will set the vriable to "0.0".

ALWAYS initialize all your variables.

Since the VLAs have been discussed you could do something like this:
1
2
3
4
5
6
7
8
9
int main()
{
    constexpr int MAXROWS{ 3 }, MAXCOLS{ 5 };
    // initializing number of rows, columns and the total
    int matrix[MAXROWS][MAXCOLS];

    int rows{}, columns{}, total{};  // <--- ALWAYS initialize all your variables.

    cout << " Enter the number of rows (maximum " << MAXROWS << "): ";

Then when you enter a value for "rows" and "columns". That would be the part of the array used.

Line 46 "rowAverage" is a misleading name maybe something like "rowTotal".

In line 60 type casting "rowAverage" to a float will always end in "?.000000". and instead of using (float) use "static_cast<double>(variableName)". The old C style cast works, but you should be using the newer C++ form.

It is good that you are making use of blank lines, but you are using to many.

Have a look at this:
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58


using namespace std;

int main()
{
    constexpr int MAXROWS{ 5 }, MAXCOLS{ 6 };
    // intializing number of rows, coloumns and the total
    int matrix[MAXROWS][MAXCOLS];

    int rows{}, coloumns{}, total{};  // <--- ALWAYS initialize all your variables.

    // variable for the average
    float average = 0;

    // asking user for the number of rows and coloumns
    cout << " Enter the number of rows (maximum " << MAXROWS << "): ";
    cin >> rows;

    cout << " Enter the number of coloumns: ";
    cin >> coloumns;

    // intializing the 2D matrix array ie the table
    //int matrix[rows][coloumns];

    // looping through i and j for getting each value of the table
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < coloumns; j++)
        {
            cout << "Enter data for " << i << "  " << j << ":";
            cin >> matrix[i][j];
        }
    }

    // looping through each element to find the row sum
    for (int i = 0; i < rows; i++)
    {
        // resetting row variable for each row
        int rowAverage = 0;

        for (int j = 0; j < coloumns; j++)
        {
            // adding each value to the row and total
            rowAverage += matrix[i][j];

            total += matrix[i][j];
        }

        // printing the average of each row
        cout << "Row Average is:" << (float) rowAverage / coloumns << "\n";
    }

    // printing the average of total table
    cout << " Average of all data is " << (float) total / (rows * coloumns);

    return 0;  // <--- Not required, but makes a good break point for testing.
}

I did not change everything that is needed or have had a chance to compile and test yet.

Andy
Hello BlueCOCO1,

When I said there are no includes in the program I did not see the "#include <iostream>" because it is hiding at the end of the first line that I did not copy.

Sorry about that.

Andy
garbage in - garbage out. Print the contents of the array after you input it. If it's garbage then you entered an illegal character. My guess is that you're entering a floating point value (like 1.4, 3.14 or 2.0) which won't work since the array is integers.
Topic archived. No new replies allowed.