Hello , I have to write an algorythm which will be able to give me all possible pairs from 1 to N; for exmp. N = 3; the cout must be 1 1 ; 1 2 ; 1 3 ; 2 1 ; 2 2; 2 3; 3 1; 3 2; 3 3; But the fact is that i cant use bool . any help ? I think i have to use double FOR but i dont know how . Thanks in advance
I'm not sure why you'd use bool. Just use two nested for loops.
The outer loop goes through from 1 to 3 and represents the first number in a pair.
The inner loop also goes from 1 to 3 and represents the second number in a pair.
Print the first and second numbers inside the inner loop.
I like ne555's idea of starting by printing the numbers from 1 to n. Below I have temporarily removed the inner loop and replaced it with code to print i and space. Run this program (be sure to enter the value for n and press enter). What does it print? Can you figure out how to fix it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int
main()
{
int n;
cin >>n;
for(int i=1;n<=100;i++){
cout << i << ' ';
}
return 0;
}
it isnt required to use 2 nested loops, but that is the simple way.
the outer loop will hold a value for all the inner loops; so outer loop is 1, the inner loop might be 1, then 2, then 3, then 4, ... etc.
then the outer loop variable becomes 2, and the inner goes 1, 2, 3, 4, ... again.
if the inner and outer are the same, you don't appear to want it.
otherwise, you do.
string those ideas together...
nested loops (and any other nested code) looks about like you would expect
for(i = 1; i <= n; i++)
{ //I prefer brackets even when not needed.
for(j = 1; j <= n; j++)
{
do something
}
} //end outer loop