if..else construction
The if...else Construction is a fundamental control flow statement in programming. It allows your code to make decisions by executing specific blocks of code only when certain conditions are met.
At its simplest, it evaluates a condition as either True or False.
Basic Structure
The syntax varies slightly by language, but the logic remains the same:
if: Executes the code block if the condition is True.else: Provides an alternative path if theifcondition is False.
Conceptual Example (Pseudocode)
if (it is raining) {
take an umbrella
} else {
wear sunglasses
}
Expanding the Logic
When you have more than two possibilities, you use else if (or elif in languages like Python) to test multiple conditions in sequence.
| Statement | Purpose |
if | The initial condition to check. |
else if | Additional conditions to check if the previous ones were False. |
else | The “catch-all” block if no previous conditions were True. |
Implementation in Python
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Best Practices
Order Matters: Conditions are evaluated from top to bottom. Once one condition is met, the program executes that block and skips the rest of the chain. Always place your most specific conditions at the top.
Keep it Readable: If you find yourself nesting
ifstatements too deeply (e.g., anifinside anifinside anif), consider using aswitchormatchstatement, or breaking your logic into smaller functions.Boolean Logic: You can combine multiple conditions using logical operators:
and: Both conditions must be True.or: At least one condition must be True.not: Reverses the boolean value.
Here are the following examples in the if..else construction for different programming languages
C
C++
Common Lisp
Dart
F#
Go
Java
JavaScript
Python
Rust
int n = 21;
if (n > 22)
{
printf("n > 22 \n");
}
else if (n < 22)
{
printf("n < 22 \n");
}
else
{
printf("n == 22 \n");
}C++
#include <iostream>
int main()
{
int n {21};
if (n > 22)
{
std::cout << "n > 22" << std::endl;
}
else if (n < 22)
{
std::cout << "n < 22" << std::endl;
}
else
{
std::cout << "n == 22" << std::endl;
}
// if-else with variable initialization
int a {5};
int b {3};
if(int c {a - b}; a > b)
{
std::cout << "a + b = " << c << std::endl;
}
else
{
std::cout << "a - b = " << c << std::endl;
}
}
C#
C#
int n = 21;
if(n > 22)
{
Console.WriteLine("n > 22");
}
else if (n < 22)
{
Console.WriteLine("n < 22");
}
else
{
Console.WriteLine("n = 22");
}
Common Lisp
Lisp
(let ((n 21))
(if (> n 22)
(format t "n > 22")
(if (< n 22)
(format t "n < 22")
(format t "n = 22"))))
If the if block must have several expressions, which are formatted using the progn operator:
Lisp
(let ((n 21))
(if (< n 22)
(progn
(format t "n < 22~%")
(format t "n != 22~%"))))
To test the truth of a condition, you can also use the when macro, which is similar to if..then:
Lisp
(let ((n 21))
(when (< n 22)
(format t "n < 22~%")
(format t "n != 22~%")))
The unless macro is equivalent to an else expression and tests the opposite condition:
Lisp
(let ((n 22))
(when (< n 22)
(format t "n < 22~%")
(format t "n != 22~%"))
(unless (< n 22)
(format t "n >= 22~%")))
Dart
Dart
void main() {
int n = 21;
if(n > 22){
print("n > 22");
}
else if(n < 22){
print("n < 22");
}
else{
print("n = 22");
}
}
F#
F#
let n = 21
if n > 22 then
printfn "n > 22"
elif n < 22 then
printfn "n < 22"
else
printfn "n = 22"
Getting the result from if..then
F#
let a = 21
let b = 22
let res = if(a > b) then 1 elif(a < b) then -1 else 0
printfn "%d" res
Go
Go
package main
import "fmt"
func main() {
n := 21
if n > 22 {
fmt.Println("n > 22")
} else if n < 22{
fmt.Println("n < 22")
} else{
fmt.Println("n == 22")
}
}
Java
Java
class Program {
public static void main(String[] args) {
int n = 21;
if(n > 22)
{
System.out.println("n > 22");
}
else if (n < 22)
{
System.out.println("n < 22");
}
else
{
System.out.println("n = 22");
}
}
}
JavaScript
JavaScript
let n = 21;
if(n > 22) {
console.log("n > 22");
}
else if (n < 22){
console.log("n < 22");
}
else{
console.log("n == 22");
}
Kotlin
Kotlin
fun main() {
val n = 21
if(n > 22) {
println("n > 22")
}
else if(n < 22){
println("n < 22")
}
else{
println("n = 22")
}
}
Getting the result from if..else
Kotlin
fun main() {
val a = 21
val b = 22
val res = if(a > b) 1 else if(a < b) -1 else 0
println(res) // -1
}
Python
Python
n = 21
if n > 22:
print("n > 22")
elif n < 22:
print("n < 22")
else:
print("n = 22")
Getting the result from if..else
Python
a = 21
b = 22
res = 1 if(a > b) else -1
print(res)
Rust
Rust
fn main(){
let n = 21;
if n > 22 {
println!("n > 22")
}
else if n < 22 {
println!("n < 22")
}
else{
println!("n = 22")
}
}
Getting the result from if..else
Rust
fn main(){
let a = 21;
let b = 22;
let res = if a > b {1} else {-1};
println!("{}", res);
}
NextExplore More IT Terms
#
A
- A Guide to SQL Query Formatting
- A/B testing
- Agile
- Algorithm complexity in 5 minutes
- Algorithms and Data Structures in C#
- An overview of the C # programming language
- An overview of the Python programming language
- Anaconda Python
- Android
- Android App Bundle
- Android SDK
- Angular
- Ansible
- Apache
- Apache Airflow
- Apache Kafka
- Apache Tomcat
- App Store
- AppCode
- Array-based stack
- ArrayList
- ASCII
- ASP.NET
- Assembly Language Lessons
B
C
D
- Data Analytics: applications of data analysis in companies
- Data Engineer - Who is it, what does a data engineer do, and an overview of the profession
- Data modeling: what it is, types, and process steps.
- Data preprocessing: a complete guide for beginners and professionals.
- Data structure
- Data structures
- Defining Aliases
- Defining Arrays
- Deque
- Developing a Website from Scratch
- Digital data: understand the importance of this asset for businesses.
- Doubly linked lists
E
F
H
- Handling errors and exceptions
- How to effectively organize your workflow
- How to Learn Java: Tips for Beginner Developers
- How to Learn PHP: A Beginner's Guide
- How to Use S3 Storage in Kubernetes with CSI
- HTML
- HTML and CSS: Definition, Application, and Operating Principles
- HTML and CSS. Layout from Scratch: What to Learn, Where to Learn, and How Long Will It Take?
- HTML Frame Structure
- HTML Link Formatting
I
- if..else construction
- Inheritance in Java: A Complete Guide to Principles and Implementation
- Inserting an Image
- Interactive Python Tutorial – Learn Programming from Scratch
- Interview Problem: Finding a Deleted Element in O(N)
- Interview Scare: The FizzBuzz Challenge
- Introduction to C++
- Introduction to Machine Learning
- Introduction to programming languages
- IT Specialist Resume (CV)
J
K
M
O
P
S
- SFML Graphics Library Tutorials
- SQL commands: see what they are, what the main ones are + examples
- SQL Interview Questions and Tasks
- SQL Lessons
- SQL Stored Procedures
- SQL Syntactic Sugar: The COALESCE Function
- Stack
- Start in analytics: Python or R
- Statistical analysis: importance for decision making.
- String formatting in Python
- Swift Lessons
- switch/match construct
T
W
- What are databases, and why do they need DBMS and SQL?
- What do Linux distributions consist of?
- What is .NET and what is it used for?
- What is a GPU in a computer, in simple terms?
- What is Big Data? Introduction, Types, Characteristics, and Examples
- What is Golang and what is it used for?
- What is Haskell and what is it used for?
- What is Kotlin and what is it used for?
- What is Linux? The History of Linux
- What is machine learning, and how does it work?
- What is Power BI: everything about the data analytics software
- What is the C++ programming language?
- What is the OSI Model: A Complete Explanation of the Seven Layers and Their Role in Networking
- Where to start learning the C programming language?
- Which Linux distribution should you choose? A Linux distribution overview
