0

Lesson 03 | Conditionals

 2 years ago
source link: https://dev.to/ilosrim/lesson-03-conditionals-1cd6
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Types of Conditionals

A conditional in C can be written using if, else-if, else, ternary operators, and switch statements.

if Statements

An if statement tests an expression and executes code based on its truth.

if (x == 3) {
  printf("x is 3!");
}

Enter fullscreen mode

Exit fullscreen mode

else-if Statements

An else-if statement tests an expression and must come after an existing if or else-if.

if (x > 3) {
  printf("x is greater than 3");
} else if (x < 3) {
  printf("x is less than 3");
}

Enter fullscreen mode

Exit fullscreen mode

else Statements

An else statement is accessed when all preceding if and/or else-if statements return false.

if (x > 3) {
  printf("x is greater than 3");
} else if (x < 3) {
  printf("x is less than 3");
} else {
  printf("x equals 3");
}

Enter fullscreen mode

Exit fullscreen mode

Dangling else Statement

A dangling else statement results when it’s ambiguous which conditional the else statement is attached to.

Ternary Operators

A ternary operator is a condensed if-else statement.

min = a < b ? a : b; // This is the same as the if-else below

if (a < b) {
  min = a;
} else {
  min = b;
}

Enter fullscreen mode

Exit fullscreen mode

switch Statements

A switch statement is a condensed series of cascading else statements. It tests a value and compares it against multiple cases.

switch (grade) {
  case 9:
    printf("Freshman\n");
    break;
  case 10:
    printf("Sophomore\n");
    break;
  case 11:
    printf("Junior\n");
    break;
  case 12:
    printf("Senior\n");
    break;
  default:
    printf("Invalid\n");
    break;
}

Enter fullscreen mode

Exit fullscreen mode

Operators and Conditionals

A conditional in C can use relational operators such as &&, ||, and ! to compare values and test multiple expressions.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK