C if Statement

You are Here:

C if Statement

The if is a control statement, executes a block of user-defined code only when the condition is true; otherwise, the block will be skipped.

Syntax

if (condition){ // user-defined code }

The following 4 example programs will help you to understand the if statement better.

Using Boolean Value

In the below example C program, we will directly hard code the first if conditional statement to 'true' and the other if conditional statement to 'false' to get the desired output.

Source Code

C Compiler
#include <stdio.h> #include<stdbool.h> int main() { bool x = true; bool y = false; if(x){ // Here condition is 'true' printf("Execute this block \n"); } if(y){ // Here condition is 'false' printf("Skip this block \n"); } printf("I will always execute"); return 0; }

Output

Execute this block I will always execute

Using Number

The conditional statement that returns anything other than 0 (zero) is true

Source Code

C Compiler
#include <stdio.h> #include<stdbool.h> int main() { if(1){ // Here the condition is 'true' printf("1 - Execute this block \n"); } if(0){ // Here the condition is 'false' printf("Skip this block \n"); } if(0.01){ // Here the condition is 'true' printf("0.01 - Execute this block \n"); } printf("I will always execute"); return 0; }

Output

1 - Execute this block 0.01 - Execute this block I will always execute

Using String

The conditional statement that returns the string datatype is always true.

Source Code

C Compiler
#include <stdio.h> int main() { if("hello"){ printf("Hello is a string \n"); } if("0"){ printf("Here '0' is a string \n"); } printf("I will always execute"); return 0; }

Output

Hello is a string Here '0' is a string I will always execute

Real World Example

In the below example program, we will check whether the value in a variable x is greater than 50.

Source Code

C Compiler
#include <stdio.h> int main() { int x = 75; if(x > 50){ printf("%d is greater than 50",x); } return 0; }

Output

75 is greater than 50
congratulation

Congratulation! you have learned everything about if statement in C Programming.

Reminder

Hi Developers, we almost covered 98% of String functions and Interview Question on C with examples for quick and easy learning.

We are working to cover every Single Concept in C.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author