Benny
Benny

Reputation: 1

Printing out an entire array multiple times

I am wondering how you can print out an entire array multiple times in C++. Say you have the following array:

arr1 = [1,2,5,6,7,8]

and you want to print it out n times such that the output would be:

1 2 5 6 7 8

1 2 5 6 7 8

1 2 5 6 7 8

If n would be equal to 3. You could just code some number of for loops if n is a static integer, but what if it's dynamic?

I know you need to use a for loop for printing out all the contents of an array, but I'm not sure what you would do if you want to get the above output.

Upvotes: 0

Views: 2364

Answers (3)

user10957435
user10957435

Reputation:

If n is dynamic, it doesn't matter. You can have a loop that prints the array n times quite easily:

void printInts(int* arr, size_t size) {
    // some printing logic
}

int main() {
    int arr[] = {0,1,2,3,4,5,6,7,8};
    int n = 3; // could be anything really

    for(int i = 0; i<n; i++) {
        printInts(arr, 9);
    }
}

The value of n doesn't really matter here: it should print n times.

If you're asking how do we know the size of arr if it's a dynamic array, that's actually pretty easy too:

Until C++11:

size_t size = sizeof(arr)/sizeof(arr[0]);

After C++11 you can use:

size_t size = *(&arr + 1) - arr;

You could do this in main() or even in printInts() if you want.

Note: keep in mind you can't get the size of a pointer allocated dynamically easily. If you allocate with say new, you'll have to keep track of the size of the array yourself.

You can't. The size of an array allocated with new[] is not stored in any way in which it can be accessed. Note that the return type of new [] is not an array - it is a pointer (pointing to the array's first element). So if you need to know a dynamic array's length, you have to store it separately.

Upvotes: 2

Jason Javier
Jason Javier

Reputation: 201

I think you know how to use for loop.

  int rows;
  int arr1 [5] = {1, 2, 3, 4, 5};
  cout << "Enter number of rows? ";
  cin >> rows;
  for(int row=1; row<=rows;row++) {

      for(int index=0;index<=4;index++) {
         // print the array index here and space after a digit
      }

      // print line-break here
  }

Upvotes: 0

madeleine
madeleine

Reputation: 1

If what you're asking is how to get user input:

int n;
cin >> n;
for (int i = 0; i < n; i++) {
  // print array
}

Upvotes: 0

Related Questions