Conditional statements in programming are used to control the flow of a program based on certain conditions. These statements allow the execution of different code blocks depending on whether a specified condition evaluates to true or false, providing a fundamental mechanism for decision-making in algorithms. In this article, we will learn about the basics of Conditional Statements along with their different types.
What are Conditional Statements in Programming?Conditional statements in Programming, also known as decision-making statements, allow a program to perform different actions based on whether a certain condition is true or false. They form the backbone of most programming languages, enabling the creation of complex, dynamic programs.
5 Types of Conditional Statements in ProgrammingConditional statements in programming allow the execution of different pieces of code based on whether certain conditions are true or false. Here are five common types of conditional statements:
5 Types of Conditional Statements in Programming 1. If Conditional Statement:The if statement is the most basic form of conditional statement. It checks if a condition is true. If it is, the program executes a block of code.
Syntax of If Conditional Statement:if (condition) {
// code to execute if condition is true
}
if condition is true, the if code block executes. If false, the execution moves to the next block to check.
Use Cases of If Conditional Statement:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = 10;
if (x > 0) {
cout<<"x is positive";
}
return 0;
}
Java
public class Main {
public static void main(String[] args) {
int x = 10;
// Check if x is greater than 0
if (x > 0) {
System.out.println("x is positive"); // Print a message if x is positive
}
}
}
Python
class Main:
def main():
x = 10
# Check if x is greater than 0
if x > 0:
print("x is positive") # Print a message if x is positive
if __name__ == "__main__":
main()
C#
using System;
class Program
{
static void Main(string[] args)
{
int x = 10;
if (x > 0)
{
Console.WriteLine("x is positive");
}
// This code checks if the variable x is positive.
}
}
JavaScript
function main() {
let x = 10;
// Check if x is greater than 0
if (x > 0) {
console.log("x is positive"); // Print a message if x is positive
}
}
// Call the main function
main();
2. If-Else Conditional Statement:
The if-else statement extends the if statement by adding an else clause. If the condition is false, the program executes the code in the else block.
Syntax of If-Else Conditional Statement:if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
if condition is true, the if code block executes. If false, the execution moves to the else block.
Use Cases of If-Else Conditional Statement:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = -10;
if (x > 0) {
cout << "x is positive";
}
else {
cout << "x is not positive";
}
return 0;
}
Java
public class Main {
public static void main(String[] args) {
// Define the value of x
int x = -10;
// Check if x is greater than 0
if (x > 0) {
System.out.println("x is positive");
} else {
System.out.println("x is not positive");
}
}
}
Python
def main():
# Define the value of x
x = -10
# Check if x is greater than 0
if x > 0:
print("x is positive")
else:
print("x is not positive")
# Call the main function to execute the code
if __name__ == "__main__":
main()
C#
using System;
class Program
{
static void Main(string[] args)
{
int x = -10;
// Check if x is greater than 0
if (x > 0)
{
Console.WriteLine("x is positive");
}
else
{
Console.WriteLine("x is not positive");
}
}
}
JavaScript
// Main function
function main() {
// Define the value of x
const x = -10;
// Check if x is greater than 0
if (x > 0) {
console.log("x is positive");
} else {
console.log("x is not positive");
}
}
// Call the main function to execute the program
main();
3. if-Else if Conditional Statement:
The if-else if statement allows for multiple conditions to be checked in sequence. If the if condition is false, the program checks the next else if condition, and so on.
Syntax of If-Else if Conditional Statement:if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if all conditions are false
}
In else if statements, the conditions are checked from the top-down, if the first block returns true, the second and the third blocks will not be checked, but if the first if block returns false, the second block will be checked. This checking continues until a block returns a true outcome.
Use Cases of If-Elif-Else Conditional Statement:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = 0;
if (x > 0) {
cout << "x is positive";
}
else if (x < 0) {
cout << "x is not positive";
}
else {
cout << "x is not zero";
}
return 0;
}
Java
public class Main {
public static void GFG(int x) {
// Check if the number is positive
if (x > 0) {
System.out.println("x is positive");
}
// Check if the number is negative
else if (x < 0) {
System.out.println("x is not positive");
}
// If the number is neither positive nor negative
// it must be zero
else {
System.out.println("x is not zero");
}
}
public static void main(String[] args) {
// Test the function with the sample number
int x = 0;
GFG(x);
}
}
Python
def GFG(x):
# Check if the number is positive
if x > 0:
print("x is positive")
# Check if the number is negative
elif x < 0:
print("x is not positive")
# If the number is neither positive nor negative
# it must be zero
else:
print("x is not zero")
# Test the function with the sample number
x = 0
GFG(x)
JavaScript
let x = 0;
// Check if the number is positive
if (x > 0) {
console.log("x is positive");
}
// If not positive, check if the number is negative
else if (x < 0) {
console.log("x is not positive");
}
// If neither positive nor negative
// the number is zero
else {
console.log("x is not zero");
}
4. Switch Conditional Statement:
The switch statement is used when you need to check a variable against a series of values. It’s often used as a more readable alternative to a long if-else if chain.
In switch expressions, each block is terminated by a break keyword. The statements in switch are expressed with cases.
Switch Conditional Statement Syntax:
switch (variable) {Use Cases of Switch Statement:
case value1:
// code to execute if variable equals value1
break;
case value2:
// code to execute if variable equals value2
break;
default:
// code to execute if variable doesn't match any value
}
#include <iostream>;
using namespace std;
int main()
{
int x = 2;
switch (x) {
case 1:
cout << "x is one";
break;
case 2:
cout << "x is two";
break;
default:
cout << "x is neither one nor two";
}
return 0;
}
Java
public class Main {
public static void main(String[] args) {
// Declare and initialize the variable x
int x = 2;
// Use a switch statement to check the value of x
switch (x) {
// If x is 1, print "x is one"
case 1:
System.out.println("x is one");
break;
// If x is 2, print "x is two"
case 2:
System.out.println("x is two");
break;
// For any other value of x, print "x is neither one nor two"
default:
System.out.println("x is neither one nor two");
}
}
}
//This code is contributed By monu.
Python
def main():
# Define x
x = 2
# Switch statement equivalent in Python using dictionary
switch_case = {
1: "x is one",
2: "x is two"
}
# Get the corresponding value for x
result = switch_case.get(x, "x is neither one nor two")
# Print the result
print(result)
if __name__ == "__main__":
main()
#this code is cotributed by Utkarsh.
JavaScript
// Declare and initialize the variable x
let x = 2;
// Use a switch statement to check the value of x
switch (x) {
// If x is 1, print "x is one"
case 1:
console.log("x is one");
break;
// If x is 2, print "x is two"
case 2:
console.log("x is two");
break;
// For any other value of x, print "x is neither one nor two"
default:
console.log("x is neither one nor two");
}
5. Ternary Expression Conditional Statement:
The ternary operator is a shorthand way of writing an if-else statement. It takes three operands: a condition, a result for when the condition is true, and a result for when the condition is false.
Syntax of Ternary Expression:condition ? result_if_true : result_if_falseUse Cases of Ternary Expression:
#include <iostream>;
using namespace std;
int main()
{
int x = 10;
string result
= (x > 0) ? "x is positive" : "x is not positive";
cout << result;
return 0;
}
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
// Define an integer variable x and assign the value
// 10 to it
int x = 10;
// Use a ternary operator to check if x is positive
// or not If x is greater than 0, assign "x is
// positive" to the result variable Otherwise,
// assign "x is not positive" to the result variable
String result = (x > 0) ? "x is positive"
: "x is not positive";
// Print the result to the console
System.out.println(result);
}
}
Python
# Define an integer variable x and assign the value
# 10 to it
x = 10
# Use a ternary operator to check if x is positive
# or not. If x is greater than 0, assign "x is
# positive" to the result variable. Otherwise,
# assign "x is not positive" to the result variable.
result = "x is positive" if x > 0 else "x is not positive"
# Print the result to the console
print(result)
JavaScript
// Define an integer variable x and assign the value
// 10 to it
let x = 10;
// Use a ternary operator to check if x is positive
// or not. If x is greater than 0, assign "x is
// positive" to the result variable. Otherwise,
// assign "x is not positive" to the result variable.
let result = x > 0 ? "x is positive" : "x is not positive";
// Print the result to the console
console.log(result);
Difference between Types of Conditional Statements in Programming: Conditional Statement Purpose Usage Example if Execute code if condition is true Single condition if x > 5: print("x is greater than 5")
if-else Execute one block if condition is true, another if false Two mutually exclusive possibilities if x > 5: print("x is greater than 5") else: print("x is not greater than 5")
if-elif-else Execute based on multiple conditions Multiple conditions, sequential evaluation python if x > 5: print("x is greater than 5") elif x == 5: print("x is equal to 5") else: print("x is less than 5")
switch-case Select one of many code blocks to execute based on a variable Matching variable against multiple cases java switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Unknown day"); }
Difference between If Else and Switch Case: Feature if-else
Statement switch
Statement Multiple Conditions Supports multiple conditions using else if
Supports multiple cases using case
statements Equality Comparison Can handle complex conditions with relational operators Typically checks equality with case
values Range Comparison Can handle ranges using logical operators Typically handles discrete values, not suitable for ranges Fall-Through Executes the first true condition and exits Continues executing cases until break
or end. Default Case Optional else
block for default behavior default
case for unmatched values Expression Type Supports any boolean expression in the condition Typically used with expressions resulting in discrete values Readability and Maintainability Readability may decrease with nested conditions Readability can be maintained for multiple cases Use Cases Suitable for various conditions and complex logic Suitable for scenarios with distinct, known values Best Practices for Conditional Statements in Programming:
In conclusion, Conditional statements are a fundamental part of programming, allowing for dynamic and interactive programs. By understanding and using them effectively, you can create programs that are more efficient, readable, and maintainable.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4