#include <iostream>
int main()
{
int myArray[5]; // array of 5 integers lol
int i;
for (i=0; i<5; i++ ) // 0 - 4
{
std::cout << "Value for myArray[" << i << " ]: ";
std::cin >> myArray[i];
}
for (i = 0; i<5; i++)
std::cout << i << ": " << myArray[i] << std::endl;
return 0;
}
Why is i++ required for this program to work?
Because if you don't execute i++
(or any other statement which increments i
), i
will remain 0
, the condition i < 5
will always remain true and the loop will never end.
The ++ is the increment operator, and increments the value of i in each iteration of the loop.
i++ is just a short hand for
i = i + 1;
If you don't increment your loop counter then the loop will never end for example this would be an infinite loop
for(i = 0; i < 5; i+ 1)
/*do something*/
i++ increases the i variable.. you can also use i-- in the loop to decrease the i variable.
Or even i+=2 to increment the variable by two.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.