- Conditional Branching Statements
- Unconditional Branching Statements
Conditional Branching Statements:
In C, conditional branching statements are used to execute particular code blocks based on a condition (as needed). These branching instructions in C allow programmers to run the code only when specific conditions are met. The various categories of conditional branching statements in C are as follows:
- if Statement
- if-else Statement
- nested if-else Statement
- switch Statement
The if Statement:
The primary branching mechanism in C is the "if" statement. When a specific condition is satisfied, it allows the execution of a group of statements. The syntax for the "if" statement is as follows:
if (condition) {
// Code to execute if condition is true
}
Example:
#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
return 0;
}
Output:
The number is positive.
The if-else Statement:
By providing an alternative code block to execute when the condition evaluates to false, the "if-else" statement extends the functionality of the "if" statement. The structure of the "if-else" expression is as follows:
if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if condition is false
}
Example:
#include <stdio.h>
int main() {
int num = -5;
if (num > 0) {
printf("The number is positive.\n");
}
else {
printf("The number is non-positive.\n");
}
return 0;
}
Output:
The number is non-positive.
The nested if-else Statement:
You have the flexibility to include an "if-else" condition within another "if" or "else" block in C programming language because it facilitates the nesting of "if-else" statements. This feature enables you to handle diverse scenarios effectively. The structure of a nested "if-else" statement is as follows:
if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if condition2 is true
}
else {
// Code to execute if condition2 is false
}
}
else {
// Code to execute if condition1 is false
}
Example:
#include <stdio.h>
int main() {
int num = 0;
if (num > 0) {
printf("The number is positive.\n");
}
else if (num < 0) {
printf("The number is negative.\n");
}
else {
printf("The number is zero.\n");
}
return 0;
}
Output:
The number is zero.
The switch Statement:
Multiple functions can be executed with the "switch" statement depending on the variable or expression's value. This becomes particularly advantageous when handling numerous cases. The syntax for the "switch" statement is as follows:
switch (expression) {
case constant1:
// Code to execute if expression matches constant1
break;
case constant2:
// Code to execute if expression matches constant2
break;
// More cases...
default:
// Code to execute if expression doesn't match any constant
}
Example:
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Output:
Wednesday
Unconditional Branching Statements:
C uses unconditional branching statements to alter the typical course of program execution. These statements give programmers the freedom to jump to a specific location in their code under any circumstance. The various categories of unconditional branching statements in C are as follows:
- goto Statement
- break Statement
- continue Statement
goto Statement:
Programmers can utilize the "goto" command to jump directly to a specified labeled statement in their code, serving as an unconditional branching statement.
Syntax of goto Statement in C:
goto label;
...
label:
// code to be executed
The "goto" statement runs the code within the block after jumping to the statement labeled with a user-defined identifier following a colon. Any valid identifier can serve as the "label" for this purpose.
Example:
It is an illustration of a goto statement .
#include <stdio.h>
int main() {
int num = 1;
if (num == 1) {
goto label;
}
printf("This statement is skipped.\n");
label:
printf("The value of num is 1.\n");
return 0;
}
Output:
The value of num is 1.
Explanation:
In this scenario, the 'goto' command transfers the control to the specified 'label' statement, bypassing the following printf instruction, if the condition num == 1 evaluates to true. Subsequently, only the statement "The value of num is 1" will be displayed.
The 'break' Statement:
The "break" statement is commonly used in switch statements and various loop structures such as "for", "while", and "do-while". It allows you to bypass the following statement in the loop or switch and terminate the execution of the nearest enclosing loop or switch statement.
The "break" keyword in the C programming language is specified with the following syntax.
break;
Example:
Examine the illustration below depicting the application of the 'break' statement within a loop:
#include <stdio.h>
int main() {
int i;
for (i = 1; i<= 5; i++) {
if (i == 3) {
break;
}
printf("%d ", i);
}
return 0;
}
Output:
Explanation:
In this example, the 'for' loop runs through the numbers 1 to 5. Nevertheless, the 'break' statement is activated when i is equal to 3, causing the loop to halt prematurely. Consequently, only the digits 1 and 2 get displayed.
continue Statement
In C programming, the continue statement is employed to move to the subsequent iteration of a loop without executing the remaining code for the current iteration. It is commonly utilized within loop constructs such as for or while.
Syntax of continue statement in C is as follows:
continue;
When a loop reaches the continue statement, it terminates the current iteration and redirects control back to the loop's beginning for the next iteration to commence.
Example:
This example showcases the functionality of the C continue statement.
#include <stdio.h>
int main() {
int i;
for (i = 0; i< 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
printf("%d ", i);
}
return 0;
}
Output:
1 3 5 7 9
Explanation:
In the provided example, the for loop runs through values from 0 to 9. When the loop counter i is a multiple of 2 (i.e., even), the continue statement is triggered, causing the loop to skip that iteration and move on to the next one. Consequently, the printf statement exclusively displays odd numbers while bypassing the even ones.
Advantages and Disadvantages of Branching Statements
There are various advantages and disadvantages of the branching statements. Some main advantages and disadvantages of the branching statements are as follows:
Advantages of Branching Statements:
Enhanced Decision Making: Branching statements empower developers to determine the next course of action in their code based on specific conditions. This enhances the program's functionality and flexibility by enabling it to react and adjust to different scenarios.
Improving code readability: Conditional statements enhance the clarity and simplicity of the code logic. They offer clear indications to other developers about the decision-making flow within the program, aiding in comprehension and maintenance of the codebase.
Branching statements enhance the efficiency of code execution by selectively executing specific code blocks based on predefined conditions. This optimization can significantly improve program performance, particularly when utilizing the "switch" statement to handle extensive sets of cases or intricate decision trees.
Programming flexibility is achieved by utilizing branching statements, allowing the execution of different code paths based on varying conditions. This versatility is particularly beneficial when a program must promptly adjust to changing inputs or external factors.
Code Reusability: Branching statements simplify the reuse of code by allowing the execution of code blocks based on different conditions. By effectively using branching statements, developers can craft modular code that is easily recyclable across different sections of the program.
Disadvantages of Branching Statements:
Code Complexity: Excessive utilization or deep nesting of branching statements can lead to decreased code clarity and comprehension. This can introduce challenges in maintenance, increase the likelihood of defects, and result in lower-quality code. Therefore, it is essential to use branching statements judiciously and strive for simplicity.
Readability Challenges: While branching statements can enhance code clarity, they can introduce complications if employed haphazardly. Excessive nesting, intricate conditions, or redundant code segments can all contribute to a decrease in code readability and comprehension.
Potential for Errors in Reasoning: When the conditions are not thoroughly defined and verified, conditional statements are at risk of logical errors.
Maintaining code becomes more challenging due to the complexity of branching statements. Understanding the code logic and implementing changes can be arduous, especially when dealing with multiple branching statements and nested conditions.
Let's explore additional examples to observe the application of conditional statements in different scenarios:
Example 1: Finding the Maximum Number
#include <stdio.h>
int main() {
int num1 = 10;
int num2 = 20;
int max;
if (num1 > num2) {
max = num1;
}
else {
max = num2;
}
printf("The maximum number is: %d\n", max);
return 0;
}
Output:
The maximum number is: 20
Explanation:
In this example, the highest value is determined by evaluating two numerical values (num1 and num2) through an "if-else" statement. The script assigns the variable max to the greater of the two numbers before presenting it on the console.
Example 2: Grade Classification
#include <stdio.h>
int main() {
int marks;
printf("Enter the marks: ");
scanf("%d", &marks);
if (marks >= 90) {
printf("Grade: A\n");
}
else if (marks >= 80) {
printf("Grade: B\n");
}
else if (marks >= 70) {
printf("Grade: C\n");
}
else if (marks >= 60) {
printf("Grade: D\n");
}
else {
printf("Grade: F\n");
}
return 0;
}
Output (for input 78):
Grade: C
Explanation:
In this example, the software takes in the student's scores as input and identifies the academic level using an "if-else if" ladder. The system displays the relevant grade on the screen according to the entered marks.
Example 3: Month Name
#include <stdio.h>
int main() {
int monthNumber;
printf("Enter the month number (1-12): ");
scanf("%d", &monthNumber);
switch (monthNumber) {
case 1:
printf("January\n");
break;
case 2:
printf("February\n");
break;
case 3:
printf("March\n");
break;
case 4:
printf("April\n");
break;
case 5:
printf("May\n");
break;
case 6:
printf("June\n");
break;
case 7:
printf("July\n");
break;
case 8:
printf("August\n");
break;
case 9:
printf("September\n");
break;
case 10:
printf("October\n");
break;
case 11:
printf("November\n");
break;
case 12:
printf("December\n");
break;
default:
printf("Invalid month number\n");
}
return 0;
}
Output (for input 8):
August
Explanation:
In this scenario, the computer accepts the numerical representation of a month from the user and employs a "switch" statement to determine the corresponding month's name. Subsequently, the system displays the relevant month name on the console according to the provided input.
Example 4: Leap Year Check
#include <stdio.h>
int main() {
int year;
printf("Enter the year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
printf("%d is a leap year.\n", year);
}
else {
printf("%d is not a leap year.\n", year);
}
return 0;
}
Output (for input 2024):
2024 is a leap year.
Explanation:
In the preceding instance, the for loop runs from 0 to 9, and if the loop counter i is even, the continue statement is triggered, moving control to the next iteration. Consequently, the printf statement displays solely odd numbers, bypassing even ones.
Conclusion:
Developers frequently utilize branching constructs as they empower them to alter the flow of code execution depending on specific conditions. This article delves into the essential branching statements in the C programming language, including the "if", "if-else", nested "if-else", and "switch" expressions.
The "if-else" statement enhances the conditional code execution capability of the "if" statement by providing an extra code block to run when the condition is false. This allows for more versatile decision-making as multiple conditions can be accommodated within nested blocks using the nested "if-else" statement. In contrast, the "switch" statement streamlines handling multiple scenarios by allowing different actions to be taken based on the value of a variable or expression.
Understanding the utilization of branching statements empowers developers to exercise greater influence over the flow of their programs, enabling the creation of more sophisticated and adaptive applications. It is essential to explore different conditions and situations extensively to enhance understanding and proficiency in employing branching statements effectively.
As you progress in your comprehension of C programming, remember that conditional statements are powerful instruments that enhance the adaptability and reasoning of the code. Through experience and dedication, you will cultivate the skills required to make optimal choices and construct robust, efficient programs.