0

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;
2
Contributors
2
Replies
3
Views
11 Years
Discussion Span
Last Post by Duke_0064
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";
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.