Hello,

I have this for loop here, and everything is great except I can't figure out how to display 3 numbers per line instead of all number on one line. Can anyone help? Thanx!


#include <iostream>
using namespace std;

int main( )          
{
	int x;           
	
   

	cout << "Numbers between 5 and 12 (3 numbers per line)are:\n";

	for (x = 5; x <= 12; x++)
	{
		cout << x << " ";
		
	}
	    cout << endl << endl;
		
	return 0;

You can play games with modular arithmetic to avoid adding another variable, but sometimes it's just easier to count how many numbers you've printed. When you get to 3, print a newline and reset the counter:

#include <iostream>
using namespace std;

int main()
{
  int x, n = 0;

  cout<<"Numbers between 5 and 12 (3 numbers per line)are:\n";

  for ( x = 5; x <= 12; x++ )
  {
    cout<< x <<" ";

    if ( ++n == 3 ) {
      cout<<'\n';
      n = 0;
    }
  }

  cout<<"\n\n";
}

Thanx alot!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.