简体   繁体   中英

How to Repeat an integer multiple times in C++

#include <iostream>
#define el '\n'
using namespace std;

int main(){
    int T;
    int i;
    cin >> T;
    int N[i];
    for(int i=0; i < T; i++){
        cin >> N[i];
    }
    for(int i=0 ; i < T ;i++){
        cout << N[i] << el;

    }

}

If the input is:

3
3
4
6

I need the output to be:

3 3 3
4 4 4 4
6 6 6 6 6 6

what is the change I can make for the 14th line to solve the problem?

You need to print each number N[i] times, and you already know how to do that - use a loop.

But the number of inputs is T , not i - you never give the i in int N[i]; a meaningful value.
Also, variable-length arrays are not part of the C++ standard, so even if you use int N[T] , you don't have a standard C++ program.

Fortunately, you don't need an array at all - you can just read each number in turn and print it that many times:

int main(){
    int T;
    cin >> T;
    for (int t = 0; t < T; t++)
    {
        int x;
        cin >> x;
        for (int i = 0; i < x; i++)
        {
            cout << x << ' ';
        }
    }
    cout << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM