if else statement in Programming Language

Rumman Ansari   Software Engineer   2024-11-12 10:58:40   819  Share
Subject Syllabus DetailsSubject Details Login to Open Video
☰ TContent
☰Fullscreen

Table of Content:


The if statement is a fundamental control structure in programming languages that allows you to execute a block of code only if a specified condition is true. It’s commonly used for decision-making, where the program takes one path if the condition is met and can optionally take another if it’s not.


Basic Structure of an if Statement

Most programming languages have a similar structure for the if statement. Here’s a general syntax:


if (condition) {
    // code to execute if the condition is true
} 

if Statement control flow

if statement control flow
Figure: if statement control flow


Basic Structure of an if-else Statement


if (condition) {
    // code to execute if the condition is true
} else {
    // optional: code to execute if the condition is false
}

if else Statement control flow

if-else control flow
Figure: if-else control flow


if Statement in Various Programming Languages

Here’s how the if statement looks in some popular programming languages:

Language Example Code Explanation
Java if (x > 0) { System.out.println("Positive"); } Executes if x is greater than 0.
Python if x > 0: print("Positive") No braces; uses indentation to define scope.
C if (x > 0) { printf("Positive\n"); } Common in C-based languages; braces enclose blocks.
JavaScript if (x > 0) { console.log("Positive"); } Similar to Java; uses braces.
Ruby if x > 0 puts "Positive" end Uses end to close the block instead of braces.
PHP if ($x > 0) { echo "Positive"; } Uses $ to denote variables; braces enclose blocks.



Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.