-2

So I encountered this problem of not knowing how to display my random numbers from an array. The display should have 6 columns and I don’t know how about the rows. It is up to the user to enter amount of numbers in the array. Then, rand() will generate the numbers and display them in 6 columns like that (IF USER ENTERED 26 NUMBERS)

1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1

I know how to generate the numbers and all that, my problem is only in displaying 1d array in that format. (the output has to compatible with other numbers entered as well not only 26) Any help or pointing in the right direction would be much appreciated. Thanks, uszy 123345.

uszy123345
  • 43
  • 9
  • loop through array and print each element. when loop index is > 0 and modulo 6 == 0, print a newline. – DBug Dec 07 '15 at 00:13

2 Answers2

0

Since you worry about just the output, you can insert a newline character every 6 numbers printed and just stop when you get at the end of the array.

Paul92
  • 8,827
  • 1
  • 23
  • 37
0

Very often in c++ programming you can make use of extra variables to accomplish something every X number of iterations in a loop. In your case it looks like you want to insert a newline after every 6 numbers. Here is an example of how you would do that in code:

//I am assuming an array called arr with 26 elements already exists
for(int x = 1, i = 0; i < 26; ++i)
{
    std::cout << arr[i] << ' ';
    x++;
    if(x == 6)
    {
        std::cout << std::endl;
        x = 0;
    }
}
Kevin Tindall
  • 375
  • 5
  • 16
  • That seems legit I never thought of that way. Anyways one more question. I never learned anything with the for example with std::cout. Wouldn’t cout work just fine? Im sorry if that is a noob question haha. – uszy123345 Dec 07 '15 at 00:26
  • @uszy123345 Well, `std::cout` is just referring to a stream `cout` defined in a namespace `std`. If you wrote `using namespace std;` at the start of your .cpp file, it would work without `std::` part. It's just some of us got into habit of writing explicit statements where the function/class/object comes from, rather than writing `using namespace` everywhere. – Algirdas Preidžius Dec 07 '15 at 00:32
  • @uszy123345 Just as Algirdas said, some of us got into the habit. It is a good habit to not mangle the global namespace in c++. Another user asked this question about why is `using namespace std;` bad?[http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Kevin Tindall Dec 07 '15 at 00:36