The document discusses different types of loops in C programming language including while, for, and do-while loops. It provides examples of infinite loops and explains how to use ranges in switch-case statements. Key differences between if-else and switch statements are also summarized such as their definitions, expressions evaluated, order of execution, and speeds.
Download as PPT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
29 views
C - Loops
The document discusses different types of loops in C programming language including while, for, and do-while loops. It provides examples of infinite loops and explains how to use ranges in switch-case statements. Key differences between if-else and switch statements are also summarized such as their definitions, expressions evaluated, order of execution, and speeds.
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31
C - Loops
Dr. Shalini Gambhir
C - Loops • You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. • Programming languages provide various control structures that allow for more complicated execution paths. • A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages − C programming language provides the following types of loops to handle looping requirements Loop Control Statements • Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. • C supports the following control statements. The Infinite Loop • A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty. • #include <stdio.h> • int main () • { for( ; ; ) { printf("This loop will run forever.\n"); } return 0; } When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.
• NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
if-else vs switch What is an if-else statement? An if-else statement in C programming is a conditional statement that executes a different set of statements based on the condition that is true or false. The 'if' block will be executed only when the specified condition is true, and if the specified condition is false, then the else block will be executed. Syntax of if-else statement is given below: if(expression) { // statements; } else { // statements; } • What is a switch statement? • A switch statement is a conditional statement used in C programming to check the value of a variable and compare it with all the cases. If the value is matched with any case, then its corresponding statements will be executed. Each case has some name or number known as the identifier. The value entered by the user will be compared with all the cases until the case is found. If the value entered by the user is not matched with any case, then the default statement will be executed.
• Syntax of the switch statement is given below:
• switch(expression) • { • case constant 1: • // statements; • break; • case constant 2: • // statements; • break; • case constant n: • // statements; • break; • default: • // statements; • } Similarity b/w if-else and switch • Both the if-else and switch are the decision- making statements. • Decision-making statements mean that the output of the expression will decide which statements are to be executed. Differences b/w if-else and switch statement • The following are the differences between if-else and switch statement are: 1. Definition • if-else • Based on the result of the expression in the 'if-else' statement, the block of statements will be executed. If the condition is true, then the 'if' block will be executed otherwise 'else' block will execute. • Switch statement • The switch statement contains multiple cases or choices. The user will decide the case, which is to execute. 2. Expression • If-else • It can contain a single expression or multiple expressions for multiple choices. In this, an expression is evaluated based on the range of values or conditions. It checks both equality and logical expressions. • Switch • It contains only a single expression, and this expression is either a single integer object or a string object. It checks only equality expression. 3. Evaluation • If-else • An if-else statement can evaluate almost all the types of data such as integer, floating- point, character, pointer, or Boolean. • Switch • A switch statement can evaluate either an integer or a character. 4. Sequence of Execution • If-else • In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed based on the condition. • Switch • In the case of the 'switch' statement, one case after another will be executed until the break keyword is not found, or the default statement is executed. 5. Default Execution • If-else • If the condition is not true within the 'if' statement, then by default, the else block statements will be executed. • Switch • If the expression specified within the switch statement is not matched with any of the cases, then the default statement, if defined, will be executed. 6. Values • If-else • Values are based on the condition specified inside the 'if' statement. The value will decide either the 'if' or 'else' block is to be executed. • Switch • In this case, value is decided by the user. Based on the choice of the user, the case will be executed. 7. Use • If-else • It evaluates a condition to be true or false. • Switch • A switch statement compares the value of the variable with multiple cases. If the value is matched with any of the cases, then the block of statements associated with this case will be executed. 8. Editing • If-else Editing in 'if-else' statement is not easy as if we remove the 'else' statement, then it will create the havoc. • Switch • Editing in switch statement is easier as compared to the 'if-else' statement. If we remove any of the cases from the switch, then it will not interrupt the execution of other cases. Therefore, we can say that the switch statement is easy to modify and maintain. 9. Speed • If-else • If the choices are multiple, then the speed of the execution of 'if-else' statements is slow. • Switch • The case constants in the switch statement create a jump table at the compile time. This jump table chooses the path of the execution based on the value of the expression. If we have a multiple choice, then the execution of the switch statement will be much faster than the equivalent logic of 'if-else' statement. Using range in switch case in C • We can use a range of numbers instead of a single number or character in the case statement. • Range in switch case can be useful when we want to run the same set of statements for a range of numbers so that we do not have to write cases separately for each value. • You can specify a range of consecutive values in a single case label. • Syntax • The syntax for using range case is: • case low ... high: It can be used for a range of ASCII character codes like this: • case 'A' ... 'Z': • You need to Write spaces around the ellipses ( … ). • For example, write this: • // Correct - case 1 ... 5: • // Wrong - case C program to illustrate using range in switch case • #include <stdio.h> • int main() • { • int arr[] = { 1, 5, 15, 20 }; • • for (int i = 0; i < 4; i++) { • switch (arr[i]) { • // range 1 to 6 • case 1 ... 6: • printf("%d in range 1 to 6\n", arr[i]); • break; • // range 19 to 20 • case 19 ... 20: • printf("%d in range 19 to 20\n", arr[i]); • break; • default: • printf("%d not in range\n", arr[i]); • break; • } • } • return 0; • } • Output • 1 in range 1 to 6 • 5 in range 1 to 6 • 15 not in range • 20 in range 19 to 20 Error conditions • low > high: The compiler gives an error message. • Overlapping case values: If the value of a case label is within a case range that has already been used in the switch statement, the compiler gives an error message. Exercise • Try the same program for a char array by modifying the char array and case statement. while loop in C • The while Loop is an entry-controlled loop in C programming language. This loop can be used to iterate a part of code while the given condition remains true. • Syntax • The while loop syntax is as follows: • while (test expression) • { // body consisting of multiple statements } Example • // C program to demonstrate while loop • #include <stdio.h> • int main() • { • // Initialization of loop variable • int i = 0; • // setting test expression as (i < 5), means the loop • // will execute till i is less than 5 • while (i < 5) { • // loop statements • printf(“KeepSmiling\n"); • • // updating the loop variable • i++; • } • return 0; • } • Output • KeepSmiling • KeepSmiling • KeepSmiling • KeepSmiling • KeepSmiling while Loop Structure • The while loop works by following a very structured top-down approach that can be divided into the following parts: • Initialization: In this step, we initialize the loop variable to some initial value. Initialization is not part of while loop syntax but it is essential when we are using some variable in the test expression
• Conditional Statement: This is one of the most crucial steps as it decides
whether the block in the while loop code will execute. The while loop body will be executed if and only the test condition defined in the conditional statement is true.
• Body: It is the actual set of statements that will be executed till the specified condition is true. It is generally enclosed inside { } braces.
• Updation: It is an expression that updates the value of the loop
variable in each iteration. It is also not part of the syntax but we have to define it explicitly in the body of the loop. Flowchart of while loop in C Working of while Loop • Working of the while loop by looking at the flowchart: • STEP 1: When the program first comes to the loop, the test condition will be evaluated.
• STEP 2A: If the test condition is false, the body of the
loop will be skipped, program will continue.
• STEP 2B: If the expression evaluates to true, the body
of the loop will be executed.
• STEP 3: After executing the body, the program control
will go to STEP 1. This process will continue till the test expression is true. Infinite while loop • An infinite while loop is created when the given condition is always true. It is encountered by programmers in when: • The test condition is incorrect. • Updation statement not present. Example • // C program to demonstrate an infinite while loop • #include <stdio.h> • int main() • { • // Initialization • int g1 = 1; • int g2 = 1; • • // 'g1' is the Check/Test statement, which means that • // the while loop will iterate till the conditions • // satiate • while (g1 < 10) { • • // ‘g2' is the body statements • g2 =g2 + 1; • printf(“KeepSmiling to Infinity"); • } • // Return statement to tell that everything executed • // safely • return 0; • } • Output • KeepSmiling to Infinity • KeepSmiling to Infinity • KeepSmiling to Infinity ......................... • The loop will continue till infinite because the loop variable will always remain the same resulting in the condition that is always true. • Important Points • It is an entry-controlled loop. • It runs the block of statements till the conditions are satiated, once the conditions are not satisfied it will terminate. • Its workflow is firstly it checks the condition and then executes the body. Hence, a type of pre-tested loop. • This loop is generally preferred over for loop when the number of iterations is unknown.