hello stack overflowers! haha I am relatively new to c++ and I have a small problem figuring out small piece of the code. Basically I need to print out a full array of ints in 5 different columns. The thing that throws me off is that I have no clue how many ints are in the array and how many rows it'd create?(it is a 1d array) 2d is very easy to process. I just dont know how to go about this. Any logical help would be much appreciated. I have no problem coding it i just don't know how to set this up. Ive been thinking about it for some time now.
Asked
Active
Viewed 964 times
1 Answers
0
You need to know the total number of elements in the 1d-array and we need decompose the number of these elements in the 1d array on the two multiplier. First multiplier will be lines, second - rows. For example if we have 50 elements in the 1d-array we can assume that we have 10 lines and 5 columns and then write something like this:
for(int line = 0; line < 10; line++)
{
for( int col = 0; col < 5; col++)
{
cout << setw(5) << arr[line*5 + col];
}
cout << endl;
}

Evgeniy331
- 404
- 2
- 8
-
thank you for a fast response! so what if i have 48 ints in the array? do i just divide it by 5 columns and round up the number to get the rows? – uszy123345 Dec 05 '15 at 19:11
-
If you have 48 ints, you cannot assume that you have 5 columns, it is not divisible by 5. We need decompose in other way. For example we can assume that we have 6 lines and 8 columns or 8 and 6 or 2 and 24. – Evgeniy331 Dec 05 '15 at 19:18
-
Of course you can round the number of lines and when you display the values you need to check we have moved beyond and if yes simply displaying the empty char but I'm not sure that's a good decision – Evgeniy331 Dec 05 '15 at 19:20
-
or @uszy123345 can [read up on the modulus operator](https://msdn.microsoft.com/en-us/library/h6zfzfy7(v=vs.90).aspx). [Better link](http://stackoverflow.com/questions/12556946/how-does-the-modulus-operator-work). – user4581301 Dec 05 '15 at 19:23
-
@user4581301 It's interesting why people keep calling modulo as modulus, while modulus originally means absolute value, and modulo (or modulo division) is the name of operator as official c++ site and mathematics say. (Anyway, not offending you :), just thinking loudly) – Lasoloz Dec 05 '15 at 19:32
-
To be honest @Lasoloz , I don't know why I still do that. Been corrected many times, but it never sticks. – user4581301 Dec 05 '15 at 20:47
-
@user4581301 :) I know. I also keep using some of my mistakes, even in maths. – Lasoloz Dec 06 '15 at 07:38