We all need to alter our actions in the face of changing circumstances. If the weather is fine, then I will go for a stroll. If the highway is busy, I would take a diversion. If the pitch take a
spin, we would win the match. If she says no, I would look elsewhere. If you like this content, I would write the next edition. You can notice that all these decisions depend on some conditions being met.
C language too must be able to perform different sets of actions depending on the circumstance in fact, this is what makes it worth its salt. C has three major decision-making instructions, the if statement,if-else statement, and the switch statement. A fourth,
somewhat less important structure is the one that uses a conditional operator. In this topic, we will explore all these ways(except switch, which has a separate chapter devoted to it, later)in which a C program can react to changing circumstances.
We have utilised a sequence control structure in the programmes developed in Chapter 1 in which the various phases are carried out sequentially, or in the order that they appear in the programme. In actuality, we don’t need to do anything at all in order to carry out the instructions consecutively.
A program’s instructions are often carried out in order by default. But in a serious
Rarely do we want the instructions to be executed sequentially in programming situations.
We frequently want one set of instructions to be carried out in one situation and a completely different set to be carried out in another. The C programme uses decision control instructions to handle this kind of issue. As was previously explained, a decision control command can be implemented in C using:
(a)The if statement
(b)The if-else statement
(c)The conditional operators
Now let us learn each of these and their variations in turn.
The if Statement
The decision control instructions in C are implemented using the term if, like in most other languages. The if statement has the following general form:
execute this statement if the given condition is true;
The compiler is informed that a decision control instruction is about to follow by the keyword “if.” If is always followed by a condition that is enclosed in a pair of brackets. The assertion is carried out if the condition, or whatever it may be, is true. The statement is not performed and the programme passes over it if the condition is false. But how do we translate the condition into C? And how can we determine whether it is true or false? In general, we use the’relational’ operators in C to specify a condition.
The relational operator allows us to compare two values to see whether they are equal to each other, unequal, or whether one is greater than the other. Here’s how they look and how they are evaluated in C.
The relational operators should be familiar to you except for the equality operator == and the inequality operator!=. Note that = is used for assignment, whereas, == is used for comparison of two quantities. Here is a simple program, which demonstrates the use of if and the relational operators.
Flow chart of if statement
/* Demonstration of if statement*/
#include <stdio.h> main() { int num; print ("Enter a number less than 10*); scanf ("%d", &num); if (num<10) printf ("What an obedient servant you are!");
The if-else Statement
When the expression that comes after the if statement evaluates to true, the if statement alone will execute a single statement or a collection of statements. When the expression is false, there is no effect. Can we run one set of statements in the case where the expression is true and a another set of statements in the case where it is false? Yes, of course! This is what the else statement’s intent is, as shown in the example that follows:
An employee at a corporation might be paid as follows:
If his basic pay is less than Rs. 1500, HRA will be 10% of that amount and DA will be 90% of that amount. If his basic salary is Rs. 1500 or more, HRA will be Rs. 500 and DA will be 98% of that amount. If
Flow chart of if-else Statement
/* Calculation of gross salary*/
#include<stdio.h> main() { float bs, gs, da, hra; print("Enter basic salary"); scanf ("%f", &bs); if (bs<1500) { hra=bs*10/100; da=bs*90/100; } else { hra=500; da=bs*98/100: } gs= bs+hra+da; print (*gross salary= Rs. %f", gs); }
Nested if-else
It is perfectly all right if we write an entire if-else construct within either the body of the if
statement or the body of an else statement. This is called ‘nesting’ of if. This is shown in the following program.
Flow chart of nested if-else Statement
/*A quick demo of nested is-else*/ #include<stdio.h> main() { int i; print ('Enter either 1 or 2'); scanf ("%d", &i); if (i==1) printf ("You would go to heaven!"); else { if (i==2) printf ("Hell was created with you in mind"); else printf("How about mother earth!"); } }
Keep in mind that the first else statement nested the second if-else sentence. The condition in the second if statement is only examined if the first if statement’s condition is false. If it is also untrue, the final else statement is carried out.
The programme demonstrates how every time an if-else construct is nested inside of another if-else construct, it is also indented to improve readability. Create the habit of using indentation; otherwise, you can end up developing programmes that no one can comprehend later on (even you). Note that it makes no difference whether we indent or do not indent the programme.
affect how the program’s instructions are executed.
Decisions Using Switch
The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since three keywords go together to make up the control statement. They most often appear as follows:
switch ( integer expression ) { case contact 1: do this; case contact 2: do this; case contact 3: do this; default: do this; }
The integer expression following the keywords switch is any C expression that will yield an integer value. It could be an integer constant like 1,2,3 or an expression that evaluates to an integer
What happens when we run a program containing a switch? First, the integer expression following the keywords switch is evaluated. The value it gives is then matched, one by one, against the constant value that follows the case statements. When a match is found, the
program executes the statements following that case, and all subsequent case and default
statements as well. If no match is found with any of the case statements, only the statements
following the default are executed. A few examples will show how this control structure works.
Considered the following program:
#include<stdio.h> void main() { int i=2; switch(i){ case 1: printf ("I am in case 1\n"); case 2: printf ("I am in case 2\n"); case 3: printf ("I am in case 3\n"); default: case 1: printf ("I am in default/n");
The output of this program would be:
I am in case 2 I am in case 3
I am in case default
The results are definitely not what we were hoping for! The second and third lines in the output above were unexpected. The default case, case 2, and case 3 are all printed by the programme. Okay, sure. We stated that the switch performs the default case, all following cases, and the case when a match is discovered.
A flow graphic illustrating how the switch works is provided below for your convenience.
Flow chart of the switch statement
switch Versus if-else Ladder
There are some things that you simply can not do with a switch. These are:
- A float expression cannot be tested using a switch.
- Cases can never have variable expression(for example: It is wrong to say case a+3:
- Multiple expressions can notuse the same expressions. thus the following switch is illegal:
switch(a){ case3:
…..
case1+2:
……
}
You might think that the disadvantages of a switch are obvious based on points 1, 2, and 3, especially given that if-else did not have any restrictions like these. So why even use a switch? Because speed-switch operates more quickly than an equal if-else ladder. Why is that? This is due to the jump table that the compiler creates for a switch during compilation. As a result, rather than really determining whether case is satisfied during execution, it simply consults the jump table to determine which case should be carried out. In contrast, if-else statements take longer to execute since the conditions within them must be examined.
With 10 cases, a switch would therefore be quicker than an equivalent if else ladder. The jump table is looked to and the statements for the 10th case are performed if the 10th case is satisfied. Contrarily, in an if-else
10 conditions would need to be examined at the time of execution for the ladder, which makes it sluggish. It should be noted that a jump table lookup is quicker than evaluating a condition, particularly if the condition is complex.
The if-else, on the other hand, would function more quickly than a switch’s search method if the conditions in the if-else were straightforward and few in number. A switch that has two cases will therefore operate more slowly than an equal if-else.
Flow chart of if-else ladder Statement
Summary
1. A switch statement is utilized when we need to select one amount from a range of options.
2. An integer or an expression that evaluates to an integer comes after the switch keywords.
3. A character or integer constant comes after the case keyword.
4. The control fails in every scenario unless a break statement is provided.
Helpful