How this program outputs 3? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
11th Mar 2021, 4:23 PM
Jawahirullah
Jawahirullah - avatar
3 Answers
12th Mar 2021, 3:39 AM
A͢J
A͢J - avatar
+ 2
Your code : #include <iostream> using namespace std; int main() { int val=0; for(int i=0;i<7;i++) val+=i%2; cout<<val; return 0;} Here intial value of val is 0 , in for loop you are adding i%2 in val. i%2 will add 1 whenever i will be odd number. Your loop is from 0 to 7. In first iteration val+=i%2 will add nothing in val as i=0 as 0%2=0. At second time i will be 1 so 1%2=1 , and here 1 will be added in val so it will became 1. At next 2%2=0 , so val=1 next 3%2=1 so val =2 , next 4%2=0 so val =2 , next 5%2=1 so val =3 , next 6%2=0 so val =3. And after that i will be 7 and therefore loop will be breaked. So finally the value of val is 3 . That's why it's output is 3.
11th Mar 2021, 4:56 PM
Hrutik Bhalerao
Hrutik Bhalerao - avatar
+ 1
0%2 = 0 1%2 = 1 2%2 = 0 3%2 = 1 4%2 = 0 5%2 = 1 6%2 = 0 0+1+0+1+0+1+0 = 3
11th Mar 2021, 4:47 PM
Igor Kostrikin
Igor Kostrikin - avatar