Building a basic calculator - Question in sequencing? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Building a basic calculator - Question in sequencing?

So I'm building a calculator by defining 3 variables - 'a' , 'b' and 'sum'. The calculator works fine if I define 'sum = a + b' AFTER asking for the input. But I define it BEFORE asking for the input it just generates some random number. So what's the deal with that? Shouldn't the variable sum remain same regardless of the positioning?

27th Jul 2017, 5:59 PM
Rahul Chaudhary
Rahul Chaudhary - avatar
3 Answers
+ 2
the flow of program is very important . summation must be done after getting values...
27th Jul 2017, 6:03 PM
Ashwaghosh Sadanshiv
Ashwaghosh Sadanshiv - avatar
+ 2
Variables that are local and are not initialized will have undefined behaviour in C++. (Assuming the variable isn't static)
27th Jul 2017, 6:05 PM
Rrestoring faith
Rrestoring faith - avatar
0
It's a big deal for a variable, whose value depends on immutable objects. When you define `sum = a + b` before asking for input, what is the value of `a` and `b`? Once `sum` is bind to `a + b`, it's value will remain the same throughout the program regardless of what value to `a` or `b` changes afterwards. ``` a = 80 b = 8 sum = a + b print(sum) # >> 88 a = int(input("Enter an integer")) b = int(input("Enter another integer")) print(sum) # >> 88 # Old values of `a` and `b` are there in memory, until they're not required # by your program, in which case garbage collector will erase them from # memory. They are immutable, you can't change them. You can only change # the binding of variable, pointing to them, to point to some other value. ``` Strings/Integers are immutable values, in simple terms, let suppose that you bind an integer to a variable. Now you want to do some fancy operation on it or you've written a function which does that. Now when you pass this value to function, a copy of that value is passed. The original value remain as it is. But if it was an array, which is mutable, it's "reference" would have been passed to the function. ``` magic_num = 419 ref = magic_num magic_num = 785 # here you might think that you've changed the integer 419 to 785. Nope, # the int 419 is still in memory, you've only change the `magic_num` to binding. # Now if you change the magic_num to somehthing else, magic_num = 1337 # 785 will be erased from memory by garbage collector to free up the memory, # as it isn't required by your program. ```
27th Jul 2017, 6:30 PM
its_mastan
its_mastan - avatar