Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
85 views

Lecture 4 - C Conditional Statement - IF - IF Else and Nested IF Else With Example

This document provides information about conditional statements and switch statements in C programming. It includes: - An overview of if, if-else, and nested if-else conditional statements and how they allow a program to decide which code to execute based on evaluated conditions. - Details and examples of switch statements, including syntax, flow, nested switches, and default cases. Switch statements compare a value to multiple case labels and execute the associated block for a matching case. - Examples of if, if-else, and switch statements to illustrate their usage for decision making and selecting code paths in C programs.

Uploaded by

Mab Abdul
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Lecture 4 - C Conditional Statement - IF - IF Else and Nested IF Else With Example

This document provides information about conditional statements and switch statements in C programming. It includes: - An overview of if, if-else, and nested if-else conditional statements and how they allow a program to decide which code to execute based on evaluated conditions. - Details and examples of switch statements, including syntax, flow, nested switches, and default cases. Switch statements compare a value to multiple case labels and execute the associated block for a matching case. - Examples of if, if-else, and switch statements to illustrate their usage for decision making and selecting code paths in C programs.

Uploaded by

Mab Abdul
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 65

C Conditional Statement

IF, IF Else and Nested IF Else


with Example
MODULE CODE: CS 6224
MODULE NAME: Basic Computer Programming in C
FACILITATOR: Pangahela, R. A
Email: pangriz@gmail.com Phone: +255 742 926 569
In ‘C’ programming conditional statements are
possible with the help of the following two
constructs:
1. If statement

2. If-else statement
It is also called as branching as a program decides
which statement to execute based on the result of
the evaluated condition
In this tutorial, you will learn-

• What is a Conditional Statement?


