Why the output is 20 ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Why the output is 20 ?

#include <iostream> using namespace std; int main() {int a=1; int b =9; a= ++b; cout<<a+b; }

28th Sep 2019, 10:52 AM
Harshit Nema
Harshit Nema - avatar
6 Answers
+ 5
Answer is: a=++b means a=10 because int b=9 so pre increment of b is 10. Then a=10,b=10 .so final answer of a+b= 20
29th Sep 2019, 7:30 AM
Kiran Kumar
Kiran Kumar - avatar
+ 5
a=++b ; means a=b+1 ; given b=9 a=10 a+b a=10 and b=10(as ++b incremented b also) so OUTPUT: 20
29th Sep 2019, 5:54 PM
Aditya
Aditya - avatar
+ 3
Pre increment operator increments value of <b> before returning the result. So that when you assigned ++b to variable <a> the value of <b> had been incremented to become 10. Then value of <b> is assigned to variable <a>, which makes both value of <a> and <b> equal 10. Next you output <a> (10) + <b> (10). And that's how it outputs 20.
28th Sep 2019, 11:05 AM
Ipang
+ 2
Thank you .
28th Sep 2019, 11:41 AM
Harshit Nema
Harshit Nema - avatar
+ 1
Ipang does it the giving value of 10 to b too?
28th Sep 2019, 11:07 AM
Harshit Nema
Harshit Nema - avatar
0
~ swim ~ What if I wrote b++?
28th Sep 2019, 11:36 AM
Harshit Nema
Harshit Nema - avatar