Nest if statement in for loop : For statement « Statement « C Tutorial






#include <stdio.h>

int main(void)
{
  int chosen = 15;            
  int guess = 0;              
  int count = 3;              

  printf("\nA Number.\n");

  for( ; count>0 ; --count)
  {
    printf("\nYou have %d tr%s left.", count, count == 1 ? "y" : "ies");
    printf("\nEnter a guess: ");
    scanf("%d", &guess);

    if (guess == chosen)
    {
      printf("\nYou guessed it!\n");
      return 0;               
    }

    if(guess<1 || guess > 20)
      printf("between 1 and 20.\n ");
    else
      printf("Sorry. %d is wrong.\n", guess);
  }
  printf("\nYou have had three tries and failed. The number was %d\n", chosen);
  return 0;
}
A Number.
     
     You have 3 tries left.
     Enter a guess: 1
     Sorry. 1 is wrong.
     
     You have 2 tries left.
     Enter a guess: 2
     Sorry. 2 is wrong.
     
     You have 1 try left.
     Enter a guess: 3
     Sorry. 3 is wrong.
     
     You have had three tries and failed. The number was 15








6.6.For statement
6.6.1.for LOOP
6.6.2.Omit all three parts in for loop
6.6.3.The for loop with a comma operator
6.6.4.Initialize loop control variable outside the for statement
6.6.5.Use for loop to print a rectangle
6.6.6.Sum integers in for statement
6.6.7.for loop backward
6.6.8.indefinite loop: empty for
6.6.9.Nest if statement in for loop
6.6.10.Nest for loop: two different control variables
6.6.11.Use char variable to control for loop
6.6.12.Continue a for loop