Printing numbers 1-n using a function

Hello everyone,

What's reason behind why I can't print out numbers from 1-n in this program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

void print_out(int n);

void print_out(int n) {

    for(int i = 1; i <= n; i++) {
        cout << n << " ";
    }
    
}

int main() {
    int n;
    
    cout << "Enter a number: ";
    cin >> n;
    
    print_out(n);

}


For example, I want it to be 1 2 3 4 5 and not 5 5 5 5 5.

Output:

Enter a number: 5
5 5 5 5 5





1
2
3
    for(int i = 1; i <= n; i++) {
        cout << n << " ";
    }

This prints out n, n times and is demonstrated by your output.
1
2
3
    for(int i = 0; i <= n; i++) {
        cout << i << " ";
    }

This will do what you want it to.
Last edited on
Oh, wow. I should've known that. Thanks a lot!
Topic archived. No new replies allowed.