C++ For Loop Question

Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Mar 2006
Posts: 6
Reputation: Duke_0064 is an unknown quantity at this point 
Solved Threads: 0
Duke_0064 Duke_0064 is offline Offline
Newbie Poster

C++ For Loop Question

 
0
  #1
Mar 19th, 2006
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;
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,813
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 747
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Senior Bitch

Re: C++ For Loop Question

 
0
  #2
Mar 19th, 2006
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:
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int x, n = 0;
  7.  
  8. cout<<"Numbers between 5 and 12 (3 numbers per line)are:\n";
  9.  
  10. for ( x = 5; x <= 12; x++ )
  11. {
  12. cout<< x <<" ";
  13.  
  14. if ( ++n == 3 ) {
  15. cout<<'\n';
  16. n = 0;
  17. }
  18. }
  19.  
  20. cout<<"\n\n";
  21. }
New members chased away this month: 3
Reply With Quote Quick reply to this message  
Join Date: Mar 2006
Posts: 6
Reputation: Duke_0064 is an unknown quantity at this point 
Solved Threads: 0
Duke_0064 Duke_0064 is offline Offline
Newbie Poster

Re: C++ For Loop Question

 
0
  #3
Mar 19th, 2006
Thanx alot!!
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC