C-if else statement

ww‮l.w‬autturi.com
C-if else statement

if statement

syntax

if (condition) {
  //code...
}

In the following example, we get an integer value from the user.
If the value is greater than 100, "The number entered is greater than 100" is printed.

#include <stdio.h>
int main(void)
{
  //declare variable
  int x;
  
  //take user input
  printf("Enter an integer number: ");
  scanf("%d", &x);
  
  //check condition
  if (x > 100) {
    printf("the number entered is greater than 100.\n");
  }

  printf("End of code\n");
  
  return 0;
}
Enter an integer number: 200
Entered number is greater than 100.
End of code

when we entered an integer less than 100, so the if block is not executed.

Enter an integer number: 99
End of code

if else statement

if we have two options and want to execute either option depending on the condition, we can use an if-else statement.

Here is the syntax of the if-else statement.

if (condition) {
  //if block code
}
else {
  //else block code
}

example:

#include <stdio.h>
int main(void)
{
  //declare variable
  int x;
  
  //take user input
  printf("Enter an integer number: ");
  scanf("%d", &x);
  
  //check condition
  if (x > 10) {
    printf("Entered number is greater than 10.\n");
  }
  else {
    printf("Entered number is less than or equal to 10.\n");
  }
  
  printf("End of code\n");
  
  return 0;
}
Enter an integer number: 20
Entered number is greater than 10.
End of code
Created Time:2017-08-22 20:51:46  Author:lautturi