[go: up one dir, main page]

0% found this document useful (0 votes)
48 views16 pages

Chapter 4

The document discusses different conditional statements in C programming including if, if-else, else-if, and nested if statements. It provides the syntax, flowcharts, pseudocode representations, and examples of each statement. The if statement executes code if a condition is true. The if-else statement executes one block of code if the condition is true and another if false. The else-if statement checks multiple conditions in a ladder-like structure. Nested if statements allow placing if/else blocks within other if/else blocks to check multiple conditions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views16 pages

Chapter 4

The document discusses different conditional statements in C programming including if, if-else, else-if, and nested if statements. It provides the syntax, flowcharts, pseudocode representations, and examples of each statement. The if statement executes code if a condition is true. The if-else statement executes one block of code if the condition is true and another if false. The else-if statement checks multiple conditions in a ladder-like structure. Nested if statements allow placing if/else blocks within other if/else blocks to check multiple conditions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

CHAPTER 4

DECISION CONTROL STATEMENTS

THE CONDITIONAL STATEMENTS

Conditional Statements are used to execute a statement or a group of statement


base on certain conditions.

We will look into following conditional statements.

1. if
2. if else
3. else if
4. switch

1) if Conditional Statement

The structure of an if statement is as follows:

True condition False

Statement 1

Statement 2

Flowchart Representation of the IF Statement

if (condition)
{
statement 1
}
Statement 2

Pseudocode Representation of the IF Statement


Here is a simple example that shows the syntax:

#include<stdio.h>
#include<conio.h>
main()
{
int a=10, b=5;

if (a>b)
printf(“a if greater”);
getch();
}

Program Algorithm/Explanation:
1. #include<stdio.h> header file is included because, the C in-built statement printf
we used in this program comes under stdio.h hearder files.
2. #include<conio.h> is used because the C in-built function getch() comes under
conio.h header files.
3. main() function is the place where C program execution begins.
4. Two variables a and b of type int is declared.
5. Variable a is assigned a value of 10 and variable b with 5.
6. A if condition is used to check whether a is greater than b. if(a>b)
7. As a is greater than b the printf inside the f{} is executed with a message “a is
greater”

Small Tip!
To have more than one statement execute after an if statement that evaluates to true,
use braces, like we did with the body of the main function. Anything inside braces is
called a compound statement, or a block. When using if statements, the code that
depends on the if statement is called the “body” of the if statement.

For example

if (true)
{
/* between the braces is the body of the if statement */
Execute all statements inside the body
}

It is recommended to always put braces following if statements. If you do this, you


never have to remember to put them in when you want more than one statement to be
executed, and you make the body of the if statement more visually clear.
2) if – else Conditional Statement

Sometimes when the condition in an if statement evaluates to false, it would be nice


to execute some code instead of the code executed when the statement evaluates
to true. The “else” statement effectively says that whatever code aster it (whether a
single line or code between brackets) is executed if the if statement is FALSE.

The structure of an if – else statement is as follows:

True False
condition

Statement 1 Statement 2

Statement 3

Flowchart Representation of the IF-ELSE Statement


if(condition)
{
statement 1
}
else
{
statement 2
3)}
statement 3

Pseudocode Representation of the if-else Statement

For example:
if(true)
{
/* Execute these statements if True */
}
else
{
/* Execute these statements if False */
}
Here are the rational operators as they are known along with examples.

> Greater than 5>4 TRUE


< Less than 4<5 TRUE
>= Greater than or equal to 4>=4 TRUE
<== Less than or equal to 3<=4 TRUE
== Equal to 5 == 5 TRUE
!= Not equal to 5!=4 TRUE

Example #1

Write a program that determines if the input age is qualified to vote or not. The qualifying
age is 18 years old above.

