Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

If

Conditions and If Statements

As you’ve already discovered, C accommodates the standard logical conditions found in mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to: a == b
  • Not Equal to: a != b

These conditions can be employed to execute various actions based on different decisions.

C offers the following conditional statements:

  • Employ if to designate a block of code for execution if a particular condition holds true.
  • Utilize else to designate a block of code for execution if the same condition is false.
  • Employ else if to specify a new condition to evaluate if the first condition is false.
  • Utilize switch to designate multiple alternative blocks of code for execution.

The if Statement

Utilize the if statement to define a block of code for execution when a condition is true.

Syntax

if (condition) {
  // block of code to be executed if the condition is tru
}

 

Please note that “if” should be in lowercase letters. Using uppercase letters (such as If or IF) will result in an error.

In the following example, we evaluate two values to determine if 20 is greater than 18. If the condition is true, output some text:

Example

if (20 > 18) {
  printf(“20 is greater than 18”);

Variables can also be tested:

Example

int x = 20;
int y = 18;
if (x > y) {
  printf(“x is greater than y”);
}

Example explained

In the example provided, we utilize two variables, x and y, to evaluate whether x is greater than y (employing the > operator). Given that x is 20 and y is 18, and considering that 20 is indeed greater than 18, we display the message “x is greater than y” on the screen.