0% found this document useful (0 votes)
10 views29 pages

Programming LU4

The document discusses control flow in programming, focusing on loops, if statements, and switch statements in C. It explains different types of loops such as counter-controlled and sentinel-controlled repetitions, as well as the syntax and use cases for for, while, and do-while loops. Additionally, it covers conditional statements, including if, else, and nested if statements, emphasizing their importance for decision-making and code clarity.

Uploaded by

Kumbu Mwanganya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views29 pages

Programming LU4

The document discusses control flow in programming, focusing on loops, if statements, and switch statements in C. It explains different types of loops such as counter-controlled and sentinel-controlled repetitions, as well as the syntax and use cases for for, while, and do-while loops. Additionally, it covers conditional statements, including if, else, and nested if statements, emphasizing their importance for decision-making and code clarity.

Uploaded by

Kumbu Mwanganya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Control Flow

and Program
Loops
BICT1201
Program Loops
 In C, a program loop is a control flow statement that allows a block of code to be
executed repeatedly when a certain condition is met, or for a specified number
of times.
 Loops are fundamental for automating repetitive tasks, processing data
collections (like arrays), and implementing algorithms that require iteration.
 Instead of writing the same code multiple times, a loop enables you to automate
repetitive tasks, making your code shorter, easier to read, and more efficient
Counter-controlled and
Sentinel-controlled Repetition
 Counter-controlled repetition
 Definite repetition: know how many times the loop will execute
 Control variable used to count repetitions
 Sentinel-controlled repetition
 Indefinite repetition
 Used when the number of repetitions is not known. The loop continues to execute until a certain
condition is met, but it is not predetermined how often this will happen.
 This type of loop is often used when waiting for user input or processing data until a sentinel value is
encountered. The sentinel value indicates “end of data.”
Counter-controlled
repetitions
The counter-controlled repetition requires
 The name of a control variable (or loop counter)
 The initial value of the control variable
 An increment (or decrement) by which the control variable is modified each time
through the loop
 A condition that tests for the final value of the control variable (i.e., whether looping
should continue)
Loop example
int counter = 1; // initialization
while ( counter <= 10 ) { // repetition condition printf( "%d\n", counter );
++counter; // increment
}
for loop
 A for loop in C is a control flow statement that provides a concise way to execute a
block of code repeatedly. It's particularly well-suited for situations where you know, or
can calculate, how many times you want the loop to run.
 It consists of three main parts, all enclosed in parentheses and separated by
semicolons, followed by the block of code (the loop body) to be executed.
 for (initialization; condition; increment/decrement) {

// statement(s) or code block to be executed


// this is called the "loop body“
}
for loop
 The initialization part is executed only once when the loop first starts.
 It's typically used to declare and/or initialize a loop control variable (often called a
counter or an iterator).
 Example: int i = 0;

 Condition
 This part is evaluated before each iteration of the loop (including the first one, after
initialization).
 If the condition evaluates to true (any non-zero value in C), the loop body is executed.
 If the condition evaluates to false (zero), the loop terminates, and the program
continues with the statement immediately following the for loop.
 Example: i < 10; or character != '\0';
For loop flowchart
for loop
 increment/decrement (or more generally, "update"):
 This part is executed at the end of each iteration, after the loop body has been executed and before
the condition is rechecked for the next iteration.
 It's typically used to modify the loop control variable, bringing it closer to the termination condition.
 Example: i++ (increment i by 1), i-- (decrement i by 1), i += 2 (increment i by 2), count = count * 2.
 The for loop can contain arithmetic expressions. If x equals 2 and y equals 10

for ( j = x; j <= 4 * x * y; j += y / x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )
For loop example
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}

printf("Loop finished.\n");
return 0;
}
For loop exercise
 Use the for loop to calculate the compound interest for a principal of 100,000 at
a 5 percent rate with a 10-year duration.
 The formula used to calculate the amount is
 A=P×(1+r) n
Where;
A = Amount after n years (future value)
P = Principal (initial amount)
r = Interest rate per period (as a decimal)
n = Number of periods (years)
While loop
 A while loop is a control flow statement in programming that repeatedly executes a block
of code as long as a specified Boolean condition remains true.
 It is often described as a "pre-test loop" because the condition is evaluated before each
iteration of the loop body.
 If the condition is true, the code inside the loop runs; if false, the loop terminates, and
the program continues with the next statement after the loop.
 The condition is checked first.
 If the condition is true, the loop body executes.
 After executing the loop body, the condition is rechecked.
 This process repeats until the condition becomes false
While loop example
//this is printing x whilst it is less than 5
int x = 0;
while (x < 5) {
printf("x = %d\n", x);
x++;
}
Do While loop
 A do-while loop in C is a control structure that executes a block of code at least
once and then repeatedly executes it as long as a specified condition remains
true.
 Unlike a regular while loop, which checks the condition before executing the
loop body, the do-while loop checks the condition after the loop body has
executed.
 This guarantees that the loop body runs at least once regardless of the
condition.
Do while loop example
// printing I whilst I is less than 5
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
While and do while loop
 The loops constructed with while and do-while appear similar. You can easily
convert a while loop into a do-while loop and vice versa.
 There are a few differences between while and do-while Loops
 The obvious syntactic difference is that the do-while construct starts with the do
keyword and ends with the while keyword. The while loop doesn't need the do keyword.
 Secondly, you find a semicolon in front of while in the case of a do-while loop. There is
no semicolon in while loops.
While and do while loop
While loop Do while
//declare and initialize a to 0 //declare and initialize b to 0
printf("Output of while loop: \n"); printf("Output of do-while loop: \n");
while(a < 5){ do{
a++; b++;
printf("a: %d\n", a); printf("b: %d\n",b);
} } while(b < 5);
Switch statement
 A switch statement in C is a control flow statement that allows you to execute
one block of code from multiple options based on the value of an expression.
 It is often used as a cleaner and more readable alternative to multiple if...else if
statements when you need to compare a single variable against several
constant values.
Switch statement syntax
switch (expression) {
case constant1:
// code block
break;
case constant2:
// code block
break;
// more cases...
default:
// code block if no case matches
}
Switch statement example
int day = 4; case 4:
switch (day) {
printf("Thursday");
case 1:
break;
printf("Monday");
break; case 5:
case 2: printf("Friday");
printf("Tuesday");
break;
break;
default:
case 3:
printf("Wednesday"); printf("Weekend");
break; }
Switch statement exercise
 Write a program where a user enters a student’s grade (A–F), and use the switch
statement to have different cases for each grade.
If Statement
 An if statement in C is a fundamental conditional control flow statement.
 It allows your program to make decisions by executing a code block only if a
specified condition is true. If the condition is false, that block of code is skipped.
 The basic syntax is ;

if (condition) {
// code to execute if condition is true
}
If statement example
//an example of an if statement
int score = 95;
if (score >= 90) {
printf("Grade A\n");
}
If else statements
int age = 21;
if (age >= 18) {
printf("You are eligible to vote!\n");
} else {
printf("You are not eligible to vote.\n");
}
Nested if statements
 A nested if statement in C is an if statement placed inside another if (or else if)
statement.
 This means you can check multiple conditions where the evaluation of an inner
condition depends on the outer condition being true.
 Nested ifs allow more precise decision-making when you need to test additional
conditions within a prior true condition.
Nested if statements example
#include <stdio.h> // Inner if: number is even
printf("The number %d is positive and even.\n", number);
} else {
int main() {
// Inner else: number is odd
int number;
printf("The number %d is positive and odd.\n", number);
}
printf("Enter an integer: "); } else {

scanf("%d", &number); // Outer else: number is zero or negative


printf("The number %d is not positive.\n", number);
}
if (number > 0) {
// Outer if: number is positive
return 0;
if (number % 2 == 0) { }
Conclusion
 Program looping, if statements, and switch statements are essential control structures in
programming because they enable dynamic control of program flow, allowing programs to make
decisions and perform repetitive tasks efficiently.
 Decision Making
 If statements and switch statements allow a program to evaluate conditions and execute different blocks of
code based on those conditions. This ability to choose between alternatives is fundamental for creating
responsive and intelligent programs. Without conditionals, programs would be limited to executing the same
sequence of instructions regardless of input or state.
 Code Clarity and Optimization
 Using if and switch statements helps organize code logically, making it easier to read and maintain. They also
provide hints to compilers or interpreters for optimizations, such as simplifying branching or inlining functions

You might also like