### Loop

How to create a loop that prints the numbers 1 to 20 but skips 3, 11, and 16.
http://www.cplusplus.com/articles/jEN36Up4/

Let's be honest here, you haven't event attempted to solve this yourself. It's not difficult.
Last edited on
If you are creative with Math you might be able to find a slick way to achieve this without using a brute force method.

It there a pattern to these numbers or is just these 3 specific ones? At first glance, I don't see any patterns but I am not too great at the Maths.

If you want to brute force it just write out the logic in pseudocode.

X = 0
Begin LOOP Till X = 20
IF X != 3 AND X != 11 AND X != 16
Print X
END IF
END LOOP

Yeah well, the basic C++ code for that is:

 ``1234567891011`` ``````#include using namespace std; int main (int argc, char **argv) { for (int i = 1; i <= 20; i++) if (i != 3 && i != 11 && i != 16) cout << i << “ “; return 0; }``````

Hope I could help,
~ Raul ~
For loops are probably a better option since we're dealing with an iterator ( i ), but there is also the while loop as an option.
Jumper007's code uses the and (&&) signs in his if statement, I used or (||) signs.

They both work in this instance because jumper's code also uses the not equal sign (!=). Basically his code is saying if i doesn't equal 3 and i doesn't equal 11 and i doesn't equal 16 then print out the number.
My version says if i does equal 3 or 11 or 16 then tell them a number is skipped, otherwise print out the number.

 ``123456789101112`` ``````int i=0; while(i<=20) { if(i==3 || i==11 || i==16) { cout<<"A number was skipped"<

This is also an example of difference in syntax, mine isn't exactly wrong, but the the extra brackets I used aren't necessary after the if and else functions since there is only one action line after both of them. I prefer using brackets because it helps me organize my code when I'm skimming it.
Last edited on
Topic archived. No new replies allowed.