-1

I'm trying to add element in the vector. I want to add all even numbers from 10 to 21. But I'm getting the error. Can someone please tell me how to fix it.

int main()
{
vector<int> vect_name;
for (int i=10; i<21; i=i+2)
    vect_name.push_back(i);
    cout << vect_name[i] <<endl;

return 0;

}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
rida
  • 41
  • 5

3 Answers3

1

I don't see any reason why you should be printing the contents of the vector with the same index variable which is looping around the even numbers that you are adding. Perhaps, you should structure your code this way :

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> vect_name;
    //push to vector
    for (int i=10; i<21; i=i+2) {
        vect_name.push_back(i);
    }

    // print the contents of vector
    for (size_t i =0; i < vect_name.size(); ++i) {
        cout << vect_name[i] << " ";
    }
    cout << '\n';

    return 0;    
}
Rishi
  • 1,387
  • 10
  • 14
  • Please don't encourage omitting braces around loop bodies. https://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar Oct 26 '17 at 05:10
0

This is because you are missing a brace of the for loop. The looping variable you created in the for loop has a scope limited to it's braces, since you are missing the braces it takes just the next line only.

Because of that the loop variable i is not available

 int main()
{
vector<int> vect_name;
for (int i=10; i<21; i=i+2)
   vect_name.push_back(i);


for(int i=0; i<vect_name.size(); i++)
   cout << vect_name[i] <<endl;

return 0;

}

This should fix it.

Saram Ali Azhar
  • 234
  • 1
  • 18
0

You must be getting this error

error: ‘i’ was not declared in this scope
cout << vect_name[i] <<endl;
                  ^

Enclose the statements in parentheses to indicate loop body. Without the braces, only one following statement is taken as loop body.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vect_name;
    for (int i = 10; i < 21; i = i + 2) {
        vect_name.push_back(i);
        cout << vect_name[i] << endl;    // Will print zeroes
    }
    return 0;
}

However this will still give wrong results because arrays/vectors are 0 indexed in C++. You need to print in a separate loop.

A correct version of code will look like

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v(6, 10);
    for (int i = 0; i < v.size(); i++) {
        v[i] += (i * 2);
        cout << v[i] <<endl;
    }
    return 0;
}

Output

10
12
14
16
18
20
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50