0

In the following program When i declare sum=a+b in third line befor cout the compiler gave to me a wrong answer.why?

#include <iostream> using namespace std; int main() { int a, b; int sum; cout << "Enter a number \n"; cin >> a; cout << "Enter another number \n"; cin >> b; sum = a + b; cout << "Sum is: " << sum << endl; return 0; }

24th Dec 2016, 8:25 PM
Hanif
Hanif - avatar
8 Respuestas
+ 3
Leo you're probably just a lonely guy seeking attention online. Not worth the trouble. Anyway Hanif, if your question means that you previously declared sum a+b before cin>>b(that is third line before cout), then it didn't work because b didn't have any value as at the time you declared the equation sum=a+b
24th Dec 2016, 9:24 PM
Cody Arthur
Cody Arthur - avatar
+ 3
exactly hanif. the compiler always starts cimpiling a code from the top of the 'int main' function to the bottom. if you want it to add, subtract, divide or multiply, you must first provide the values of the variables (eg a and b in the case of your example) before bringing the equation (sum=a+b)
24th Dec 2016, 10:26 PM
Cody Arthur
Cody Arthur - avatar
+ 2
because you must always assign values to a and b before you can then find their sum. Imagine a teacher in your school asked you to find the sum of two numbers but told you he would tell you what the two numbers are after you have solved the question. you cannot solve a question like that. that is why cout must come after you've assigned values to the variables. hope this helps
24th Dec 2016, 9:02 PM
Cody Arthur
Cody Arthur - avatar
+ 1
@elema thanks for help sorry one more question do you mean is that the compiler reads statements respectively and when variables a and b get the values then operation of sum conducted?!
24th Dec 2016, 10:04 PM
Hanif
Hanif - avatar
+ 1
@elema thank you so much 🙏🙏
24th Dec 2016, 10:32 PM
Hanif
Hanif - avatar
0
Your code is fine! Tell me wuch compiler you used?
24th Dec 2016, 11:45 PM
Umair Ahmadh
Umair Ahmadh - avatar
0
@umair ahmadh codeblocks ide with gnu c/c++ compiler
25th Dec 2016, 5:20 AM
Hanif
Hanif - avatar
- 1
@elema you are retarded..it's not true..you dont need initial value if you are going to input numbers before action on them ...program works fine for me...here in sololearn you cant have multiple inputs so type number you want then enter then another one and then submit..it should work
24th Dec 2016, 9:06 PM
Leonida17st
Leonida17st - avatar