Click here to Skip to main content
15,936,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I can't figure out why the code while(i<y) outputs an included y.

Here is the code:

C++
#include <iostream>
using namespace std;
                                      
int main() {
	int x, y, i = 0, s = 0, max;
	cout << "enter x y " << endl;
	cin >> x >> y;
	if (x < y) 
		while (i < y) {
			i = x;
			s += x;
			x += 1;

			cout << i << endl;
		}
	else 
		while (i < x) {
			i = y;
			s += y;
			y += 1;

			cout << i << endl;
		}
cout << "sum = " << s << endl;

}


What I have tried:

When I input x=3 and y=6, the output I get is 3 4 5 6.
Why is 6 included while i.
Posted
Updated 24-Oct-23 1:25am
v5

Think about this, you are testing for i < y, then in the while loop you set i = x and then later you increment x.

So when i = 5 you increment x then you check for i so x is set to 6 but i is still 5.
C++
while (i < y) {
i = x;
s += x;
x += 1;

cout << i << endl;
}
 
Share this answer
 
Comments
Mike Hankey 22-Oct-23 11:07am    
Because the last time through i which is 5 is less than 6 and then you set i to 6.
kozlok 22-Oct-23 11:21am    
after setting i to 6 , i wouldn't then check the while condition wich is less then 6 so i=6 wouldn't be executed ?
Mike Hankey 22-Oct-23 12:09pm    
For x=3 and y=6

Loop: i x x+1 prints
-----------------------------
3 3 4 3
4 4 5 4
5 5 6 5
passes i
6 6 7 6
i=6 is not less than 6 so it fails
If you just need to sum number from x to (y-1), then why don't you simplify the approach?
The following code would do the trick:
C++
#include <iostream>
using namespace std;

int main()
{
  int x, y, sum = 0;
  cout << "enter x y " << endl;
  cin >> x >> y;

  if (y < x)
    swap(x,y);

  for (int i=x; i<y; ++i)
    sum += i;

  cout << "sum = " << sum << endl;
}


Also, knowing that
1 + 2 + 3 + ... + n = n * (n + 1) / 2
you could write
C++
#include <iostream>
using namespace std;

int main()
{
  int x, y;
  cout << "enter x y " << endl;

  if ( x > y ) swap(x,y);

  int sum = y*(y+1)/2 - x*(x+1)/2;

  cout << sum;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900