#include<stdio.h>
#include<conio.h>
main()
{
int age;
printf(“Enter your age”);
scanf(“%d”, &age);

if(age>=18)
printf(“You can vote”);
else
printf(“You are not eligible to vote”);
getch();

Small tip: if there is only one C statement present in IF block or ELSE block OR both then
you do not need to put the braces as shown in the example above.
Example #2:

#include<stdio.h>
#include<conio.h>
main()
{
int age;

printf(“Enter your age: ”);


scanf(“%d”, &age);

if (age>=18)
{
printf(“You can vote: ”);
printf(“Good Luck!”);
}
else
{
printf(“You are not eligible to vote: ”);
printf(“Better luck next time!”);
}
getch();

Small tip: If there is more than one C statement present in IF block or ELSE block or
BOTH then you need to put the braces as shown in the example above.
3) else – if Conditional Statement

In else if, if the condition is true the statements between IF and ELSE IF is executed.
If it is false the condition in ELSE IF is checked and if it is true, it will be executed. If
none of the conditions is true the statement under ELSE is executed.

The structure of else-if statement is as follows:

T Statement 1
Condition 1

Condition 2 T Statement 2

Condition 3 T Statement 3

Statement 4


Flowchart Representation of the ELSE-IF Statement
if(condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else if(condition n)
statement n-1;

else
statement;

Pseudocode Representation of the ELSE-IF Statement

Example #1
Write a program to assist a teacher in calculating student grades at the end of the
semester. It accepts a numerical grade as input, and then it will display the character
grade as output based on the given scale.

Range Grade
90 and above A
80-89 B
70-79 C
60-69 D
Below 60 F

Algorithm: Complete Solution

Enter grade (grade) Algorithm:


if(grade>=90) Enter grade (grade)
printf(“\n A ”); if ((grade >=90)&&(grade<=100))
else if(grade>=80) Printf(“\n A ”);
printf(“\n B ”); else if ((grade >=80)&&(grade<=89))
else if(grade>=70) Printf(“\n B ”);
printf(“\n C ”); else if ((grade >=70)&&(grade<=79))
else if(grade>=60) Printf(“\n C ”);
printf(“\n D ”); else if ((grade >=60)&&(grade<=69))
else Printf(“\n D”);
printf(“\n F ”); else if ((grade >=0)&&(grade<=59))
Printf(“\n F”);
else
printf(“Out of Rage! ”);
Solution: (Complete Codings)

#include<stdio.h>
#include<conio.h>
main()
{
int grade;

clrscr();
printf(“Enter grade: ”);
scanf(“%d”, & grade);

if ((grade >=90)&&(grade<=100))
Printf(“\n A ”);
else if ((grade >=80)&&(grade<=89))
Printf(“\n B ”);
else if ((grade >=70)&&(grade<=79))
Printf(“\n C ”);
else if ((grade >=60)&&(grade<=69))
Printf(“\n D”);
else if ((grade >=0)&&(grade<=59))
Printf(“\n F”);
else
printf(“Out of Rage! ”);
getch();
}
This solution is called the ladderized if-else-if condtional statements; where the
computer would choose only one of the given list of choice.

Example #2
...
int var1, var2;
printf(“input the value of var1: ”);
scanf(“%d”, &var1);

printf(“input the value of var2: ”);


scanf(“%d”, &var2);

if(var1!=var2)
printf(“var1 is not equal to var2”);
else if(var1>var2)
printf(“var1 is greater than var2”);
else if(var2>var1)
printf(“var2 is greater than var1”);
else
printf(“var1 is equal to var2”);

Example #3
/* program related to two integers using =, > or <

#include<stdio.h>
int main()
{
int number1, number2;

printf(“Enter two integers: ”);


scanf(“%d %d”, number1, &number2);

/*check if two integers are equal. */


if(number1==number2)
printf(“Result: %d = %d”, number1, number2);

/*check if number1 is greater than number2*/


else if(number1 > number2)
printf(“Result: %d > %d”, number1, number2);

/*check if number1 is less than number2*/


else if(number1 < number2)

return 0;
getch();
}

Sample Program Output:

Enter two integers: 12 23


Result: 12<23
Nested if and if-else statements

Description

Nested if else statement is same like if else statement. Where new block of if else
statement is defined in existing if or else block statement.

Used when user want to check more than one conditions at a time.

Syntax:

if(condition)
{
if(condition)
statement
else
statement
}
Else
{
If(condition)
statement
}
Example #1
#include<stdio.h>
#include<conio.h>
int main()
{
char username;
int password;

printf("Username: ");
scanf("%c", &username);

printf("Password: ");
scanf("%d", &password);

if(username=='a')
{
if(password==12345)
printf("Login successful");
else
printf("Password is incorrect, Try again!.");
}
else
{
if(username!='a')
printf("Username is incorrect");
if(password!=12345)
printf("\n password did not match");
}

getch();
}

The if-else statement allows a choice to be made between two possible alternatives.
Sometimes a choice must be made between more than two possibilities. For example.
The sign function in mathematics returns -1 if the argument is less than zero, returns +1
if the argument is greater than zero and returns zero if the argument is zero. The
following C statement implements this function:

if (x<0)
sign=-1;
else
if(x == 0)
sign = 0;

else
sign = 1;
This is an if-else statement in which the statement following the else is itself an if-else
statement. If x is less than zero then sign is set to -1. However if it is not less than zero
the statement following the else is executed. In that case if x is equal to zero then sign
is set to zero and otherwise it is set to 1.
The switch statement

If the condition we want to determine is a constant, i.e.. the number 1 or letter a,


then we could use the case switch statement as an alternative to the if else statement.
This is useful in instances like menus. Case Switch cannot work with ranges like in our
last homework.

General Format: switch(variable)


{
case constant1:
statement sequence
break;
case contant2:
statement sequence
break;
case contant3:
statement sequence
break;
default:
statement sequence
}
Single Expression

Flowchart Representation:

equal to Case T code block 1


Constant 1

equal to Case T code block 2


Constant 2

equal to Case T code block 3


Constant 3

F
default code
Where the default statement is executed if no matches found. The default is the
optional and it is not present, no action takes place if all matches fail. When a match is
found, the statements associated with the case are executed until the break is reached
or in the case of the default (or last case if not default is present), the end of the switch
statement is encountered.

Although break statement are generally needed inside a switch, syntactically


they are optional. They are used to terminate the statement sequence associated with
each constant. However, if the break statement is omitted, execution will continue on
into the next case’s statement until either a break or the end of the switch is reached.
Execution will start at the label that matches and continue until a break statement is
found, or switch ends.

Try the following example to understand switch statement

#include<stdio.h>
main()
{
int Grade = ‘A’;

switch(Grade)
{
case ‘A’ : printf(“Excellent \n”);
case ‘B’ : printf(“Good \n”);
case ‘C’ : printf(“OK \n”);
case ‘D’ : printf(“Mmmm … \n”);
case ‘E’ : printf(“You can do better than this \n”);
default : printf(“What is your grade anyway? \n”);
}
}

This will produce the following result:

Excellent
Good
Ok
Mmmmm…
You can do better than this
What is your grade anyway?
Using beak statement:

You can come out of the switch block if you condition is met. This can be achieved using
break statement. Try out the following example:

#include<stdio.h>
main()
{
int Grade = ‘B’;

switch (Grade)
{
case ‘A’ : printf(“Excellent \n”);
break;
case ‘B’ : printf(“Good \n”);
break;
case ‘C’ : printf(“OK \n”);
break
case ‘D’ : printf(“Mmmm … \n”);
break;
case ‘E’ : printf(“You can do better than this \n”);
break;
default : printf(“What is your grade anyway? \n”);
break;
}
}

This will produce the following result:

Good
A closer look at the Break statement

Example #1
#include<stdio.h>
main()
{
char choice;

clrscr();
printf(“What flavor do you like?”);
printf(“\n\t a) Apple”);
printf(“\n\t b) Orange”);
printf(“\n\t c) Vanilla”);
printf(“\n\t d) Mint”);
choice=getchar();
switch(choice)

{
case ‘a’ : printf(“I like apple too ”); break;
case ‘b’ : printf(“I like orange too ”); break;
case ‘c’ : printf(“I like vanilla too ”); break;
case ‘c’ : printf(“I like mint too ”); break;
default: printf(“Huh?”);
}
getchar;
}

Example #2
#include<stdio.h>
int main()
{
int num=2
switch(num+2)
{
case 1 : printf(“Case 1: Value is: %d”, num); break;
case 2 : printf(“Case 2: Value is: %d”, num); break;
case 3 : printf(“Case 3: Value is: %d”, num); break;
default : printf(“Default: Value is: %d”, num);
}
return 0;
}

Output:
Default: Value is: 2

You might also like