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; }
8 Réponses
+ 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
+ 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)
+ 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
+ 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?!
+ 1
@elema thank you so much 🙏🙏
0
Your code is fine!
Tell me wuch compiler you used?
0
@umair ahmadh codeblocks ide with gnu c/c++ compiler
- 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