C Programming — The if Statement

C Programming — The if Statement

A basic C example demonstrating comparison operators, conditional execution, else, the modulo operator and block syntax.

The if statement is used when an operation should be performed only when a specified condition is satisfied.

#include <stdio.h>
#include <conio.h>
int main()
{
int number1, number2;
printf("Enter two numbers:\n");
scanf("%d %d", &number1, &number2);
if ( number1 == number2 )
printf("%d is equal to %d\n", number1, number2);
if ( number1 != number2 )
printf("%d is not equal to %d\n", number1, number2);
if ( number1 < number2 )
printf("%d is less than %d\n", number1, number2);
if ( number1 > number2 )
printf("%d is greater than %d\n", number1, number2)
if ( number1 <= number2 )
printf("%d is less than or equal to %d\n", number1, number2);
if ( number1 >= number2 )
printf("%d is greater than or equal to %d\n", number1, number2);
if ( number1 % 2 == 0)
printf("number1 is even");
else
printf("number1 is odd");
getch();
return 0;
}
  • The conditions use parentheses and compare two variables with the comparison operators ==, !=, <, >, <= and >=.
  • There are two possible outcomes. When the condition is true, the statement after if is executed; otherwise it is skipped. For a single statement this continues up to the terminating semicolon. Multiple statements must be placed between braces { and }.
  • Notice that comparison uses two equals signs (==). A single equals sign (=) is the assignment operator and is not used for equality comparison.
  • The percent sign (%) performs the modulo operation. If the result is zero, the number is evenly divisible. In this example, a true condition prints that number1 is even.
  • When the condition is false, the statement after else is executed, so the program prints that number1 is odd.
  • Also notice that no semicolon is placed immediately after the if or else keywords.

References

  • **[1]** Brian W. Kernighan; Dennis M. Ritchie. (1988). The C Programming Language, Second Edition. Prentice Hall.
  • **[2]** International Organization for Standardization. (2011). ISO/IEC 9899:2011 - Programming Languages - C. ISO.
QR code for this page