Unit – 3
Conditional Branching And Loops
Control structure is the important concept in high level programming languages. Control structures are the instruction or the group of instructions in the programming language which are responsible to determine the sequence of other instructions in the program. Control structure is used for the reusability of the code. Control structure is useful when the program demands to repeatedly execute block of code for specific number of times or till certain condition is satisfied. Control structures can control the flow of execution of program based on some conditions. Following are the advantages of using control structures in C language.
- Increases the reusability of the code
- Reduces complexity, improves clarity, and facilitates debugging and modifying
- Easy to define in flowcharts
- Increases programmer productivity.
- Control statements are also useful in the indentation of the program.
There are two types of control statements
Conditional Branching: In conditional branching decision point is based on the run time logic. Conditional branching makes use of both selection logic and iteration logic. In conditional branching flow of program is transfer when the specified condition is satisfied.
Fig. Flowchart for conditional branching
Unconditional Branching: In Unconditional branching flow of program is transfer to a particular location without concerning the condition. Unconditional branching makes use of sequential logic. In unconditional branching flow of program is transfer as per the instruction.
Conditional Branching
In conditional branching change in sequence of statement execution is depends upon the specified condition. Conditional statements allow programmer to check a condition and execute certain parts of code depending on the result of conditional expression. Conditional expression must be resulted into Boolean value. In C language, there are two forms of conditional statements:
1. if-----else statement: It is used to select one option between two alternatives
2. switch statement: It is used to select one option between multiple alternative
- if Statements
This statement permits the programmer to allocate condition on the execution of a statement. If the evaluated condition found to be true, the single statement following the "if" is execute. If the condition is found to be false, the following statement is skipped. Syntax of the if statement is as follows
if (condition)
statement1;
statement2;
In the above syntax, “if” is the keyword and condition in parentheses must evaluate to true or false. If the condition is satisfied (true) then compiler will execute statement1 and then statement2. If the condition is not satisfied (false) then compiler will skip statement1 and directly execute statement2.
if-----else statement
This statement permits the programmer to execute a statement out of the two statements. If the evaluated condition is found to be true, the single statement following the "if" is executed and statement following else is skipped. If the condition is found to be false, statement following the "if" is skipped and statement following else is executed.
In this statement “if” part is compulsory whereas “else” is the optional part. For every “if” statement there may be or may not be “else” statement but for every “else” statement there must be “if” part otherwise compiler will gives “Misplaced else” error.
Syntax of the “if----else” statement is as follows
if (condition)
statement1;
else
statement2;
In the above syntax, “if” and “else” are the keywords and condition in parentheses must evaluate to true or false. If the condition is satisfied (true) then compiler will execute statement1 and skip statement2. If the condition is not satisfied (false) then compiler will skip statement1 and directly execute statement2.
Nested if-----else statements :
Nested “if-----else” statements are used when programmer wants to check multiple conditions. Nested “if---else” contains several “if---else” a statement out of which only one statement is executed. Number of “if----else” statements is equal to the number of conditions to be checked. Following is the syntax for nested “if---else” statements for three conditions
if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else
statement4;
In the above syntax, compiler first check condition1, if it trues then it will execute statement1 and skip all the remaining statements. If condition1 is false then compiler directly checks condition2, if it is true then compiler execute statement2 and skip all the remaining statements. If condition2 is also false then compiler directly checks condition3, if it is true then compiler execute statement3 otherwise it will execute statement 4.
Note:
If the test expression is evaluated to true,
• Statements inside the body of if are executed.
• Statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
• Statements inside the body of else are executed
• Statements inside the body of if are skipped from execution.
// Check whether an integer is odd or even
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
Program to relate two integers using =, > or < symbol
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
//checks if the two integers are equal.
if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
}
//checks if both test expressions are false
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
- Switch Statements
This statement permits the programmer to choose one option out of several options depending on one condition. When the “switch” statement is executed, the expression in the switch statement is evaluated and the control is transferred directly to the group of statements whose “case” label value matches with the value of the expression. Syntax for switch statement is as follows:
switch(expression)
{
case constant1:
statements 1;
break;
case constant2:
statements 2;
break;
…………………..
default:
statements n;
break;
}
In the above, “switch”, “case”, “break” and “default” are keywords. Out of which “switch” and “case” are the compulsory keywords whereas “break” and “default” is optional keywords.
- “switch” keyword is used to start switch statement with conditional expression.
- “case” is the compulsory keyword which labeled with a constant value. If the value of expression matches with the case value then statement followed by “case” statement is executed.
- “break” is the optional keyword in switch statement. The execution of “break” statement causes the transfer of flow of execution outside the “switch” statements scope. Absence of “break” statement causes the execution of all the following “case” statements without concerning value of the expression.
- “default” is the optional keyword in “switch” statement. When the value of expression is not match with the any of the “case” statement then the statement following “default” keyword is executed.
Example: Program to spell user entered single digit number in English is as follows
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a number");
scanf("%d",&n);
switch(n)
{
case 0: printf("\n Zero");
break;
case 1: printf("\n One");
break;
case 2: printf("\n Two");
break;
case 3: printf("\n Three");
break;
case 4: printf("\n Four");
break;
case 5: printf("\n Five");
break;
case 6: printf("\n Six");
break;
case 7: printf("\n Seven");
break;
case 8: printf("\n Eight");
break;
case 9: printf("\n Nine");
break;
default: printf("Given number is not single digit number");
}
getch();
}
Output
Enter a number
5
Five
Unconditional Branching
In unconditional branching statements are executed without concerning the condition. Unconditional statements allow programmer to transfer the flow of execution to any part of the program. In C language, there are four types of unconditional statements:
- Break statement: It is the unconditional jump instruction. It is used mainly with “switch” and loop statements. The execution of “break” instruction, transfer the flow of program outside the loop or “switch” statement Syntax of “break” statement is as follows
break;
When “break” statement used inside loops then execution of “break” statement causes the immediate termination of loop and compiler will execute next statement after the loop statement.
2. Goto statement: “goto” statement is used to transfer the flow of program to any part of the program. The syntax of “go to” statement is as follows
goto label name;
In the above syntax “goto” is keyword which is used to transfer the flow of execution to the label specified after it. Label is an identifier that is used to mark the target statement to which the control is transferred. The target statement must be labeled and the syntax is as follows
label name statement;
In the above syntax label name can be anything but it should be same as that of name of the label specified in “goto” statement, a colon must follow the label. Each labeled statement within the function must have a unique label, i.e., no two statements can have the same label.
3. Continue statement: It is used mainly with “switch” and “loop” statements. The execution of “continue” instruction, skip the remaining iteration of the loop and transfer he flow of program to the loop control instruction. Syntax of “continue” statement is as follows
continue;
4. Return statement: The “return” statement terminates the execution of the current function and return control to the calling function. The “return” statement immediately ends the function, ignoring everything else in the function after it is called. It immediately returns to the calling function and continue from the point that it is called. Return also able to "return" a value which can be use in the calling function.
Iteration statements create loops in the program. In other words, it repeats the set of statements until the condition for termination is met. Iteration statements in C are for, while and do-while.
while statement:
The while loop in C is most fundamental loop statement. It repeats a statement or block while its controlling expression is true.
The general form is:
while(condition) {
// body of loop
}
The condition can be any boolean expression. The body of the loop will be executed if the conditional expression is true.
Here is more practical example.
The output of the program is:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
do-while statement
The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.
Its general form is:
do{
// body of loop
} while(condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of C’s loops, condition must be a Boolean expression.
The program presented in previous while statement can be re-written using do-while as:
//example program to illustrate do-while looping
#include <stdio.h>
int main ()
{
int n = 10;
do
{
printf("tick %d", n);
printf("\n");
n--;
}while (n > 0);
}
for loop
Here is the general form of the traditional for statement:
for(initialization; condition; iteration) {
// body
}
The program from previous example can be re-written using for loop as:
//example program to illustrate for looping
#include <stdio.h>
int main ()
{
int n;
for(n = 10; n>0 ; n--){
printf("tick %d",n);
printf("\n");
}
}
The output of the program is same as output from program in while loop.
There can be more than one statement in initialization and iteration section. They must be separated with comma.
//example program to illustrate more than one statement using the comma
// for looping
#include <stdio.h>
int main ()
{
int a, b;
for (a = 1, b = 4; a < b; a++, b--)
{
printf("a = %d \n", a);
printf("b = %d \n", b);
}
}
The output of the program is:
a = 1
b = 4
a = 2
b = 3
Here, the initialization portion sets the values of both a and b. The two comma separated statements in the iteration portion are executed each time the loop repeats.
Nested Loops
Loops can be nested as per requirement. Here is example of nesting the loops.
// nested loops
#include <stdio.h>
int main ()
{
inti, j;
for (i = 0; i< 8; i++)
{
for (j = i; j < 8; j++)
printf(".");
printf("\n");
}
}
Here, two for loops are nested. The number times inner loop iterates depends on the value of i in outer loop.
The output of the program is:
........
.......
......
.....
....
...
..
.
Reference
- Brian W. Kernighan And Dennis M. Ritchie, The C Programming Language, Prentice Hall Of India
- YashwantKanetkar, Let Us C, Bpb Publication