1 1 Module-2
1 1 Module-2
statements
MODULE-2
Contents:
• Introduction to decision control
• Conditional branching statements:
• if
• if-else
• if-else-if
• switch case
• Iterative statements:
• For
• While
• do- while
• Nested loops
Decision making statements in ‘C’
• When you are going to write some program, it
will always be necessary that you will have to
put some code which has to be executed only
when a specific condition is satisfied.
• Your program must take decision based on
internal/external events or conditions.
• For example, if the user presses a key, then
execute ‘this’ set of statements or if the user
doesn’t press any key, then execute ‘that’ set
of statements.
• In embedded programming, let’s take an
example of water level indication and control
program. If the sensor detects water level
rising above the threshold, then the program
executes the code to turn off the motor,
otherwise program doesn’t turn off the motor.
SELECTION OR BRANCHING STATEMENTS:
• The C statements that transfer the control from one
place to other place in the program with or without
any condition are called branching or selection
statements.
• The selection / branching statements can be
classified into two categories:
1] Conditional Control /Branch Statements:
• Conditional branching statements that alter the
sequence of execution of the program based on
some condition are called Conditional branching
statements/ selection statements /decision
statements.
• Conditional Control /Branch Statements are as
follows: simple if (single selection), if-else (two
way selection), Nested if (multiple if statements),
else –if ladder (multi-way selection), switch
( multi-way selection).
Example
#include <stdio.h>
int main() {
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
} else {
printf("x is not greater than 5\n");
}
return 0;
}
Output is: 5
SELECTION OR BRANCHING STATEMENTS:
2] Unconditional Control /Branch Statement:
• The statements that alter the sequence of execution of the program based on some
unconditioned are called Unconditional branching statement.
• Unconditional Control /Branch Statements are as follows: Goto Statement, break
Statement, continue Statement and return Statement.
#include <stdio.h>
int main() {
Output:
int num = 1;
Number: 1
start:
Number: 2
printf("Number: %d\n", num);
Number: 3
num++;
Number: 4
if (num <= 5) {
Number: 5
goto start;
}
return 0;
}
Introduction to decision
control:
• A conditional branching statement like the ‘if’ statement in C programming allows you to control the flow of execution
based on certain conditions.
• The ‘if’ statement is fundamental in controlling program flow and implementing conditional logic in C programs.
• Purpose: The ‘if’ statement is used to execute a block of code only if a specified condition is true.
• Syntax:
if (condition)
}
How it works:
The ‘if’ keyword is followed by a condition enclosed in parentheses (condition).
If the condition is true, the code block inside the curly braces ‘{}’ is executed.
If the condition is false, the code block inside the curly braces is skipped, and the program continues executing the next statement
after the ‘if’ block.
Example:
if (num > 5)
Use Cases:
else
• How it works:
• The if keyword is followed by a condition enclosed in parentheses (condition).
• If the condition is true, the code block inside the first set of curly braces {} is executed.
• If the condition is false, the code block inside the else block's curly braces is executed.
• Example:
int num = 10; Use Cases:
• Implementing binary decisions where an action is taken
if (num > 15) if a condition is true, and another action is taken if the
condition is false.
{
• Handling mutually exclusive scenarios based on the
printf("Number is greater than 15\n"); evaluation of a condition.
}
Difference between if and if-else statement:
• In if, the statements inside the if block will execute, if the condition is
true and the control is passed to the next statement after the if block.
• In the if else, if the condition is true, the statements inside the if block
will execute and if the condition is false the statements in the if else
block will execute.
#include <stdio.h>
#include <stdio.h>
int main() {
int main() { int age;
int age;
printf("Enter your age: ");
printf("Enter your age: "); scanf("%d", &age);
scanf("%d", &age);
if (age >= 18) {
if (age >= 18) { printf("You are eligible to vote.\n");
printf("You are eligible to vote.\n"); } else {
} printf("You are not eligible to vote.\n");
}
return 0;
} return 0;
}
Conditional branching statements:
if-else-if statement:
• The "if-else-if" statement, is a conditional branching statement used in
programming languages like C.
• It allows you to test multiple conditions and execute different blocks of
code based on the outcome of these conditions.
• Syntax:
if (condition1) {
// code block 1
} else if (condition2) {
// code block 2
} else {
// default code block
}
Working:
The if statement checks condition1. If it's true, code block 1 executes.
If condition1 is false, the else if part checks condition2. If condition2 is true,
code block 2 executes.
If neither condition1 nor condition2 is true, the else part executes the default
code block.
Example:
int num = 10;
if (num > 0) {
printf("Positive\n");
} else if (num < 0) {
printf("Negative\n");
} else {
printf("Zero\n");
}
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
return 0;
}
Finding the Largest Number
#include <stdio.h>
int main() {
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
return 0;
}
The main differences between the if-else statement and the if-else-if statement (nested if) in C programming are:
1. Usage:
• The if-else statement is used to execute a block of code if a condition is true. If the condition is false, the code inside the else block
executes.
• The if-else-if statement is used when you have multiple conditions to check sequentially. It allows you to test multiple conditions and
execute different blocks of code based on these conditions.
2. Structure:
• The if-else statement has a simple structure with an initial if condition followed by an optional else block.
• The if-else-if statement has a more complex structure with an initial if condition followed by multiple else if conditions, and an optional else
block at the end.
3. Execution:
• In the if-else statement, only one block of code (either the if block or the else block) is executed based on the condition's evaluation.
• In the if-else-if statement, multiple conditions are sequentially tested. Once a condition is true, the corresponding block of code executes,
and the remaining conditions are not evaluated.
4. Decision Making:
• The if-else statement is suitable for simple decision-making scenarios where there are only two possible outcomes based on a single
condition.
• The if-else-if statement is suitable for more complex decision-making scenarios where there are multiple conditions to be checked in a
specific order.
#include <stdio.h>
// Using if-else-if statement
int main() { if (num > 0) {
int num = 10; printf("Number is positive.\n");
} else if (num < 0) {
// Using if-else statement printf("Number is negative.\n");
if (num > 0) { } else {
printf("Number is positive.\n"); printf("Number is zero.\n");
} else { }
printf("Number is not positive.\n");
} return 0;
}
Multiple Conditions using if-else if-else (if else if
ladder)
int score = 85;
if (score >= 90) {
printf("Grade A\n");
} else if (score >= 80) {
printf("Grade B\n");
} else if (score >= 70) {
printf("Grade C\n");
} else {
printf("Grade F\n");
}
Conditional branching statements:
switch case :
• A "switch case" statement is a type of conditional branching statement commonly
used in programming languages like C, C++, Java, and others.
• It allows you to execute one out of several possible blocks of code based on the
value of an expression or variable.
• Overall, switch case statements offer a structured approach to handle multiple
conditional branches based on the value of an expression, enhancing code
readability and maintainability.
• Syntax:
switch (expression) {
case value1:
// Code to be executed if expression == value1
break;
case value2:
// Code to be executed if expression == value2
break;
...
default:
// Code to be executed if expression doesn't match any case
}
• The switch keyword is followed by an expression in parentheses.
• Inside the curly braces, there are multiple case statements each followed by a value.
• The break statement is used to exit the switch case block.
• The default case is optional and executes when none of the other cases match.
Execution Flow:
The expression inside the switch is evaluated.
The value of the expression is compared with each case value sequentially.
If a match is found, the corresponding block of code is executed, and the
switch case block is exited unless a break statement is encountered.
If no match is found and there is a default case, its block of code is executed.
Use Cases:
Switch case statements are often used when there are multiple conditions to be
checked against a single variable.
They provide a more organized and efficient way to handle multiple conditions
compared to nested if-else statements, especially when each condition
corresponds to a specific value.
Note:
• The case values must be unique and constants (integer, character, enum, or string literals in
some languages).
• The break statement is crucial to prevent "fall-through," where execution continues into
subsequent cases after a match.
• If-Else is executed based on the condition inside the statement and is used to choose between
two options. Switch Case executes as per the user decision and is used to choose among
multiple options.
Example-1:
#include <stdio.h>
int main() {
int choice;
printf("Enter a number between 1 and 3: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You entered 1.\n");
break;
case 2:
printf("You entered 2.\n");
break;
case 3:
printf("You entered 3.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
#include <stdio.h> case 'g':
#include <string.h> case 'G':
printf("Green\n");
int main() { break;
char color[10]; case 'b':
case 'B':
printf("Enter a color (red, green, blue): "); printf("Blue\n");
scanf("%s", color); break;
default:
switch (color[0]) { printf("Unknown color\n");
case 'r': }
case 'R':
printf("Red\n"); return 0;
break; }
1. Start the program.
2. Declare a character array color of size 10.
3. Display a message asking the user to enter a color (red, green, blue).
4. Read the input color from the user using scanf and store it in the character array color.
5. Use a switch case statement to check the first character of the input color (color[0]):
• If the first character is 'r' or 'R', print "Red" and then exit the switch case block using break.
• If the first character is 'g' or 'G', print "Green" and then exit the switch case block using
break.
• If the first character is 'b' or 'B', print "Blue" and then exit the switch case block using
break.
• If the first character does not match any of the cases, print "Unknown color".
• If num is 2, print "Two" and then exit the switch case block using break.
• If num is 3, print "Three" and then exit the switch case block using break.
• If num is 4, print "Four" and then exit the switch case block using break.
• If num is 5, print "Five" and then exit the switch case block using break.
int main() {
int i;
for (i = 0; i < 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
In this example, the loop initializes i to 0, checks if i is less than 5 in each iteration, and
increments i by 1 after each iteration. The loop prints "Iteration 0" to "Iteration 4".
Components:
• Initialization: It sets the initial value of the loop control variable.
• Condition: It defines the condition that must be true for the loop to continue executing.
• Increment/Decrement: It updates the loop control variable to progress towards the termination condition.
• Loop Body: It contains the code to be executed repeatedly as long as the condition is true.
Common Usages:
• Iterating over arrays or sequences.
• Performing a specific number of iterations.
• Implementing counters and accumulators.
• Generating number sequences.
Note:
• The initialization, condition, and increment/decrement parts are optional but
commonly used.
• The loop control variable is often used as an index in arrays or for counting iterations.
#include <stdio.h>
int main() {
// Declare a 5x5 array
int matrix[5][5];
int main() {
for(int i = 1; i <= 10; i++)
{
printf("%d ", i);
}
return 0;
}
Example-2: Calculating Factorial
#include <stdio.h>
int main() {
int n = 5;
int factorial = 1;
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
int main()
{
for(int i = 0; i <= 10; i += 2)
{
printf("%d ", i);
}
return 0;
}
Iterative statements:
While
• The while statement is an iterative control structure in programming that repeats a block
of code as long as a specified condition is true.
• Syntax:
while (condition) {
// code block to be executed while the condition is true
}
• Behavior:
• Condition Check: The condition inside the parentheses is evaluated before each iteration. If the
condition is true, the code block inside the while loop is executed.
• Loop Execution: As long as the condition remains true, the code block inside the while loop
continues to execute.
• Exiting the Loop: When the condition becomes false, the loop terminates, and program control
moves to the statement immediately following the while loop.
Example:
#include <stdio.h>
int main() {
int count = 1;
printf("Loop ended.\n");
return 0;
}
Key Points:
• The condition in a while loop is evaluated before each iteration.
• The loop continues to execute as long as the condition remains true.
• Care should be taken to avoid infinite loops by ensuring that the condition eventually becomes false during the loop
execution.
Example-1: Countdown from 10 to 1
#include <stdio.h>
int main() {
int count = 10;
while(count >= 1) {
printf("%d ", count);
count--;
}
printf("\n");
return 0;
}
Example-2: Summing Numbers Entered by the User
#include <stdio.h>
int main() {
int num, sum = 0;
while(1) {
scanf("%d", &num);
if(num == 0) break;
sum += num;
}
int main() {
int n = 5;
int factorial = 1;
int i = 1;
while(i <= n) {
factorial *= i;
i++;
}
int main() {
int n = 10;
int prev = 0, curr = 1, next;
while(n > 0) {
printf("%d, ", prev);
next = prev + curr;
prev = curr;
curr = next;
n--;
}
printf("\n");
return 0;
}
Example-5: Copying Characters from one
String to Another
#include <stdio.h>
int main() {
char source[] = "Hello, world!";
char destination[20];
int i = 0;
while(source[i] != '\0') {
destination[i] = source[i];
i++;
}
destination[i] = '\0';
Number of Iterations These must be known when using a for loop. The while loop works well even if the number of
iterations is basically unknown.
Condition It is a form of relational expression. The condition, in this case, may be a non-zero value
or an expression.
Initialization The initialization may exist both- outside the loop or The initialization, in this case, always occurs outside
in the loop statement. the loop.
Time of Increment The increment occurs only after the execution of the We can perform the increment both- after or before
statement(s). the execution of the given statement(s).
Use We use the for loop when the increment and We use the while loop in the case of a complex
initialization are very simple. initialization.
Iterative statements:
do- while
• The do-while loop is an iterative statement in C programming that executes a
block of code repeatedly until a specified condition becomes false.
• Unlike the while loop, which checks the condition before entering the loop,
the do-while loop checks the condition after executing the loop's body at least
once.
• Syntax:
do {
// code to be executed
} while(condition);
Execution Flow:
• The block of code inside the do statement is executed first, regardless of the
condition.
• After executing the code inside the do block, the condition is evaluated.
• If the condition is true, the loop repeats, executing the do block again.
• If the condition is false, the loop terminates, and program control moves to the
statement immediately following the do-while loop.
• Key Points:
• The do-while loop guarantees that the loop's body is executed at least
once, even if the condition is initially false.
• The loop continues to execute as long as the condition remains true.
• The condition is checked after each iteration, so even if the condition
becomes false during the loop's execution, the loop completes its current
iteration before terminating.
Example:
#include <stdio.h>
printf("\n");
return 0;
}
Use Cases:
• Use the do-while loop when you want to execute a block of code at least once,
regardless of the condition's initial value.
• It is commonly used when you need to perform an action and then check a condition
to decide whether to repeat the action.
Example-1: Reading Input Until a Valid Value is Entered
#include <stdio.h>
int main() {
int num;
do
{
printf("Enter a positive number: ");
scanf("%d", &num);
}
while(num <= 0);
switch(choice) { }
Example-3: Calculating Factorial
#include <stdio.h>
int main() {
int n, factorial = 1;
int i = 1;
scanf("%d", &n);
do {
factorial *= i;
i++;
return 0;
}
Example-4: Generating Fibonacci Series
#include <stdio.h> do {
int main() { printf("%d, ", first);
return 0;
}
While loop: 1. Begin the program.
2. Declare variables n (for the input number), i (loop
#include <stdio.h>
variable initialized to 1), and factorial (to store the
int main() { factorial value).
int n, i = 1; 3. Prompt the user to enter a number and read the
unsigned long long factorial = 1; input into variable n.
4. Initialize factorial to 1.
printf("Enter a number to calculate factorial: ");
scanf("%d", &n);
5. Start a while loop with the loop condition i <= n.
• Inside the loop, multiply factorial by i.
while(i <= n) { • Increment i by 1 in each iteration.
factorial *= i;
6. After the loop, print the calculated factorial using the
i++;
}
printf function.
7. End the program.
printf("Factorial using while loop: %llu\n", factorial);
return 0;
}
Do-While loop: 1. Begin the program.
2. Declare variables n (for the input number), i (loop
#include <stdio.h> variable initialized to 1), and factorial (to store the
factorial value).
int main() {
3. Prompt the user to enter a number and read the input
int n, i = 1;
into variable n.
unsigned long long factorial = 1;
4. Initialize factorial to 1.
printf("Enter a number to calculate factorial: "); 5. Start a do-while loop with the loop condition i <= n.
scanf("%d", &n); • Inside the loop, multiply factorial by i.
• Increment i by 1 in each iteration.
do {
6. After the loop, print the calculated factorial using the
factorial *= i;
printf function.
i++;
} while(i <= n); 7. End the program.
return 0;
}