if else statement in Programming Language
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
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 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. |
- Question 1:
Question:
Given the following code fragment:
if (a == 0) System.out.println("Zero"); if (a == 1) System.out.println("One"); if (a == 2) System.out.println("Two"); if (a == 3) System.out.println("Three");Write an alternative code (using
if) that saves on the number of comparisons. - Question 2:
What is the problem of dangling-else?
When does it arise?
What is the default dangling-else matching, and how can it be overridden? - Question 3:
Question:
Rewrite the following fragment using
switch:if (ch == 'E') eastern++; if (ch == 'W') western++; if (ch == 'N') northern++; if (ch == 'S') southern++; else unknown++;