How to make repeating for loop become one?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <iomanip>
#include <conio>

int main()
{  int j;
	cout<<"\n\t Multiplication Tables";
   cout<<"\n______________________________________\n\n";
   // print multiplication table for 1
   for (j=2; j<=18; j+=2)
   {
   	cout<<setw(4)<<j*2;
   }
   	cout<<endl;

   //print multiplication table for 2
   for (int j=5; j<=45; j+=5)
   {
   	cout<<setw(4)<<j*1;
   }
   	cout<<endl;

   //print multiplication table for 3
   for (int j=6; j<=54; j+=6)
   {
   	cout<<setw(4)<<j*1;
   }
   	cout<<endl;


getch();
return 0;
}


The above looping is something like repeating, so I wish to make it become just a loop using i and j, is that possible? TQ...
I'm not entirely sure what you are asking here.

You could put all of this into one for loop, but you'd have to add some extra controls. Also, since you are doing things in a different order this way, your tables will not be in the same order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{  int j;
   cout<<"\n\t Multiplication Tables";
   cout<<"\n______________________________________\n\n";

   for (j=2; j<=64; j++)
   {
      if (j >=2 && j <= 64 && j%2==0)
   	     cout<<setw(4)<<j*2;
      if (j >=5 && j <= 45 && j%5==0)
         cout<<setw(4)<<j;
      if (j >=6 && j <= 54 && j%6==0)
         cout<<setw(4)<<j;
   }

getch();
return 0;
}
Last edited on
I think he means making the loop generic, rather than copypasting the loop code. If so:

1
2
3
4
5
6
for (i = 2 -> last multiplication table) {
    cout << "Printing table for " << i << endl;
    for (j = 1 -> last multiplicator) {
        cout << j*i << "\t";
    }
}
I mean to make a loop just by using "i" and "j" and something like "i*j" to get the above program works without copying and pasting the "same" thing for every loop...for example, I can just change at "i" and "j" how many row and column i want instead of changing every number in every loop(let say 100 loop)...TQ...
Topic archived. No new replies allowed.