Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Conditional Statements in C - if else break continue switch (http://www.go4expert.com/articles/conditional-statements-c-break-continue-t29935/)

msfq17a 19Dec2013 08:42

Conditional Statements in C - if else break continue switch
 
Conditional statements are statements, which are executed depending on some condition being satisfied as true or false. In this tutorial, we will try to learn some conditional statements which include: If-else, switch, break and continue which controls the behaviour of loop to some extent.
  1. if else
  2. break
  3. continue
  4. switch

if else



We are going to discuss about a conditional statement "if-else" in this section in C programming. Let's forget about C programming concept for some time and go for some real life examples.

Do you watch cricket? Cricket game has a term - "century". If any player scores more than hundred runs, it is termed as he has made a century. Suppose you have just finished watching cricket. I have asked you "Did Bryan Lara make a century in today's match?" You have to remember his run and answer me. How does the decision comes in your mind? You will remember his score, and then if he has scored 100 or more runs, your answer will be "yes". Now in C programming the projection will have to be proceeded in this logical manner as your brain does.

A flow chart is given here for the demonstration of the working procedure:

http://imgs.g4estatic.com/c-conditionals/ifelse.png

The steps are as follows:
Code:

int score;
scanf("%d", &score);
if(score >= 100)
        printf("He has scored a century");

Here (score >= 100) is a conditional statement. It can be either true or false.
So, what is the generalized structure for the if statement?
Code:

if(conditional expression)
        statement;

You can decide and write multiple statements under one conditional expression.

Code:

if(conditional expression)
{
        statement 1;
        statement 2;
        .
        .
        .
        statement N;
}

For example, multiple statements under one if condition can be written like:
Code:

int score;
scanf("%d", &score);
if(score >= 100)
{
        printf("He has scored a century.");
        printf("Congratulations to him");
}

I guess if condition has been covered well. Now we can proceed to else part.

Let's move back to our first example. If century has been scored, your answer will be "yes". What would be the otherwise condition? It must be "no". The otherwise part is covered using else keyword. Here the demonstration is given:
Code:

if(score >= 100)
        printf("He has scored a century.");               
else
        printf("No, he didn't Score a century");

So far, we have considered one condition and decision making based on that condition. How to deal with it if the decision is not limited in between "yes" and "no"? May be you can decide the performance according to the score.
Code:

if(score < 20)
        printf("Poor score");
if(score < 30)
        printf("Average score");
if(score < 60)
        printf("Good score");
if(score >=60)
        printf("Excellent score");

The above example works fine, but it is novice programming. Why?

If score is 10. Then first if condition is true. So it is not required to test other if condition. But in the example above, all of four conditions are tested, while it is not required if the decision has been made.

So, we should go for optimisation. If one condition is true, we will make the decision and wouldn't check the other conditions. How can we do that?

Here comes the necessity of another keyword else if. It optimizes the decision-making procedure if there are multiple conditions. If one condition is true, the decision is made and other conditions are ignored.
Code:

if(score < 20)
        printf("Poor score");
else if(score < 30)
        printf("Average score");
else if(score < 60)
        printf("Good score");
else
        printf("Excellent score");

Sometimes, the decision is made if multiple conditions are true. For example, if a player makes fifty or more runs and takes two or more wickets, then he shows all-round performance. The example below first checks the run. If it is equal or more than fifty, then checks the wicket. If it is equal or more than two, then declares the player's performance as all-round.
Code:

int score, wicket;
scanf("%d %d", &score,&wicket);
if(score >= 50)
        if(wicket>=2)
                printf("Good all-round performance");

Another way of implementation of the above example is as follows:
Code:

if(score >= 50 && wicket >=2)
        printf("Good all-round performance");

&& is logical and operator. It checks whether two conditions before and after it is true or not.

Let's try something difficult. You have to decide a player's performance as all-round or good batting. If score is 50+, then the player is designated with good batting. And if along with that, wicket taking is 2+, then he obtains all-round performance.
Code:

if(score >= 50)
        if(wicket>=2)
                printf("All-round performance");
        else
                printf("Good batting");

There should be some confusion. For which if condition the else condition works? It works for the last if condition immediately above it.

If there are multiple if and else, then the first else works for the last if, next else works for second last if, until there are curly braces ({,}).
Code:

if(score >= 50)
        if(wicket>=2)
                printf("alround performance");
        else
                printf("good batting");
else
        printf("poor batting");

Let's go through another example for the clarification of the confusion.
Code:

if(score >= 50)
{
        if(wicket>=2)
                printf("All-round performance");
        else
                printf("Good batting");
}
else
{
        if(score < 20)
                printf("Poor batting");
        else
                printf("Avg batting");
}

I think the if else conditional statement is covered well here. But never think it is finished. Go for some practice, think about different scenario and try to implement those scenarios using if else condition.

break



The keyword tells about what it does. It breaks something. But what does it break? It breaks the execution of the loop or switch statement to which it belongs. This loop includes for loop, while loop, do while loop. Let's go for example.

Consider about the loop below. It will be traversed for 10 times and print the number-0123456789 one after another. Each time it would display one number and after traversing the loop for the subsequent time, it would display the subsequent number and proceed thereby. After traversing 10 times, it will go out from the loop and print the last line-outside loop.
Code:

for(counter = 0; counter < 10; counter++)
{
        printf("%d",counter);
}
printf("outside loop");

What if we want to break the loop before traversing 10 times? Here comes the keyword break. Let's consider we want to break the loop after 5 traverses. Then we can check the counter, if it is equal to 5, we can use break statement, to break the loop.
Code:

for(counter = 0; counter < 10; counter++)
{
        if (counter== 5)
                break;
        printf("%d",counter);
}
printf("outside loop");

What will be the output? It will be- 01234, and then break the loop. The next execution point is the line after the loop. So it prints - outside loop.

Let's go for another example. Suppose you will take input from keyboard inside a loop and print square root of the number. The loop will continue until there is a negative input. Let's use break keyword to implement it.

Code:

while(1)
{
        scanf("%f", &num);
        if(num < 0.0)
                break;
        printf("%f\n", sqrt(num));
}

continue



Like break keyword, continue also tells about its work by its name. It works almost opposite of break. It resides in a loop, bypasses the next statements of that iteration and passes control to the next iteration.

For example, suppose you are trying to print the even number from 1 to 20. You will use a for loop and increment the loop by one (1). Then how will you achieve your goal? Let's see:
Code:

for(num = 1; num <= 20; num++)
{
        if (num % 2)
                continue;
        printf("%d\t",num);
}

Let's make a counter. It will count from 20 to 0. But display will show only last ten numbers (9-0). Implementation using continue keyword goes there:
Code:

for(num = 20; num >=0 ; num--)
{
        if (num >= 10)
                continue;
        printf("%d\t",num);
}

Let's go for more descriptive example. Suppose you are playing a cricket match. You have to count total score of your team. You have to take input the score of each player and make sum of scores of each player. Team consists of eleven (11) players. Usually, you will do the operation like this:
Code:

for(player = 1; player <= 11; player++)
{
        scanf("%d", &score);
        totalScore =  totalScore + score;       
}
printf("%d",totalScore);

Every time we are taking a score and summing it with previous total score. How can we improve it using continue keyword? See, you have to do addition operation for 11 times for 11 players. But what if any player scores 0? What if many players score 0? 0 has no impact on addition operation, right? So, if three (3) of your team players score 0, you need to add the scores of other eight (8) players. But in the current implementation, we are doing it for all 11 players, including the 0 add operation.

So, we need optimization, right? We should not add 0 score to total score as it has no impact and does extra operation which cost extra cpu cycle. How can this be done? When we get a 0 score, we will ignore the addition operation and go for the next input.
Code:

for(player = 1; player <= 11; player++)
{
        scanf("%d", &score);
        if(score == 0)
                continue;
        totalScore =  totalScore + score;       
}
printf("%d",totalScore);

switch



switch is used to work with conditional statement. The goal is same as if else, but switch has some advantages over if else. Specially for large program with lots of conditions, it works much better than its counterpart. Generalization of switch statement is given below:
Code:

switch(expression)
{
        case constant1: statement1;
                break;
        case constant2: statement2;
                break;
        case constantN : statementN;
                break;
        default : statementDefault;
                break;
}

switch statement works with four different keywords, which are :
  1. switch
  2. case
  3. break
  4. default
A brief discussion for each keyword is given here:

switch

switch keyword tells the compiler that the conditional statement begins from here. There is an expression after switch closed in first bracket; depending on its value, next statement executes. But unlike the expression of the if or else if condition, it can only be a variable , not logical or relational expression.

switch(expression)
{
}


case

In every switch statement, there can be one or multiple case. The value of expression is checked here. When any match is found, the statement of that case is executed.
Code:

case constant:
        statement1;
        statement2;
        statementN;

break

Traditionally, statement(s) of every case is followed by a break keyword. It tells the compiler that execution of switch statement is over. It is not mandatory, but is a good practice.

default

Consider a situation. Let you are checking an operator value in switch. In case, you have checked (+,-*,/) value. But what would you do if you have entered an operator other than those? For example-if it is % operator, what is needed to do? You haven't handle this in any case, right? For this type of scenario, a default section is added. When there is no match with any case, default section is executed.
Code:

default :
        statement1;
        statement2;
        statementN;

A flowchart is given for demonstration:

http://imgs.g4estatic.com/c-conditio...witch-case.png

Let's go for our first example of switch. I will try to explain working procedure of switch statement step by step.

Suppose your friend has got his result of his last exam. You want to know his result and appreciate accordingly. How will you do this? You will ask his grade, measure his performance and appreciate him according to his performance. Appreciation words for different grades will be different. You have thought your words for different grades – "Excellent", "Very good", "Average", "Not good", "Sorry" for the grades "A", "B", "C", "D" and "F" respectively.

This is implemented using switch case here. Variable grade contains the grade letter. Keyword switch takes the variable and different case are written for different grade. Every statement of a case is followed by a break keyword as we want to break the loop if any case executes.
Code:

char grade;
scanf("%c",&grade);

switch(grade)
{
        case 'A' :
                printf("Excellent Result\n");
        break;
        case 'B' :
                printf("Very Good Result\n");
        break;
        case 'C' :
                printf("Average Result\n");
        break;
        case 'D' :
                printf("Not good\n");
        break;
        case 'F' :
                printf("Sorry\n");
        break;
        default :
                printf("Invalid grade\n");
        break;
}
printf("You achieved %c grade", grade);

Here, break keyword is not compulsory, but provision is suggested. It is good practice to use break after the last statement of any case.

In first example, we have seen different statements for every case. But what if different case provides same result? Will you write same statement for each case? You should not. There is an optimal way. Write the statement only once, keep blank for other case. Can't understand? Observe the example given below.
Code:

char inputChar;
scanf("%c",&inputChar);
switch(inputChar)
{
        case 'a' :
        case 'A' :
        case 'e' :
        case 'E' :
        case 'i' :
        case 'I' :
        case 'o' :
        case 'O' :
        case 'u' :
        case 'U' :
                printf("The char is a vowel\n");
        break;
        default :
                printf("It is not a vowel\n");
        break;
}

You have to tell whether the input letter is vowel or not. We know the vowels are –'a', 'e', 'i', 'o', 'u'. You have to consider both upper and lowercase. So, for ten (10) cases, it will be vowel, otherwise not. The way to write is write ten consecutive cases, keep statement blank and for the last case, write the statement.

Let's go for some more practical scenario. Make a basic calculator, which will do some basic operation like addition, subtraction, multiplication and division. You will write the expression like “a+b”, “a-b”, “a*b”, “a/b” and your program will output the result. How? In switch statement, take operator as expression ((switch(op)), in every case , check the operator(+, -, *, /), then do the operation according to the operator.
Code:

char op;
float firstNum,secondNum;
scanf("%f %c %f",&firstNum,&op,&secondNum);

switch(op)
{
        case '+':
                printf("Summation result is =%.2f",firstNum+secondNum);
        break;
        case '-':
                printf("Subtraction result is =%.2f",firstNum-secondNum);
        break;
        case '*':
                printf("Multiplication result is =%.2f",firstNum*secondNum);
        break;
        case '/':
                printf("Division result is =%.2f",firstNum/secondNum);
        break;
        default: 
                printf("Invalid operator");
        break;
}

One of the limitations of switch statement is that it takes only variable or constant as expression. To extend the usability, we can use enumeration and complete the task using switch statement. We can enumerate our weekly days starting from Monday, and then give a message according to the day. Here, enumeration begins with Monday, value starts with 1, and the other days after the Monday (Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday) automatically gets the value (2,3,4,5,6,7).
Code:

enum days {
        Monday=1, Tuesday, Wednesday,Thursday, Friday, Saturday, Sunday
} weekday;

 
int main(void)
{
        int num;
        scanf("%d", &num);
        weekday=num;
        switch (weekday)
        {
        case Monday:
                printf("It is Monday. Your first weekday.\n");
        break;
        case Tuesday:
                printf("You are in your second weekday.\n");
        break;
        case Wednesday:
                printf("Already passed two weekday.\n");
        break;
        case Thursday:
                printf("Hi, weekend is almost there, it is thursday.\n");
        break;
        case Friday:
                printf("Congrats.You are going to enjoy your weekend from evening.\n");
        break;
        case Saturday:
                printf("Lazy satday. Wanna go out?\n");
        break;
        case Sunday:
                printf("Enjoy the last holiday.\n");
        break;
        default:
                printf("C'est le mauvais jour.\n");
        }
        return(0);
}

There are some advantages and disadvantages of switch statement over multiple if else statement. Let’s have a look on it:

Advantages:
  • It is more descriptive
  • It saves CPU cycles.
  • It enhances readability
Disadvantages:
  • Only fixed values can be tested, logical operation (<, >, >/) or relational operation can’t be.
  • Only one variable can be used as parameter for the switch statement, whereas nested ‘if statement’ allow several conditions with different parameter.
So far, we have tried to learn how conditional statements work in C language. Actually in every language these control statements work in same way, the difference is in the syntax. Hopefully, this discussion was helpful for you.


All times are GMT +5.5. The time now is 14:08.