Hey guys!

Hi everybody :) I just started learning C++ since yesterday when I received my C++ primer fifth edition. In the exercises section, I have to write a program that prints each number in the range specified by those 2 integers. I came up with this.
#include <iostream>
namespace std

int main();
{
int y=0, x=0;
cout << "write two numbers, Ill write the numbers between them" <<endl;
cout << "first number NOW" <<endl;
cin>> y;
cout << "another number please" <<endl;
cin>> x;

if (y>x);
y--;
cout<<y<<endl;

if (x>y);
y++;
cout<<y;

else;
cout<<"these are same numbers..."<<endl;

return 0;
}

But contrary to my other programs, I can't get to build it since it has too many grammatical errors. Could someone help me with this :). (and also correct my writing style if it really sucks, I'm still new.)
At the end of the 2 if test expressions you added semi-colons. Those are wrong, and end the if block so everything after is simply regular code and run straight. Also, if any loop contains more than 1 statement the statements must be enclosed in braces.

Here is what your code so far should look like (barring any mistakes I missed, also added code tags to make it easier to read.)

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
29
#include <iostream>
namespace std

int main();
{
    int y=0, x=0;
    cout << "write two numbers, Ill write the numbers between them" <<endl;
    cout << "first number NOW" <<endl;
    cin>> y;
    cout << "another number please" <<endl;
    cin>> x;

    if (y>x)
    {
        y--;
        cout<<y<<endl;
    }

    if (x>y)
    {
        y++;
        cout<<y;
    }

    else;
        cout<<"these are same numbers..."<<endl;

    return 0;
}


Now, obviously that code won't print each number between those 2 since that would either require a recursive function call or some form of loop. To do that you could use something like this (which would replace the 2 ifs and the else)

1
2
3
4
5
6
7
8
9
if (y < x) // If y is less than x swap them since that'll make it easier going into the loop
{
    int temp = y;
    y = x;
    x = temp;
}

for (; x <= y; ++x)
    std::cout << x;


If you only want to print out the numbers BETWEEN the 2 values entered and not the values entered themselves change that for to:

for (x += 1; x < y; ++x)
Last edited on
Topic archived. No new replies allowed.