• 0

C++ Question


Question

I am trying to print in rows of 4 and then 3 colums. Here is the code I have now

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
	int x[12];
	int z = 0;
	int y;
	int tmp;


	for(z = 0; z<12; z++) *(x+z) = rand()%23 + 11;
	for(z = 0; z<12; z++)
	{
 ?cout << *(x+z) << " ";
 ?if ( *(x+z)%3==0) cout << endl;
	}

	return 0;
}

Right now it prints out like this

x x x x

x

x x

x

x x x

x

I need it to be like this

x x x x

x x x x

x x x x

Can you guys please tell me what I am doing wrong ?

Thank you

mzkhadir

Link to comment
Share on other sites

8 answers to this question

Recommended Posts

  • 0

for(z = 0; z<12; z++) *(x+z) = rand()%23 + 11;

for(z = 0; z<12; z++)

Should you be using the Z variable in both for loops? By doing this, the Z variable changes each time it goes round each of the two loops

Link to comment
Share on other sites

  • 0
for(z = 0; z<12; z++) *(x+z) = rand()%23 + 11;

for(z = 0; z<12; z++)

Should you be using the Z variable in both for loops? By doing this, the Z variable changes each time it goes round each of the two loops

Except it's not a nested for loop. One initializes and one prints out.

But the problem is right now it's only printing out when the value in x+z is divisible by 3 instead of printing out when the current place, z, is divisible by 3. Also note, it needs to be 4 if you want 4 on a line. Plus the if needs to go before printing the next value, since it'll print out the newline after the value is printed.

for(z = 0; z<12; z++)

{

if (z%4==0 && z!=0) cout << endl; //Take out z!=0 is you don't care about a newline at 0.

cout << *(x+z) << " ";

}

Link to comment
Share on other sites

  • 0
That does work. Thank You. Instead of using the random number generators, you used the variable to stop the function.

Exactly. Another way you could have done it is with a 2D array. x[4][3], although they end up the same in memory either way, so it doesn't matter all that much.

Link to comment
Share on other sites

  • 0

#include&lt;iostream&gt;
#include&lt;iomanip&gt;
using namespace std;

int main()
{
	int x[12];
	int z = 0;
	int y; int j;
	int tmp;
	int b =0;


	for(z = 0; z&lt;12; z++) *(x+z) = rand()%23 + 11;
	for(z = 0; z&lt;12; z++) 
	{
  if (z%4==0) cout &lt;&lt; endl;
  cout &lt;&lt; *(x+z) &lt;&lt; " ";
	}
//sort

	for(z=0; z&lt;12; z++)
  for(j=(z+1); j&lt;12; j++)
 	 if(*(x+z) &gt; *(x+j))
 	 {
    tmp = *(x+j);
    *(x+j) = *(x+z);
    *(x+z) = tmp;
 	 };

//print
	cout &lt;&lt; endl;
	cout &lt;&lt; endl;

	for(z = 0; z&lt;12; z++)
	for(z = 0; z&lt;12; z++) 
	{
  if (z%3==0) cout &lt;&lt; endl;
  cout &lt;&lt; *(x+z) &lt;&lt; " ";
	}

	return 0;
}

Here is what the full code is supposed to look like at the end.

Thank You again for your help.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.