Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop with condition only

Tags:

c++

for-loop

Can someone explain how the for(; A--;) loop works. It doesn't have any increments, so shouldn't it run forever ?

int main(){
int A, B;

cout << "Anna t\x84htien m\x84\x84r\x84: "; //Give ammount of stars: 
cin >>A;
cout << endl;

for(; A--;){
    for(B = 0; A >= B; B++){
        cout << "* ";
    }
    cout << endl;
}

return 0;
}
like image 910
VortexP Avatar asked May 20 '26 06:05

VortexP


1 Answers

A for loop runs for as long as its condition holds true. A-- is equivalent to A-- != 0, so this is how long it's going to run.

One thing that is possibly nice to know is that a for loop can contain a lot more than mere incremental operations. Usually, it's something like ++i, but that is no necessity. In school, you might not learn about how general for loops actually are, though.

like image 59
cadaniluk Avatar answered May 21 '26 19:05

cadaniluk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!