0

i've just learned cpp and want to know is there a shorter way to display a sequential number.

this is my code

#include<iostream>

using namespace std;

int main(){
    int n;

    cout<<"Input number: ";
    cin>>n;

    cout<<"The next 5 rows of number is :"<<n+1<<n+2<<n+3<<n+4<<n+5;
}
FNP123
  • 37
  • 2
  • 7
    How about loops? Perhaps it's time you [find a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read? – Some programmer dude Sep 10 '18 at 13:15
  • 2
    Possible duplicate of [Neatest way to loop over a range of integers?](https://stackoverflow.com/questions/15088900/neatest-way-to-loop-over-a-range-of-integers) – hellow Sep 10 '18 at 13:15
  • 1
    You use a loop for that usually. – Hatted Rooster Sep 10 '18 at 13:16
  • 1
    "rows upwards" is a strange way to describe what you're doing. It seems to me like you want to "display the next 5 numbers". – Wyck Sep 10 '18 at 13:18
  • sorry for my bad english, yes that's what i meant. display the next 5 numbers. – FNP123 Sep 10 '18 at 13:19
  • 1
    I swear if this was the Java tag there would've already been 10 answers showing how to use a loop from 100 rep users. – Hatted Rooster Sep 10 '18 at 13:20
  • 1
    There are better ways to do it, but what actually do you want? the easiest? the shortest? the most correct one? – Ispas Claudiu Sep 10 '18 at 13:22
  • actually i want to learn many ways to show it, but the shortest or the most correct is okay. can you write it? – FNP123 Sep 10 '18 at 13:25
  • `for(int i=1;i<=5;i++) { cout << n+i << ";" }` – Stephan Lechner Sep 10 '18 at 13:29
  • You could pitch it on [code golf](https://codegolf.stackexchange.com/) and see what the hardcore "shorter way" crowd comes up with. – Wyck Sep 10 '18 at 13:32
  • @StephanLechner Answers go in the answer section mate – Lightness Races in Orbit Sep 10 '18 at 13:39
  • 1
    Your code may actually be more efficient than using a loop. When the processor encounters a branch or jump, it has to decide if the instruction cache needs to be reloaded. A`for` loop would execute 5 times (5 jumps), whereas your addition statements don't use jumps or branches. – Thomas Matthews Sep 10 '18 at 13:54

1 Answers1

1

A simple loop should solve your problem:

int main(){
    int n;

    cout << "Input number: ";
    cin >> n;

    cout << "The next 5 rows of number are: ";

    for (int i = n + 1; i <= n + 5; i++) {
        cout << i << ' ';
    }
}
HugoTeixeira
  • 4,674
  • 3
  • 22
  • 32