While Loops

closed account (oy8URXSz)
Hi again! I've got a new problem which is, create a program that will ask for three inputs, x,y&z. Once these numbers have been given...display allo numbers from x to y with increments of z. (Use while loops)

Sample Program Output, it should be like this(the x,y,z and underscores under the numbers are not included, just to represent what the number is):

Enter x: 4
Enter y: 18
Enter z: 2

4 6 8 10_12_ 14 16 18
x       z  z       y  
I wouldn't give you the whole code but it'd go something like this

int x,y,z;
x = 4;
y = 18;
z = 2;
int sum = x;
while (sum < y) {
cout << sum << endl;
sum += z;

}
cout << y << endl;


That is the main algorithm
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
26
27
28

//Determine whether going up or down
if(x < y)
{
     int i = x;
     std::cout << x << " ";
     while (i + z < y)
     {
          i += z;
          std::cout << i  << " ";
          
      }
     std::cout << y;
}
      
if(x > y)
{
     int i = x;
     std::cout << x << " ";
     while (i + z > y)
     {
          i += z;
          std::cout <<  i  << " ";
          
      }
     std::cout << y;
}


Pretty sure this can be done without using the ugly 2 if statements especially since the only difference is one uses > while the other uses <.

You didn't specify whether z is given as negative for going down. This assumes it is. Zero error checking is done. Also didn't handle case where x=y.

Pretty crude, I didn't run it.
Last edited on
closed account (oy8URXSz)
@raban and @Robert LeBlanc, thank you very much for the big help!
Topic archived. No new replies allowed.