You are on page 1of 47

Selection Statements


Topic 3
Definition of selection statement


 Selection statement execute a set of instructions only
one. Select between one statement or another
 Selection depending on condition is satisfied.
 There are three kind of selection structure
 If
 If—else
 Switch..case
A control statement is a statement that determines whether other
statements will be executed. It also know as decision making
statement. In these statements one group of statement depending on
the result of decisions. The result may be in the form of two
Expressions in True or False.
Selection statements are used to perform ‘decision making‘ and then
branch the program flow based on the outcome of decision making


There are three types of control statement available in C :
1) Sequence structure (straight line paths)
2) Selection structure (one or many branches) such as if, if-else,
nested if, if-if-else, if-else-if and switch-case-break.
3) Repetition(Loop) e repetition of a set of activities such as for,
while and do-while.)
Types of control statements :-


1. if statement
2. if- Else statement
3. nested if statement
4. switch statement
(a) if statement
decides whether to execute another statement, or

decides which of two statements to execute.

(b) if-else Statement


This is used to decide whether to do something at a
special point, or to decide between two courses of
action . If and If Else statements are 2 way branching
statements
(c ) nested if-else Statement
One property of if –else statement is that they can be
nested
(d) switch statement decides which of several statements to
execute. Switch is a multi branching statement
Selection statement

Is a control statement that allows choosing
between two or more execution paths in a
program.
Most modern programming languages include
one-way, two-way and n-way (multiple)
selectors
a) if statement with no else is a one-way selector
b) if-else statement is a two-way selector
c) switch or case statement is an n-way selector
(a)The IF statement

 One way decision the statement.
 This is the most simple form of the branching
statements.
 If statement allows decision to be made by evaluating a
given expression as true or false.
The expression must be
Syntax: if(expression) placed in parentheses.

{
statement block
The state
ment wil
express l b e e xe
ion has cuted on
The state a nonzero ly if the
ment ca value –
} compou
Often co
nd.
n be eith tr
er simple e,
u
or
mp
include o ound statemen
ther con t which m
trol state ay
ments
condition
OPERATOR

MEANING EXAMPLE
== Equal to a==10
!= Not equal to Flag != DONE
< Less than a<b
<= Less than or equal to <=20
> Greater than pointer>end_of_list
>= Greater than or equal Lap>=start
to
Logical Task
 Starting from the most basic if syntax,
if (expression)
statement;
next_statement;


1. (expression) is evaluated.
2. If TRUE (non-zero) the statement is executed.
3. If FALSE (zero) the next_statement following the if
statement is executed.
4. So, during the execution, based on some condition, some
codes were skipped.
Flowchart of IF

Flow chart for if

Example 1 : IF Statement

 The answers:
#include <stdio.h>
main ()
{ int age, yrs;
printf("Type in your age: ");
scanf ("%d", &age);

if (age < 18)


{ printf ("You cannot vote yet\n");
yrs = 18 - age;
printf("You can vote in %d years.\n", yrs);
}
if (age > 18)
{ printf ("You can vote now.\n");
}
return 0;
}
(b) The IF –ELSE statement

 Two-way decision using the IF-ELSE statement
 Pseudocode of IF –ELSE structure
syntax
if(expression)
statement 1
else
statement 2
Flowchart of IF-ELSE

False
(zero)
True (!
zero)
Example 1 : IF…Else
# include <stdio.h>
main()
{
int yrs, age; The answers :
printf("Type a age: ");
scanf("%d", &age);
if (age < 18)
{ printf("You cannot vote yet\n");
yrs = 18 - age;
printf("You can vote in %d years. \n", yrs);
}
else
{
printf("You can vote now.\n", yrs);
}

return 0;
}
(c) Nested if...else statement

 Nested if else statements are used when a series of
decision are involved
 Nested if...else statement (if...else if....else Statement)
 The nested if...else statement is used when program
requires more than one test expression.
Syntax of nested if...else statement.

if (expression1)
{

statement \\ be executed if test expression1 is true;
}
else if(expression2)
{
statement \\ to be executed if test expression1 is false and 2 is true;
}
else if (expression 3)
{
statement \\ to be executed if text expression1 and 2 are false and 3
is true;
}
. . . Else
{
Flowchart of nested IF-
ELSE

Example Program : Nested If

#include<stdio.h>
The answers :
main()
{
int number;
printf("Type a number:");
scanf("%d", &number);
if(number>100)
printf("Large\n");
else if (number>0) 
printf("Not large but positive\n");
else if (number==0)
printf("or zero\n");
else
printf("Negative \n");

return 0;
}
 In this nested form, condition_1 is evaluated. If it is zero (FALSE),
statement_1 is executed and the entire nested if statement is
terminated.
 If non-zero (TRUE), control goes to the second if (within the first if)
and condition_2 is evaluated.
 If it is zero (FALSE), statement_2 is executed; if not, control goes


to the third if (within the second if) and condition_3 is evaluated.
 If it is zero (FALSE), statement_3 is executed; if not,
statement_4 is executed. The statement_4 (inner most) will only
be executed if all the if statement are TRUE.
 Again, only one of the statements is executed other will be skipped.
 If the else is used together with if, always match an else with the
nearest if before the else.
 statements_x can be a block of codes and must be put in curly
braces.
(d) SWITCH statement

 Switch is a multi branching control statement.
 Used for multiple way selections that will branch
into different code segments based on the value of a
variable or expression.
 This expression or variable must be of integer data
type.
 Syntax for switch statement is shown below.
 Break- it is used to exit from a loop or switch
Flow chart for
Switch case statement


 The switch constructs has the following form:

switch(condition)
{
case 1 : statement(s);
break;
case 2 : statement(s);
break;

case 3 : statement(s);
break;


case n : statement(s);
break;

default : statement(s);
}
next_statement;
switch-case-break

 The most flexible selection program control.


 Enables the program to execute different statements

based on an condition or expression that can have more
than two values.
 Also called multiple choice statements.
 The if statement were limited to evaluating an expression
that could have only two logical values: TRUE or FALSE.
 If more than two values, have to use nested if.
 Used together with case and break.
 Evaluates the (condition) and compares its value with the
templates following each case label.
 If a match is found between (condition) and one of the
templates, execution is transferred to the statement(s) that
follows the case label.
 If no match is found, execution is transferred to the



statement(s) following the optional default label.
If no match is found and there is no default label, execution
passes to the first statement following the switch statement
closing brace which is the next_statement.
 To ensure that only the statements associated with the
matching template are executed, include a break keyword
where needed, which terminates the entire switch statement.
 The statement(s) can be a block of code in curly braces.
Example Program : Switch …Case
#include<stdio.h>
main()
{
char ch;
printf("\n Enter character A, B or C: ");
ch=getchar(); Some of the answers:
switch(ch)
{
case 'A':
printf("You Entered A");
break;

case 'B':
printf("You Entered B");
break;

case 'C':
printf("You Entered C");
break;

default:
printf("You Did Not Entered A, B or C!\n");
}

return 0;
}
3.2.1The differences between nested if and
switch

 The switch-case permits the execution of more than one


alternatives (by not placing break) whereas the if statement does
not. In other words, alternatives in an if statement are mutually
exclusive whereas they may or may not be in the case of a switch-
case.


A switch can only perform equality tests involving integer (or
character) constants, whereas the if statement allows more general
comparison involving other data types as well.

 When there are more than 3 or 4 conditions, use the


switch-case-break statement rather than a long nested
if statement.
 When there are multiple options to choose from.
 When test condition only use integer (or character) constants.
3.4 Input Output
Operations

Output scanf( ) : get( )
• In any programming language input means to feed some
data into program. This can be given in the form of file or
from command line. C programming language provides a
set of built-in functions to read given input and feed it to
the program as per requirement.

Input printf( ) : put( )

• In any programming language output means to display


some data on screen, printer or in any file. C programming
language provides a set of built-in functions to output
required data.

3.2.5 printf() function
#include <stdio.h>
main()
{
int no_bulat = 5;
char perkataan[] = "rempit";

char huruf = 's';
float PI = 3.14;

printf("Welcome to C programming\n");
printf("%d %s %c %f is the output.\n", no_bulat, perkataan, huruf, PI);

return 0;
}

Output:
Welcome to C programming
5 rempit s 3.140000 is the output.

In the program statement above:


"%d %s %c %f is the output.\n" is the control string
no_bulat, perkataan, huruf, PI is the variable to be printed










3.2.5 printf Control String Conversion Characters
 A table of the control characters used in printf statements is given
below:
Character Form of output Expected argument type

c character  int
d or i decimal integer int
x hexadecimal integer int
o octal integer int
u unsigned integer int
e scientific notation floating double
point
f “normal” notation floating double
point
g e or f format, whichever is double
shorter
s string pointer to char
p address format (depends on pointer
system)
3.2.5 Character Escape Sequences
 There are several character escape sequences which can be used in place of a
character constant or within a string. They are:

Escape sequence  Meaning


\a Alert (bell)
\b Backspace
\f Formfeed
\n Newline
\r Carriage return
\t Tab
\v Vertical tab
\\ Backslash
\? Question mark
\’ Quote
\” Double quote
\ooo character specified as an octal number
\xhh character specified in hexadecimal
3.2.5 Other output
function : puts
 The puts() function is a very simple way to send a string to the

screen when you have no placeholders to be concerned about. It
works very much like the printf() function we saw the “Welcome to
C programming" example:
#include <stdio.h>
main()
{

puts("Welcome to C programming.");

return 0;
}

Output:
Welcome to C programming.
3.2.5 scanf() function
#include <stdio.h>
main()
{
int t_lahir, t_semasa, umur; 
printf("Please enter your birth year :");
scanf("%d", &t_lahir);

printf("Please enter the present year :");


scanf("%d", &t_semasa);

umur=t_semasa-t_lahir;
printf("\nYour age is %d year old in year %d",umur, t_semasa);
return 0;
}

Output:
Please enter your birth year : 1990
Please enter the present year : 2011

Your age is 21 year old in year 2011


scanf Control String Conversion
Characters
 scanf uses the same conversion characters as printf .
 The arguments to scanf must be pointers (addresses), hence the need for the
& character above. The arguments to scanf must be pointers (addresses),

Character Form of output



hence the need for the & character above.
Expected argument type
c character pointer to char
d decimal integer pointer to int
x hexadecimal integer pointer to int
o octal integer pointer to int
u unsigned integer pointer to int
i integer pointer to int
e floating point number pointer to float
f floating point number pointer to float
g floating point number pointer to float
s string pointer to char
p address format , depends
DTK, JKE, PTSBon
(V 10.12) Pointer to void
system
Other input function :
gets
 gets is a function in the C standard library, declared in


the header file stdio.h, that reads a line from the standard
input and stores it in a buffer provided by the caller. Use
of gets
#include is strongly discouraged.
<stdio.h>
main()
{

char nama[20];
puts("Please insert your name.");
gets(nama);

printf("\nYour name is %s", nama);

return 0;
}

Output:
Please insert your name.
Ana Rafali

Your name is Ana Rafali


The End

You might also like