Reputation: 480
The Expected Output is 2000 but it stops on 1980.
Note: The Execution is started from 20 and not from 0 as int i = 1
The Code:
#include <iostream>
using namespace std;
int main() {
const int iarraysize = 100;
int i = 1;
int iarray[iarraysize];
while (i < iarraysize) {
iarray[i] = 20 * i;
cout << iarray[i++] << "\n";
}
}
Upvotes: 4
Views: 72
Reputation: 505
The array goes from 0 to 99, you start at 1 and it only goes to 99 (99*20=1980).
You're expecting 2000 but there's no iarray[100]
(array out of bounds).
Upvotes: 3
Reputation: 311088
The last value of the variable i
that is less than 100 is 99. So 20 * 99 is equal to 1990
.
If you want to get 2000 then rewrite the loop like
int i = 0;
while (i < iarraysize) {
iarray[i] = 20 * (i + 1);
cout << iarray[i++] << "\n";
}
Upvotes: 3
Reputation: 63117
Arrays start at 0, and end one before their size.
You don't need an array however.
#include <iostream>
int main()
{
int limit = 100;
int i = 1;
while (i <= limit)
{
std::cout << (i++ * 20) << "\n";
}
}
Upvotes: 4