Output issue

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cmath>
#include <conio.h> 

using namespace std;
int funtion1(double x, double &y, double A[]);
int function1(double x, double &y, double A[]) {
	int i;  double sum; 
	x = 1.1; y = 2.1;  A[3] = 3.1;  sum = 0.0;
	for (i = 1; i <= 3; i++) sum += A[i]*A[i];
	cout << "\nsum = " << sum;
	return i + (int)y; 
} 


int main() {
	double x1 = 4.1, y1 = 5.1, A[4] = { 1.0, 2.0, 3.0, 4.0 }, ans; 
	ans = function1(x1, y1, A);
	cout << "\nfunction 1 = " << ans << x1 << y1 << A[3];

	cout << "\ndone.\n";
	getch();

	return 0;
}
why isn't it just 14.61 since 1.0*1.0+2.0*2.0+3.1*3.1=14.61

The actual sum is 2.0*2.0 + 3.0*3.0 + 3.1*3.1 = 22.61
Can you see why?
Last edited on
Yeah, I have literally just realized that the array count starts from 0 therefore should start from 2.0! Thank you so much for answering
what about the return i+ int (y). what would be the value of i in this case?
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"
Topic archived. No new replies allowed.