c++ - Iteration counter not incrementing -
i wrote program in c++ print primes 100, writes "hello world"
, , hangs. why that?
#include <iostream> bool is_prime(int num) { if(num == 1) { return false; } for(int = 2; < num; i++) { if(num % == 0) { return false; } } return true; } int increase(int i) { return i++; } int main() { std::cout << "hello world!!" << std::endl; int = 1; while(i < 100) { = increase(i); if(is_prime(i)) { std::cout << << " prime" << std::endl; } } }
return i++;
statement return original value of i
, not incremented one.
you need return ++i;
or return + 1
(thanks @interjay pointing that). later return + 1;
makes clear return value matters, , not new value of i
.
the effect of post increment i++
visible on next line (or usage of i
).
not sure, if need separate method incrementing variable i
, can @ in while loop.
while(i < 100) { if(is_prime(i)) { std::cout << << " prime" << std::endl; } i++; }
you can use for
loop, instead of while
since working range of values.
for(i = 1; < 100; i++) { if(is_prime(i)) { std::cout << << " prime" << std::endl; } }
Comments
Post a Comment