For loop compilation error

Question:

I'm making a program that asks how many notes the user is going to type and after that it goes into a 'for' loop asking what notes to type. The grades are stored in an array and finally the average is calculated.

#include <iostream>
using namespace std;

int main(){

int qt, tot, med;
cout << "Quantidade de notas: ";
cin >> qt;

int nt[] = {};

for(i = 0; i <= qt; i++){
    cout << "Digite a nota " << i+1 << " : " << endl;
    cin >> nt[i];
    tot = tot + nt[i];
}

med = (tot / qt);

cout << "Media = " << med << endl;

return main();
}

The problem is that whenever I try to compile, the following error appears:

 'i' was not declared in this scope
  for(i = 0; i <= qt; i++){

Answer:

There are several errors in the code, when you solve this one will show others. Let's fix at least one part:

#include <iostream>
using namespace std;

int main() {
    cout << "Quantidade de notas: ";
    int qt;
    cin >> qt;
    int nt[qt] = {}; //isto é mais C que C++
    int tot = 0;
    for (int i = 0; i < qt; i++) {
        cout << "Digite a nota " << i + 1 << " : " << endl;
        cin >> nt[i];
        tot += nt[i];
    }
    cout << "Media = " << tot / qt << endl;
}

See working on ideone . And at Coding Ground . Also posted on GitHub for future reference .

The array had no size and would corrupt memory.

The iteration variable for was not declared as the compiler reported.

The counter went to one position after the entered size.

You can't call the same function without an exit condition and it's not too long for stackoverflow .

It may be that you want averages with decimal part, this code does not allow that.

The rest is more cosmetic.

Scroll to Top