Example of if Statement in Programming
Let’s explore examples of “if” statements in various programming languages:
1. if Statement in C:
C
#include <stdio.h> int main() { int x = 5; if (x > 0) { printf ("x is positive\n"); } return 0; } |
x is positive
Explanation: In this example, the condition x > 0 is evaluated to true because x is greater than 0. Therefore, the code inside the if block is executed, which prints “x is positive” to the console.
2. if Statement in C++:
C++
#include <iostream> using namespace std; int main() { int x = 5; if (x > 0) { printf ("x is positive\n"); } return 0; } |
x is positive
Explanation: In this example, the condition x > 0 is evaluated to true because x is greater than 0. Therefore, the code inside the if block is executed, which prints “x is positive” to the console.
3. if Statement in Java:
Java
public class Main { public static void main(String[] args) { int x = 5 ; if (x > 0 ) { System.out.println("x is positive"); } } } |
x is positive
Explanation: In this example, the condition x > 0 is evaluated to true because x is greater than 0. Therefore, the code inside the first if block is executed, which prints “x is positive” to the console.
4. if Statement in Python:
Python3
x = 5 if x > 0 : print ("x is positive") |
x is positive
Explanation: In this example, the condition x > 0 is evaluated to true because x is greater than 0. Therefore, the code inside the first if block is executed, which prints “x is positive” to the console.
5. if Statement in Javascript:
Javascript
let x = 5; if (x > 0) { console.log("x is positive"); } |
x is positive
Explanation: In this example, the condition x > 0 is evaluated to true because x is greater than 0. Therefore, the code inside the first if block is executed, which prints “x is positive” to the console.
6. if Statement in C#:
C#
using System; class Program { static void Main() { int x = 5; if (x > 0) { Console.WriteLine("x is positive"); } } } |
x is positive
Explanation: In this example, the condition x > 0 is evaluated to true because x is greater than 0. Therefore, the code inside the first if block is executed, which prints “x is positive” to the console.
If statement in Programming
An if statement is a fundamental control structure in programming languages that allows you to execute specific code blocks based on whether a condition is true or false. It is used to make decisions and control the flow of execution in your program.
Table of Content
- What is an If Statement?
- Example of If Statement in Programming
- Conditional Operators in If Statements
- Common Mistakes to Avoid
- Best Practices for Using If Statements
Contact Us