Problem

#include <iostream>
#pragma hdrstop
using namespace std;

int fun(int x){
return x*x;
}

int main ()
{
int n , i , x, t;


x = 0;
t = 0;
n = 75;




for (i= 1 ; fun (i) < n; i++){
cout << fun(i) << endl;
}
n = n - fun(i);
cout << n << endl;
}

Hey guys. I've got a problem with while or for loop and actually I dont know exactly where it is. When for loop is stoped the value of fun(i) is 64, but the next value is 81, why it's happening?
Last edited on
This is because of a misunderstanding in how for loops work. What it actually does is increments i, and then checks to see if the compare is true. What this means is that it is showing you 1 past the value you want. The easiest way to solve this is simply to pass n = n - fun(i - 1); instead.
is this a troll?
Why would you even do something like this?

8 squared is 64, 9 squared is 81, so results are as expected...

The loop stops when i == 9 and fun(i) == 81 because that is the first value that is equal to or higher than 75.
Yea, but the first one is in for loop, and another value of fun(i) is not in for loop, but the value is still changing, Im interrest about that.
Is it easier to see what's going on if I rewrite the for loop into the equivalent while loop?
1
2
3
for (i = 1 ; fun(i) < n; i++) {
	cout << fun(i) << endl;
}
->
1
2
3
4
5
i = 1;
while (fun(i) < n) {
	cout << fun(i) << endl;
	i++;
}


These two loops are doing the exact same thing.

#include <iostream>
#pragma hdrstop
using namespace std;

int fun(int x){
return x*x;
}

int main ()
{
int n , i , x, t;


x = 0;
t = 0;
n = 75;
i = 1;


while (n > 0){

for (i= 1 ; fun (i) < n; i++){
cout << fun(i) << endl;
}
n = n - fun(i - 1);
i = 1;

cout << n << endl;

}
return 0;
}
I need to find yout all highest square values from 75 to 0. And I have got problem here with subtraction.
I need to find out all highest square values from 75 to 0. And I have got problem here with subtraction.


Why do you need to subtract anything?
Topic archived. No new replies allowed.