Home > database >  (C ) Why is the code written in the description/body of this question giving 10(all) 0's as th
(C ) Why is the code written in the description/body of this question giving 10(all) 0's as th

Time:11-27

int main()
{
    vector<int> g1;
  
    for (int i = 1; i <= 10; i  )
    {
     g1.push_back(i * 10);
     cout << g1[i] << " ";
    }
    
}

The above written code is giving me output as "0 0 0 0 0 0 0 0 0 0" that 10 0's with a space after each 0 of them, as written in the code. But in the code, it is written to add at the end of the vector the iterator*10:

g1.push_back(i * 10);

and the output code

cout << g1[i] << " ";

is giving 0 for every iterations(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) when it should be giving:

10 20 30 40 50 60 70 80 90 100

as the output

Output:

0 0 0 0 0 0 0 0 0 0

Expected output:

10 20 30 40 50 60 70 80 90 100

CodePudding user response:

 cout << g1[i] << " ";

should be

 cout << g1[i - 1] << " ";

In C arrays and vectors use zero based indexing.

CodePudding user response:

As cigien and G.M. explained in the comments to the question above, over here in the code, the iteration should start at 0 since in the vector the indices start at 0 or else the g1.push_back(i * 10); part of the code can give anything because that's undefined behavior as pointed out by πάντα-ῥεῖ in the comments of this answer.

So either for (int i = 1; i <= 10; i ) needs to be modified to be for (int i = 0; i < 10; i ) or as noted by ceorron in their answer we can have cout << g1[i] << " "; modified to be cout << g1[i - 1] << " "; to make the code give expected output after compilation and execution.

  • Related