C PROGRAMMING NOTES , IOE
5.3. Branching Statement
In our daily life, we alter our actions and behavior based upon situations and conditions. For example: If it is rainy outside, I will stay at home, otherwise I will go for a walk. In the given example: depending upon the condition(rainy or not) we choose our action (stay inside or go for a walk).
In C programming, we can also alter the sequential execution of instruction by using a branching statement which is also called a decision or conditional statement. The decision statement like if-statement, if-else statement and switch-statement can be used for conditional execution of statements.
5.3.1. Simple if Statement
In C programming, we can impose simple conditional execution of statements by using if-statements. The general form of if-statement is:
if(condition)
statement
The above instruction tells the compiler that what follows if-statement is condition expression, which is expressed as relational or logical expression i.e(x==y, x!=y, x>y, x<y etc.), and return Boolean value i.e either 0 or 1. Depending upon the result of conditional expression or statement, the execution of statement is decided as follows:
The simple if-statement can be expressed in flowchart as follows:
Write a c program to check whether the given number is positive.
#include <stdio.h>
int main() {
// Declare variables
int number;
// Input: Get the number from the user
printf("Enter a number: ");
scanf("%d", &number);
// Simple if statement to check if the number is positive
if (number > 0)
printf("The number %d is positive.\n");
return 0;
}
Write a C program that asks to enter the total amount of a purchase from the user and calculate a discount based on the following criteria:
// Program Title: Discount Calculator (Single Statement in if)
#include <stdio.h>
int main() {
// Declare variables
float total, discount;
// Input: Get the total amount from the user
printf("Enter the total amount: ");
scanf("%f", &total);
// Simple if statement to calculate discount based on total amount
if (total > 1000)
discount = total - (0.10 * total);
// Note: Single statement in if, applies a 10% discount for amounts greater than 1000
// Output: Display the original and discounted amounts
printf("Original Amount: %.2f\n", total);
printf("Discounted Amount: %.2f\n", discount);
return 0;
}
Output:
Enter the total amount: 1500
Original Amount: 1500.00
Discounted Amount: 1350.00
Some Notes:
As mentioned above, the general form of if-statement is:
if(condition)
Statement
The condition enclosed within the bracket can be any valid:
int x = 5;
if (x > 0) {
// Your code here
}
and ..
int x = 5, y = 10;
if (x > 0 && y < 20) {
// Your code here
}
if(5+2%3)
{
...
}
if(-2)
{
}
All the above mathematical expressions are also perfectly valid for conditional statements as : all the non-zeros values are considered TRUE values while ZERO is considered FALSE value in C programming.
Multiple statement within if-statement
In C-programming, the default scope of the if-statement is the statement immediately next after it. Inorder to execute multiple statement for given statements, the statements need to be enclosed within pair of curly brackets. The general form of multiple statement within if-statement is:
if(condition)
{
statement 1;
statement2;
.
.
statement n;
}
Write a C program that asks the user to enter their annual income and calculate the tax amount based on following tax rate:
// Program Title: Tax Calculator (Single if-statement with Multiple Statements)
#include <stdio.h>
int main() {
// Declare variables
float income, tax;
// Input: Get the income from the user
printf("Enter your annual income: ");
scanf("%f", &income);
// Single if-statement with multiple instructions to calculate and display tax
if (income > 50000) {
tax = 0.05 * income;
printf("For your income Rs. %.2f tax is amount is : %.2f\n",income,tax);
}
return 0;
}
Output:
Enter your annual income: 55000
For your income Rs. 55000.00 tax is amount is : 2750.00
5.3.2. if-else Statement
The syntax of if statement as discussed above is:
if(condition)
statement1
or
if(condition)
{
statement1;
statement2;
.
.
statementn
}
The given syntax clearly states that in an if-statement, when the condition evaluates to TRUE(1 or any non-zero value) then a single statement or group of statements following it will be executed. The if-statement does not handle the case when the condition evaluates to FALSE(0). In the C programming language, it is possible to execute another set of statements when the condition evaluates to FALSE, such a statement is called an if-else statement. The syntax of if-else statement is:
if(condition)
statement1
else
statement2
or
if(condition)
{
statement1;
statement2;
.
.
statementn
}
else
{
statement1;
statement2;
.
.
statementn
}
NOTE: In the provided syntax, it explicitly indicates that there is no separate condition following the else statement. Instead, the code within the else block is executed when the condition in the if statement evaluates to FALSE.
Write a C Program to check whether the given number is even or odd.
#include <stdio.h>
int main() {
// Declare a variable to store the input number
int number;
// Prompt the user to enter a number
printf("Enter a number: ");
// Read the number from the user
scanf("%d", &number);
// Check if the number is even or odd
if (number % 2 == 0) {
// If the remainder of the division by 2 is 0, it's even
printf("%d is even.\n", number);
} else {
// If the remainder is not 0, it's odd
printf("%d is odd.\n", number);
}
// Return 0 to indicate successful execution
return 0;
}
output:
Enter a number: 2
2 is even.
Write a C Program to find the largest numbers among two given numbers.
#include <stdio.h>
int main() {
// Declare variables to store the two input numbers
int num1, num2;
// Prompt the user to enter the first number
printf("Enter the first number: ");
// Read the first number from the user
scanf("%d", &num1);
// Prompt the user to enter the second number
printf("Enter the second number: ");
// Read the second number from the user
scanf("%d", &num2);
// Check which number is larger
if (num1 > num2) {
// If num1 is greater than num2
printf("%d is the largest number.\n", num1);
} else if (num2 > num1) {
// If num2 is greater than num1
printf("%d is the largest number.\n", num2);
} else {
// If both numbers are equal
printf("Both numbers are equal.\n");
}
// Return 0 to indicate successful execution
return 0;
}
output:
Enter the first number: 4
Enter the second number: 5
5 is the largest number.
5.3.3. Nested if-else Statement
It is perfectly valid in C programming language to write multiple if-else statements within the given if-else statement; it is called a nested if-else statement. Here is the syntax to understand the nested if-else statement:
if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if both condition1 and condition2 are true
} else {
// code to be executed if condition1 is true and condition2 is false
if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if condition3 is false
}
// Additional nested if-else statements or code can be added here
}
} else {
// code to be executed if condition1 is false
if (condition4) {
// code to be executed if condition4 is true
} else {
// code to be executed if condition4 is false
}
// Additional nested if-else statements or code can be added here
}
Write a C Program to find the largest number among three given numbers.
#include <stdio.h>
int main() {
// Declare variables to store the three input numbers
int num1, num2, num3;
// Prompt the user to enter the first number
printf("Enter the first number: ");
// Read the first number from the user
scanf("%d", &num1);
// Prompt the user to enter the second number
printf("Enter the second number: ");
// Read the second number from the user
scanf("%d", &num2);
// Prompt the user to enter the third number
printf("Enter the third number: ");
// Read the third number from the user
scanf("%d", &num3);
// Check which number is the largest using nested if-else statements
if (num1 >= num2) {
// If num1 is greater than or equal to num2
if (num1 >= num3) {
// If num1 is greater than or equal to num3
printf("%d is the largest number.\n", num1);
} else {
// If num3 is greater than num1
printf("%d is the largest number.\n", num3);
}
} else {
// If num2 is greater than num1
if (num2 >= num3) {
// If num2 is greater than or equal to num3
printf("%d is the largest number.\n", num2);
} else {
// If num3 is greater than num2
printf("%d is the largest number.\n", num3);
}
}
// Return 0 to indicate successful execution
return 0;
}
output:
Enter the first number: 2
Enter the second number: 6
Enter the third number: -1
6 is the largest number.
5.3.4. else-if Ladder
In C, the else if statement provides a way to evaluate multiple conditions sequentially. It is particularly useful when you want to check additional conditions after the initial if condition has been found to be false. This helps in checking multiple conditions in the program in a more efficient and clear way. The general usage of else-if ladder is as:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
}else if (condition4) {
// code to be executed if condition4 is true
}
.
.
else {
// code to be executed if none of the conditions is true
}
Write a C Program to find the largest number among three given numbers.
#include <stdio.h>
int main() {
// Declare variables to store the three input numbers
int num1, num2, num3;
// Prompt the user to enter the first number
printf("Enter the first number: ");
// Read the first number from the user
scanf("%d", &num1);
// Prompt the user to enter the second number
printf("Enter the second number: ");
// Read the second number from the user
scanf("%d", &num2);
// Prompt the user to enter the third number
printf("Enter the third number: ");
// Read the third number from the user
scanf("%d", &num3);
// Check which number is the largest using else if statements
if (num1 >= num2 && num1 >= num3) {
// If num1 is greater than or equal to num2 and num3
printf("%d is the largest number.\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
// If num2 is greater than or equal to num1 and num3
printf("%d is the largest number.\n", num2);
} else {
// If num3 is greater than or equal to num1 and num2
printf("%d is the largest number.\n", num3);
}
// Return 0 to indicate successful execution
return 0;
}
Write a C program to check the type of triangle.
#include <stdio.h>
int main() {
// Declare variables to store the sides of the triangle
int side1, side2, side3;
// Prompt the user to enter the sides of the triangle
printf("Enter the length of side 1: ");
scanf("%d", &side1);
printf("Enter the length of side 2: ");
scanf("%d", &side2);
printf("Enter the length of side 3: ");
scanf("%d", &side3);
// Check the type of triangle using else if statements
if (side1 == side2 && side2 == side3) {
// If all sides are equal, it is an equilateral triangle
printf("It is an equilateral triangle.\n");
} else if (side1 == side2 || side2 == side3 || side1 == side3) {
// If two sides are equal, it is an isosceles triangle
printf("It is an isosceles triangle.\n");
} else {
// If no sides are equal, it is a scalene triangle
printf("It is a scalene triangle.\n");
}
// Return 0 to indicate successful execution
return 0;
}
5.3.5. switch Statement
The switch statement, more precisely called switch-case-default statement, helps us to make a decision from n-number of available choices. The general form of switch-case-default statement is as follows:
switch (expression) {
case constant1:
// code to be executed if expression equals constant1
case constant2:
// code to be executed if expression equals constant2
case constant3:
// code to be executed if expression equals constant3
case constant4:
// code to be executed if expression equals constant4
.
.
default:
// code to be executed if expression doesn't match any constant
}
Working of switch statement
First the expression following the switch statement is evaluated, the result of expression should be constant value either INTEGER constant or CHARACTER constant. Within the switch block we have n-number of cases in the format: case CONSTANT, the constant should be INTEGER or CHARACTER constant and finally a default case.
The result of switch expression is matched one by one against the case CONSTANTS. When a match is found, the statement following that particular case is executed as well as all following case and default statements are executed too.
Write a C program to day name for given day number
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
case 2:
printf("Tuesday\n");
case 3:
printf("Wednesday\n");
case 4:
printf("Thursday\n");
case 5:
printf("Friday\n");
case 6:
printf("Saturday\n");
case 7:
printf("Sunday\n");
default:
printf("Invalid day\n");
}
return 0;
}
Output:
Wednesday
Thursday
Friday
Saturday
Sunday
Invalid day
The output clearly shows this is not the output we are expecting, in order to stop the execution after the match is found, all the case-statements should be terminated by break-statement, as follows:
#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;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Output:
Wednesday
Note: The default case is executed only when none of the case constant matches the value of switch expression.
Write a C program to check whether the given letter is consonant or view using switch statement
#include <stdio.h>
#include<ctype.h>
int main() {
char letter;
// Input the letter from the user
printf("Enter a letter: ");
scanf("%c", &letter);
// Convert to lowercase to handle both uppercase and lowercase letters
letter = tolower(letter);
switch (letter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a vowel.\n", letter);
break;
default:
printf("%c is a consonant.\n", letter);
}
return 0;
}
5.3.6. goto statement
The goto statement in C allows you to jump to a specified label within the code. While its use is generally discouraged due to its potential to create spaghetti code and make the program harder to understand and maintain, there are situations where it might be considered acceptable.
Here's the basic syntax of the goto statement:
goto label;
// ...
label:
// code to be executed
And here's an example code using goto:
#include <stdio.h>
int main() {
int i = 0;
loop_start:
if (i < 5) {
printf("%d ", i);
i++;
goto loop_start;
}
printf("\nLoop finished.\n");
return 0;
}
In this example, the program prints numbers from 0 to 4 using a goto statement to create a loop. The label loop_start is defined, and the program jumps to this label using goto until the condition i < 5 becomes false.Another example code to understand goto statement:
#include <stdio.h>
int main() {
int choice;
menu:
printf("Menu:\n");
printf("1. Print Hello\n");
printf("2. Print World\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Hello\n");
goto menu; // Jump back to the menu
case 2:
printf("World\n");
goto menu; // Jump back to the menu
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
goto menu; // Jump back to the menu for invalid choices
}
return 0;
}
In this example, the program presents a simple menu with three options. If the user selects option 1, it prints "Hello" and jumps back to the menu using goto. Similarly, for option 2, it prints "World" and jumps back to the menu. Option 3 exits the program.