using FOR issues!

Hello fellow geeks!

So, i need help with a bit of an assignment. i need to get the following output to print:

9 8 7
6 5 4
3 2 1

Only using the code below. No more variables can be added. Any ideas?

CeErre

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include <string>
#include <iostream>
using namespace std;

int main(){
  
   
	for (int i = 0; i < 3; i++) {
		for (int j = 10; j < 4; j++) {
			cout << " " << j + i * 3;
		}
		cout << endl;
	}
	cout << endl;

}
Last edited on
What does "using the code below" mean? Variables can't be added, but can they be removed?

Your loop can be as simple as:
1
2
3
4
5
6
7
8
9
#include <iostream>

int main() {
	for (int i = 9; i > 0; i--) {
	    std::cout << i << ' ';
	    if (i % 3 == 1)
	        std::cout << '\n';
	}
}

Only one variable needed :)

If you really want to use two nested for loops, you can develop the following mapping:

" f(i, j) --> n "

(0, 0) --> 9
(0, 1) --> 8
(0, 2) --> 7
(1, 0) --> 6
(1, 1) --> 5
(1, 2) --> 4
(2, 0) --> 3
(2, 1) --> 2
(2, 2) --> 1

Can you see a pattern here?
9 = (3 - 0)*(3) - 0
8 = (3 - 0)*(3) - 1
7 = (3 - 0)*(3) - 2
6 = (3 - 1)*(3) - 0
5 = (3 - 1)*(3) - 1
4 = (3 - 1)*(3) - 2
3 = (3 - 2)*(3) - 0
2 = (3 - 2)*(3) - 1
1 = (3 - 2)*(3) - 2


Edit: To be a dead horse to death, here is the above logic realized:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            std::cout << 9 - 3 * i - j << ' ';
        }
        std::cout << '\n';
    }
}
Last edited on
One variable, restructuring the first for loop to count down, dumping the second and adding a modulus check:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main()
{
   for (int i { 9 }; i >= 1; i--)
   {
      std::cout << i << ' ';

      if (i % 3 == 1)
      {
         std::cout << '\n';
      }
   }
}
1
2
3
4
5
6
7
#include <iostream>

int main()
{
	for (int i {9}; i >= 1; --i)
		std::cout << i << (i % 3 == 1 ? '\n' : ' ');
}

Last edited on
Geeks,

Thank you all for your advice. I like @seeplus solution better. Look very clean and i love the ternary in there as well!

CeErre
If you absolutely, positively MUST use 2 for loops (no need for any modulo magic):
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
   for (int i { 9 }; i > 0; i -= 3)
   {
      for (int j { }; j < 3; j++)
      {
         std::cout << i - j << ' ';
      }
      std::cout << '\n';
   }
}
1
2
3
4
5
#include <iostream>
int main()
{
   for ( int i = 9; i; i--) std::cout << i << " \n "[i % 3];
}
Topic archived. No new replies allowed.