Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

HOw can I make a square using just

Status
Not open for further replies.

anatazi

Programmer
Jun 24, 2002
33
0
0
US
HOw can I make a square using just single dimensional array?
for example array[12]={1,2,2,3,4,5,6,4,5,6,9,12} would give something like: 1 2 2 3
4 5 6 4
5 6 9 12
I knom I need to use a for loop but can't get it to print it out correctly.
THanks a lot
 
Well the quick and easy way would be to use \t. First make sure that the array is a square.

Code:
if(sqrt(size_of_array)*sqrt(size_of_array) == size_of_array)
{

  // got a square
  int rows = sqrt(size_of_array);
  
  for(int i = 0;rows;i++)
  {
      for(int j = 0;j<rows;j++)
      {
         cout<<*(array+i*rows+j)<<&quot;\t&quot;;
      }
      cout<<&quot;\n&quot;;
   }
}

That should do it

Matt

 
I think you have a type-o in the outer for loop, the for line should read:
for (int i = 0; i < rows; i++)
not
for (int i = 0; rows; i++)

And I would write the cout-line like this:
cout << array[i*rows+j] << &quot;\t&quot;;
Not that there's anything wrong with your way of writing it, I just find my way more readable =)
 
Code:
another way for doing this would be:

#include <stdio.h>
#include <math.h>
void main()
{
   const int size = 9;
   int array[size] = {2,56,-87,37,65,226,17,398,14};/* an example */
   bool issqr = false;
   int z = 1;

   while( z <= size && !issqr )    
   {
	   if( size == 1 )
	   {
		   issqr = true;
	   }
	   else if(( size/ z) == z && !( size % z ) && z != 1 )
	   {
		   issqr = true;
	   }
	   z++;
   }

   if( issqr )    
   {
      /* got a square */

	  int row = z - 1;
      
	  for(int i = 0; i < size; i++ )
	  {
		  if( !(i%row) && i != 0 )
			  printf(&quot;\n&quot;);

		  printf(&quot;%d\t&quot;,array[i]);
	  }
   }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top