Connecting Tech Pros Worldwide Help | Site Map

how do i make an if statement repeat itself in c?

Newbie
 
Join Date: Oct 2009
Posts: 3
#1: Oct 10 '09
im a beginner and i have to write a program that makes a guessing game. For example this should be my output.

How many games would you like to play JW? (1 – 10): 22
That’s too many!
How many games would you like to play JW? (1 – 10): 2

Lets Play game 1 JW

now the code that i wrote is

printf("\nHow many games would you like to play %c%c?(1-10)\n",firsti, secondi);
scanf("%d", &games);
if(games>1&&games<10)

printf("Lets play game 1\n");

else

printf("That's too many!\n");

what do i do so that the program goes back to the line "How many games would you like to play?"
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,148
#2: Oct 10 '09

re: how do i make an if statement repeat itself in c?


You need to use a loop one of

Expand|Select|Wrap|Line Numbers
  1. for(expresion1; expresion2; expresion3)
  2. {
  3.     /* Code to repeat */
  4. }
  5.  
  6. while(expression)
  7. {
  8.     /* Code to repeat */
  9. }
  10.  
  11. do
  12. {
  13.     /* Code to repeat */
  14. }
  15. while(expression);
  16.  
I sugest you look them up in your C/C++ reference books.
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,936
#3: Oct 10 '09

re: how do i make an if statement repeat itself in c?


The do-while loop would my first choice here.

The code is pretty simple, so I'll chuck it to you in pseudo-form.

Expand|Select|Wrap|Line Numbers
  1. do
  2.   print your message (input number)
  3.   read number
  4.   if number breaks some rule
  5.     print some error
  6. while number breaks some rule
  7.  
I prefer the do-while because you always need that first message output and number read.

Hope this helps,
Mark (not a C expert).
Reply