Hello experts, I am fairly new to this forum. I need help with understanding the output of the following program.
the outcome is:
"sum = 22.61
function 1 = 64.12.13.1
done."
what I don't understand is why would the first sum be 22.61, why isn't it just 14.61 since 1.0*1.0+2.0*2.0+3.1*3.1=14.61, in fact I can see that return i+ (int) y yielded the 8, but what I fail to see is why did the compiler took the return and added it to sum.
Thank you so much, I am a new to C++, excuse my blatant ignorance.
Some cleaning: line 6 is not needed because function1 is implemented before/above the main function. If line 6 had been necessary, the typo in "function1"would have crashed your build.
note that the index from an array position starts at 0, so initially A[0]=1.0 and A[3]=4.0 and A[4] does not exist.
Then for the math:
1. Your program starts at the main.
2. x1 becomes 4.1, y1 becomes 5.1, A becomes [1.0, 2.0, 3.0, 4.0]
3. function 1 is called with the arguments: x=4.1, y=5.1, A=[1.0, 2.0, 3.0, 4.0]
(y is called by reference and an array is always provided by reference, x is called by value, so x1 will not be effected by anything that happens inside function1)
4. x becomes 1.1, y becomes 2.1, A becomes [1.0, 2.0, 3.0, 3.1] (line 9)
// One should wonder why you provide argument x in the first place
5. Calculations inside the for-loop
--- i=1: A[1] = 2.0 => 2.0 * 2.0 = 4.0 -> sum became 4.0
--- i=2: A[2] = 3.0 => 3.0 * 3.0 = 9.0 -> sum became 13.0
--- i=3: A[3] = 3.1 => 3.1 * 3.1 = 9.61 -> sum became 22,61
--- i=4: the loop stops because 4<=3 is false.
6. the sum of 22,61 is printed to the console
7. function1 returns i+(int)y = 4+2 = 6
8. the main routine prints to the console "function1 =" << 6 << 4.1 << 2.1 << 3.1 << "\ndone\n"
// since there are not spaces or tabs between the values this will look like "\nfunction1 =64.12.13.1\ndone\n"