For loop question: C++

I have a code here that displays integers from 1-100 using 5 columns.
I would like to know how to only display the numbers that are divisible by 6 and 7.

For example:

1
2
3
4
5
6
6   7 12 14 18 
21 24 28 30 35 
36 48 49 54 56 
60 63 66 70 72 
77 78 90 91 96 
98


How would I go about doing this? Thanks so much.

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 i, rows = 0;

	for (i = 1; i <= 100; i++)
	
	{	
		rows++; 
		cout << setw(3) << i << " "; 
	
		if (rows % 5 == 0) 

		cout << endl;
	}

	return 0;
}
Last edited on
%42 == 0 means divisible by both 6 and 7.
%42 == 0 changes the columns from 5 to 42 and not the value of the numbers, sorry I am lost.
Don't touch the if (rows % 5 == 0) cout << endl; logic, that's fine as is.
Add additional logic to only cout << i if i is divisible by 6 and 7 (i.e. divisible by 42).
Last edited on
Do you want numbers divisible by 6 AND 7 (42), or numbers divisible by 6 OR 7?

By your example, it looks to be 6 or 7.

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

int main()
{
   int rows = 0;

   for (unsigned i = 1; i <= 100; i++)
   {
      if ((i % 6 == 0) || (i % 7 == 0))
      {
         rows++;

         std::cout << std::setw(3) << i << " ";

         if (rows % 5 == 0)
         {
            std::cout << '\n';
         }
      }
   }
   std::cout << '\n';
}
  6   7  12  14  18
 21  24  28  30  35
 36  42  48  49  54
 56  60  63  66  70
 72  77  78  84  90
 91  96  98
display the numbers that are divisible by 6 and 7.
Your text says 6 and 7, but the sample output is (divisible by 6) XOR (divisible by 7). So do you mean AND, OR or XOR? The code below assumes XOR to generate your sample output.

Add additional logic to only cout << i if i is divisible by 6 and 7 (i.e. divisible by 42).
Actually all of the current logic in the loop should only occur when divisible by 6 and/or 7, not just the cout.

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

int
main()
{
    int i, rows = 0;

    for (i = 1; i <= 100; i++) {
	if (i%6 == 0 ^ i%7 == 0) {
	    rows++;
	    cout << setw(3) << i << " ";

	    if (rows % 5 == 0)
		cout << endl;
	}
    }

    return 0;
}


I meant XOR, and thanks, this solves it.
Topic archived. No new replies allowed.