• If statement
• Relational Operators
• The If-Else statement
• Nested If-else Statements
• Nested Else-if statements
The condition evaluates to either true or false. True
is always a non-zero value, and false is a value that
contains zero. Instructions can be a single
instruction or a code block enclosed by curly braces
{ }.
Following program illustrates the use of if construct
in ‘C’ programming:
#include<stdio.h>
int main()
{
int num1=1;
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
The above program illustrates the use of if construct
to check equality of two numbers.
1. In the above program, we have initialized two
variables with num1, num2 with value as 1, 2
respectively.
2. Then, we have used if with a test-expression to check
which number is the smallest and which number is
the largest. We have used a relational expression in if
construct. Since the value of num1 is smaller than
num2, the condition will evaluate to true.
3. Thus it will print the statement inside the block of If.
After that, the control will go outside of the block and
program will be terminated with a successful result.
The If-Else statement
The if-else is statement is an extended version of If. The
general form of if-else is as follows:
if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;
and this type of a construct, if the value of test-
expression is true, then the true block of statements
will be executed. If the value of test-expression if
false, then the false block of statements will be
executed. In any case, after the execution, the
control will be automatically transferred to the
statements appearing outside the block of If.
Following programs illustrate the use of the if-else
construct:
We will initialize a variable with some value and
write a program to determine if the value is less
than ten or greater than ten. Let’s start.
#include<stdio.h>
int main()
{
int num=19;
if(num<10)
{
printf("The value is less than 10");
Nested Else-if statements
Nested else-if is used when multipath decisions are
required.

The general syntax of how else-if ladders are


constructed in ‘C’ programming is as follows:
if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
} else if (test - expression n) {
Statement n;
} else {
default;
}
Statement x;
#include<stdio.h>
int main()
{
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55)
The above program prints the grade as per the
marks scored in a test. We have used the else-if
ladder construct in the above program.
Summary
•Decision making or branching statements are used to
select one path based on the result of the evaluated
expression.
•It is also called as control statements because it controls
the flow of execution of a program.
•‘C’ provides if, if-else constructs for decision-making
statements.
•We can also nest if-else within one another when multiple
paths have to be tested.
•The else-if ladder is used when we have to check various
ways based upon the result of the expression.
#include <stdio.h>
int main()
{
int A,B,ADD,SUB;
printf("Enter tfirst & second operand:");
scanf("%d %d",&A, &B);
if(A>B)
{
ADD=A+B;
printf("Since A is greater than B, so on addition A+B=
%d\n", ADD);
}
else
{
SUB=A-B;
printf("Since B is greater than A, so on Subtraction A-
B=%d\n", SUB);
}
return 0;
}
2. Write a program which prompt user to enter an
integer number so as to print “Hello, I love C
programming” only when the number is less
than 10 and display the message “This is greater
than 10” when it is otherwise {Use if-else
statement}.
3. Program to find greatest in three numbers.
4. Program to find if the given number is even or
odd
else
printf("%d is an odd integer.",number);
return 0;
}
switch…case in C (Switch Statement in C) with
Examples
What is Switch Statement in C?
Switch statement in C tests the value of a variable
and compares it with multiple cases. Once the case
match is found, a block of statements associated
with that particular case is executed.
Each case in a block of a switch has a different
name/number which is referred to as an identifier.
The value provided by the user is compared with all
the cases inside the switch block until the match is
found.
If a case match is NOT found, then the default
statement is executed, and the control goes out of the
switch block.
In this tutorial, you will learn-
•What is Switch Statement in C?
•Switch case Syntax
•Switch Statement Flowchart
•Switch case Example in C
•Nested Switch in C
•Why do we need a Switch case?
•Rules for switch statement
switch case Syntax
A general syntax of how switch-case is implemented
in a ‘C’ program is as follows:
switch( expression )
{
case value-1:
Block-1;
Break;
case value-2:
Block-2;
Break;
case value-n:
Block-n;
Break;
default:
Block-1;
Break;
}
Statement-x;
• The expression can be integer expression or a
character expression.
• Value-1, 2, n are case labels which are used to
identify each case individually. Remember that case
labels should not be same as it may create a problem
while executing a program. Suppose we have two
cases with the same label as ‘1’. Then while executing
the program, the case that appears first will be
executed even though you want the program to
execute a second case. This creates problems in the
program and does not provide the desired output.
• Case labels always end with a colon ( : ). Each of these
cases is associated with a block.
• A block is nothing but multiple statements which are
grouped for a particular case.
• Whenever the switch is executed, the value of test-
expression is compared with all the cases which we
have defined inside the switch. Suppose the test
expression contains value 4. This value is compared
with all the cases until case whose label four is found in
the program. As soon as a case is found the block of
statements associated with that particular case is
executed and control goes out of the switch.
• The break keyword in each case indicates the end of a
particular case. If we do not put the break in each case then
even though the specific case is executed, the switch in C will
continue to execute all the cases until the end is reached. This
should not happen; hence we always have to put break
keyword in each case. Break will terminate the case once it is
executed and the control will fall out of the switch.
• The default case is an optional one. Whenever the value of
test-expression is not matched with any of the cases inside the
switch, then the default will be executed. Otherwise, it is not
necessary to write default in the switch.
• Once the switch is executed the control will go to the
statement-x, and the execution of a program will continue.
Switch Statement Flowchart
Following diagram illustrates how a case is selected
in switch case:
How Switch Works
Switch Case Example in C
Following program illustrates the use of switch:

#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
}
1. In the given program we have explain initialized a
variable num with value 8.
2. A switch construct is used to compare the value
stored in variable num and execute the block of
statements associated with the matched case.
3. In this program, since the value stored in variable
num is eight, a switch will execute the case whose
case-label is 8. After executing the case, the control
will fall out of the switch and program will be
terminated with the successful result by printing
the value on the output screen.
Try changing the value of variable num and notice
the change in the output.
For example, we consider the following program
which defaults:

#include <stdio.h>
int main()
{
int language = 10;
switch (language) {
case 1:
printf("C#\n");
break;
case 2:
printf("C\n");
break;
case 3:
printf("C++\n");
break;
default:
printf("Other programming language\n");
}
}
When working with switch case in C, you group
multiple cases with unique labels. You need to
introduce a break statement in each case to branch
at the end of a switch statement.

The optional default case runs when no other


matches are made.

We consider the following switch statement:


#include <stdio.h>
int main()
{
int number=5;
switch (number)
{
case 1:
case 2:
case 3:
printf("One, Two, or Three.\n");
break;
case 4:
case 5:
case 6:
printf("Four, Five, or Six.\n");
break;
default:
printf("Greater than Six.\n");
}
return 0;
}
Program to illustrate the use of switch statement.
#include<stdio.h>
main()
{
char grade; // local variable definition
printf(“enter grade A to D: \n”);
scanf(“%c”,&grade);
switch(grade)
{
case 'A': printf("Excellent! \n ");
break;
case 'B': printf("Well done \n ");
break;
case 'C': printf("You passed \n ");
break;
case 'D': printf("Better try again\n ");
break;
default: printf("Invalid grade \n ");
return 0;
}
printf("Your grade is %c", grade);
return 0;
}
Output:
enter grade A to D:
B
Well done
Your grade is B
Why do we need a Switch case?
There is one potential problem with the if-else
statement which is the complexity of the program
increases whenever the number of alternative path
increases. If you use multiple if-else constructs in the
program, a program might become difficult to read
and understand. Sometimes it may even confuse the
developer who himself wrote the program.

The solution to this problem is the switch statement.


Rules for switch statement
• An expression must always execute to a result.
• Case labels must be constants and unique.
• Case labels must end with a colon ( : ).
• A break keyword must be present in each case.
• There can be only one default label.
• We can nest multiple switch statements.
Summary
•A switch is a decision making construct in ‘C.’
•A switch is used in a program where multiple
decisions are involved.
•A switch must contain an executable test-expression.
•Each case must include a break keyword.
•Case label must be constants and unique.
•The default is optional.
•Multiple switch statements can be nested within one
another.
Questions?

THANK YOU
FOR COMING!

You might also like