+ 1
PLEASE EXPLAIN THE OUTPUT OF THIS CODE??
I'm especially confused about the "for" loop with a (;;) after. What does that mean? What does it mean? Also, why does the code output 4? https://code.sololearn.com/cSKBBV6Zzgt3
2 Answers
+ 4
Jackson Meddows
about the for loop.
The for loop usually gets 3 'arguments':
for(initialization; condition; increment)
It happens that all of them are optional, it means you can skip them.
But you still have to put the semicollons.
If you have nothing to initilize and you are not going to increment/decrement anything
you can let initialization and the increment section empty and it works.
If you leave the condition section empty it means the condition is always true
and you create an infinite loop.
EDITED:
using namespace std;
int main() {
int a[]={15,4,23,8,6,11};
int c=0;
for(;;){
if(a[c]%5==1)
break;
c++;
}
cout<<c;
return 0;
}
In your code you are doing the initialization part before the loop (int c = 0);
the increment part is inside the loop (c++);
and the condition part is also inside the loop (a[c]%5 == 1).
This means the loop stops when the value of array 'a' at index 'c' divided by 5 has a remainder of 1.
If you follow the iterations:
.when c = 0 then a[c] = 15. Now 15 % 5 is 0 (zero) which is different of 1. Loop does not break. 'c' increments.
. when c = 1 then a[c] = 4. Now 4 % 5 is 4 which is different of 1. Loop does not break. 'c' increments.
.when c = 2 then a[c] = 23. (23 % 5 = 3) != 1.
. c = 3 then a[c] = 8. (8 % 5 = 3) != 1.
. c = 4 then a[c] = 6. (6 % 5 = 1) == 1. Loop breaks.
value of 'c' is printed out, which is 4.
+ 1
Ulisses Cruz
Thank you for your answer! It was very helpful!