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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I can't figure out this loop

Status
Not open for further replies.

ironyx

Technical User
Nov 13, 2001
134
US
I am trying to do a multiplication table with two integers. I know it's simple but I can't figure it out. Can someone just steer me in the right direction? I thank you for the help. :)
 
I dont fully understand what the multiplication table should look like. If you are passing 2 values dont you just want to return the product?

Matt
 
It has to be an actual table:
int1 = 4
int2 = 3

1 2 3
2 4 6
3 6 9
4 8 12

so I know it has to be two loops but I am not getting the results... The logic doesn't come easy for me. ;) Thanks!!!
 
What is the fascination with using two numbers? The very same table can be printed with just two lines of C++ code.

Perhaps ...
Code:
for (int n1 = 1; n1 <= 20; n1++) 
    cout << setw(2) << n1 << &quot; &quot; << setw(2) 
         << n1 * 2 << &quot; &quot; << setw(2) << n1 * 3 << endl;
does not work for you?
 
We'll call it user specifications to have two integers and a table appear for those. Actually it's an assignment. I did it for astericks with a loop but I just can't figure out the multiplication thing and have it display correctly. I know it's probably absurdly simple to you, but I am still crawling on the whole programming thing while everyone else seems to be running. ;)
Oh well... I'll learn bit by bit I suppose.
Thanks for taking the time to help!
 
What about this?

Code:
int n1 = 1, n2 = 1, stopValue = 20, numOfColumns = 3;
 
 for (; n1 <= stopValue; n1++) {
  for (;  n2 <= numOfColumns; n2++) {
   cout << setw(2) << n1 * n2 << &quot; &quot;;
  }	

 n2 = 1;
 cout << endl;

 }
 
The number of columns has to be equal to the second integer. What does the stop value do? I have only seen for & do / while loops that end when you run out of whatever you're counting. Because the two integers have to control the size of the table so I don't know if predefining values will work for this. I have been trying nested looping but can't figure out how to get it to display the entire table like the example. I dunno...
 
Hm. You have an interestingly sadistic instructor? Oh well. I tried twice, and failed both times.

The stop value, in my programs, was to what number the loop would iterate to, before exiting the loop (obviously).


 
GOT IT!!!

cout.setf(ios::left);
for (int i = 1; i <= int1; i++)
{
for (int j = 1; j <= int2; j++)
cout << setw(2) << &quot; &quot; << setw(3) << i * j;
cout << &quot;\n&quot;;
}
Argh.. thanks for helping me think it through.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top