Conditional Statements
Conditional statements are used to execute some block of code based on whether the given condition is true. There are the following conditional statements in C:
if statement contains a block of code that will be executed if and only if the given condition is true.
Syntax of if
if (condition) { // statements }
The if-else statement contains the else block in addition to the if block which will be executed if the given condition is false.
Syntax if-else
if (expression) { // if block } else { // else block }
The if-else-if ladder is used when we have to test multiple conditions and for each of these conditions, we have a separate block of code.
Syntax of if-else-if
if (expression) { // block 1 } else if (expression) { // block 1 } . . . else { // else block }
The switch case statement is an alternative to the if-else-if ladder that can execute different blocks of statements based on the value of the single variable named switch variable.
Syntax of switch
switch (expression) { case value1: // statements break; case value2: // statements break; . . . default: // defualt block break; }
The conditional operator is a kind of single-line if-else statement that tests the condition and executes the true and false statements.
Syntax of Conditional Operator
(condition) ? (true-exp) : (false-exp);
Example of Conditional Statements
C
// C program to illustrate conditional statements #include <stdio.h> int main() { // conditional operator will assign 10 if 5 < 25, // otherwise it will assign 20 int i = 5 < 25 ? 10 : 20; if (i == 10) printf ( "i is 10" ); else if (i == 15) printf ( "i is 15" ); else if (i == 20) printf ( "i is 20" ); else printf ( "i is not present" ); } |
i is 10
C Cheat Sheet
This C Cheat Sheet provides an overview of both basic and advanced concepts of the C language. Whether you’re a beginner or an experienced programmer, this cheat sheet will help you revise and quickly go through the core principles of the C language.
In this Cheat Sheet, we will delve into the basics of the C language, exploring its fundamental concepts that lay the groundwork for programming. We will cover topics such as variables, data types, and operators, providing you with a solid understanding of the building blocks of C programming.
Contact Us