Anda di halaman 1dari 55

Control Structure

Objective
Learn about control structures
Discover how to use the selection control
structures if, if...else, and switch in a
program

1/14/15

Ms. Nirmala Shinde KJSCE

Exercise
int a = 10, b, c; a is initialized to 10.
c = b = a;
a value is assigned to c and b(i.e.
b -= a--;
10)
c -= --a;

Written as b = b a then a is
decremented (b = 10-10, a=9)

a -= --a a--;

1st value of a is decremented then


c=c-a (a=8, c=10-8)

1st value of a is decremented (7)


then a = a-aa (7-7-7)finally a is
Output: a=6, b=0,
decremented (6)
c=2

Exercise
int k=3,l=4,m,n;
Assigned value of k is 3 and l is 4
m = ++k + l--;
1st k value is incremented (4)then m = k + l
(m=4+4) finally l value is decremented (3)
n = k++ + --l;
1st l value is decremented (2)then n = k + l
(n=4+2) finally k value is incremented (5)
Output: m= 8,n=6 ,k=5 ,l=2

Exercise
void main()
{
int x = 10, y = 5, p,q;
p = x > 9;
q = x > 3 && y != 3;
printf(\n p =%d q=%d,p,q);
}
Output: p = 1,q = 1

Exercise
void main()
{
int a = 5, b = 2, c = 7, d = 3, e = 13,f;
f = a * b c % d + e;
printf(The value of F is %d,f);
}
Output: F = 22

Exercise
void main()
{
int a = 2, b = 3;
char ch = 'C';
printf("%c \t %c \n",ch,++ch);
printf("%d\t%d\n",a,a++);
printf("%d\t%d\t%d\n",b,b,++b);
printf("%d\t%d\n",a,!(a>5));
}
Output: D D
3 2
4 4 4
3 1

Exercise
/*Find the given no. is even or odd using conditional/ternary operator.*/
#include<stdio.h>
void main ()
{
int num;
printf ("Enter the value : ");
scanf ("%d", &num);
num%2==0?printf("Even"):printf("Odd");
}
Output:
Enter the value : 4
Even

Control Structures in C
Control structures control the flow of execution in a program
or function.
There are three kinds of execution flow:
Sequence:
the execution of the program is sequential.

Selection/branching:
A control structure which chooses alternative to execute.

Repetition/iterative:
A control structure which repeats a group of statements.

Some statements are executed only if certain conditions are met


A condition is represented by a logical (Boolean) expression that
can be true or false
A condition is met if it evaluates to true

Sequential : Convert Temperature in


Celsius to Fahrenheit
Algorithm

Step 1: Start
Step 2: Read the value of temperature in
centigrade. Store the value in C
Step 3: Calculate the temperature
F = 32+ (9*C/5)
Step 4: Display value of F
Step 5: Stop

Sequential : Convert Temperature in


Celsius to Fahrenheit
Flowchart

/*To convert Celsius to Fahrenheit.*/


#include<stdio.h>
void main ()
{
float C, F;
printf ("Enter the value of Temperature in Celsius: ");
scanf ("%f", &C);
F = 32 + (9*C/5); //1.8 * C:
printf ("The value of Temperature in Fahrenheit is: %f", F);
}
Output:
Enter the value of Temperature in Celsius: 10
The value of Temperature in Fahrenheit is : 50.000000

Selection/Branching Statement
We can alter the flow of control(the order in which
statements are executed)using selection
structures.
Selection structures can be translated into C using
if statements.
Four forms of selection structures will be looked at:
One-Way
Two-Way
Nested
Switch

if statement : One Way


Selection
The syntax of one-way selection is:
if (expression/condition)
statement
statement is executed only if the value of
expression/condition is true
Expression/condition is usually a logical

expression.
if is a reserved word
statement must be a single C statement.

Cont
Flowchart

Algorithm
Find the given number is positive.
Step 1: Start
Step 2: Read the number. Store the value in
num.
Step 3: if num greater than zero then
Display Number is positive
Step 4: Stop

Flowchart

Example
/*Find the given number is positive.*/
#include<stdio.h>
void main ()
{
int num;
printf ("Enter the value : ");
scanf ("%d", &num);
if(num>0)
printf (Number is positive");
}
Output:
Enter the value: 5
Number is positive

If-else statement : Two-Way


Selection
Two-way selection takes the form:
if (expression/condition)
statement1
else
statement2

If expression/condition is true, statement1 is


executed. Otherwise, statement2 is executed
else is a reserved word
statement1 and statement2 must both be
single C statements.

Cont
Flowchart

Example
Find the given number is positive/negative.
Algorithm:
Step 1: Start
Step 2: Read the number. Store the value in num.
Step 3: if num greater than zero then
Display Number is positive
else
display Number is negative
Step 4: Stop

Example
Flowchart

Example
/*Find the given number is positive. Or negative*/
#include<stdio.h>
void main ()
{
int num;
printf ("Enter the value : ");
scanf ("%d", &num);
if(num>0)
printf (Number is positive");
else
printf(Number is negative);
}
Output:
Enter the value: 5
Number is positive

Leap Year
http://www.timeanddate.com/date/leapyear.html
Why do we need Leap Years?
Leap Years are needed to keep our calendar in alignment with the Earth's revolutions
around the sun. It takes the Earth approximately 365.242199 days or 365 days, 5
hours, 48 minutes, and 46 seconds (a tropical year) to circle once around the Sun.
However, the Gregorian calendar has only 365 days in a year, so if we didn't add a
day on February 29 nearly every 4 years, we would lose almost six hours off our
calendar every year. After only 100 years, our calendar would be off by approximately
24 days!

Which Years are Leap Years?


In the Gregorian calendar following criteria must be taken into account to
identify
leap years:
The year is called leap year if year is divisible by 400.
For example: 1600and2000are leap years, while1500, and 1700are NOT leap years.
If year is not divisible by 400 as well as 100 but it is divisible by 4 then that year are
also leap year.
For example: 2004, 2008, 1012 are leap year.

Example
To find out whether a given year is a leap year/not.
Year is said to be a leap year if it is
Divisible by 4 and not divisible by 100
(year % 4 == 0 && year % 100 != 0). A
Divisible by 400 . B

year % 400 == 0
A OR B

( (year % 4 == 0 && year % 100 != 0) || year


% 400 == 0 )

Exercise
Write a program to find the given number
is even or odd.
Write a program to find the largest of the
given two numbers.
Write a program to determine a students
final grade and indicate whether it is
passing or failing. The final grade is
calculated
as the average
of four marks.
Average
Grade
>=50

Pass

<50

Fail

Nested if-else statement


Consider the syntax of a one-way if statement:
if (expression)
statement
You might ask: Could statement be another if
statement?
Example:
if (weight > 100)
if (weight <= 1000)
price = 0.20 * weight;
What does it mean?

Nested if-else statement


It is always legal in C programming tonestedif-else statements,
which means you can use one if or else if statement inside another
if or else if statement(s).
E.g.
if(road_status == S)
{
If(temp > 0)
printf(Wet roads ahead.);
else
printf(Icy roads ahead.);

}
else
printf(Drive carefully);

Cont
Flowchart

Exercise
Determine the interestRate depending on
the value of the balance.
Balance Amount

InterestRate

Greater than 50000

0.07

Greater than equal to


25000

0.05

Greater than equal to


1000

0.03

Otherwise

#include<stdio.h>
void main ()
{
float balance,interestRate;
printf ("Enter the balance amount : ");
scanf ("%f", &balance);
if(balance > 50000.00)
interestRate = 0.07;
else
if(balance >= 25000.00)
interestRate = 0.05;
else
if(balance >= 1000.00)
interestRate = 0.03;
else
interestRate = 0.00;
printf("Amount = %f Interest Rate = %f",balance,interestRate);
}

Exercise
Find the biggest of three numbers.
#include<stdio.h>
void main ()
{
int num1,num2,num3;
printf ("Enter three numbers: ");
scanf ("%d%d%d", &num1,&num2,&num3);
if( num1 >= num2)
{
if(num1 >= num3)
printf(" % d is biggest ",num1);
else
printf(" %d is biggest ", num3);
}
else
{
if( num2 >= num3)
printf("%d is biggest", num2);
else
printf("%d is biggest", num3);
}
}

else-if Ladder
If there are multiple alternative, then use the else-if ladder
syntax:
Syntax:
if (condition1)
statement1
else if (condition2)
statement2

else if (conditionn)
statementn
else
statemente

Exercise
Find the given number is positive ,negative or zero.

#include<stdio.h>
void main ()
{
int num;
printf ("Enter the value : ");
scanf ("%d", &num);
if(num>0)
printf (Number is positive");
else if(num < 0)
printf(Number is negative);
else
printf(Number is zero.);
}
Output:
Enter the value: 5
Number is positive

Exercise
Determine the interestRate depending on
the value of the balance.
Balance Amount

InterestRate

Greater than 50000

0.07

Greater than equal to


25000

0.05

Greater than equal to


1000

0.03

Otherwise

#include<stdio.h>
void main ()
{
float balance,interestRate;
printf ("Enter the balance amount : ");
scanf ("%f", &balance);
if(balance > 50000.00)
interestRate = 0.07;
else if(balance >= 25000.00)
interestRate = 0.05;
else if(balance >= 1000.00)
interestRate = 0.03;
else
interestRate = 0.00;
printf("Amount = %f Interest Rate =
%f",balance,interestRate);
}

Exercise
Big Bazzar gives festival discount on purchase
of their products in the following percentages
i.If purchase amount < 1000 than 5% discount
ii.If purchase amount >=1000 than but <3000 then 10%
discount
iii.If purchase amount >=3000 but <5000 then 12%
discount
iv.If purchase amount > 5000 then 15% discount

Switch statement
The switch statement is used to select one of several alternatives when
the selection is based on the value of a single variable or an
expression.
Expression may be of type int or char, but not of type double or string.
Syntax:
switch (expression)
{
case label1:
statement1
break;
case label2:
statement2
break;

case labeln:
statementn
break;
default:
statementd;
}

If the result of this controlling expression matches


label1, execute staement1 and then break this
switch block.

If the result matches none of all labels, execute the


default statementd.

Cont
Flowchart
case label1

true

statement1

break

statement2

break

statementn

break

false

case label2

true

false
.
.
.

case

labeln
false

default statementd

true

Exercise
Output the days of the week
#include<stdio.h>
void main()
{
int day;
printf("Enter the day number:");
scanf("%d",&day);
switch(day)
{
case 1:
printf("Sunday");
case 2:
printf("Monday");
case 3:
printf("Tuesday");
case 4:
printf("Wednesday");
}
}

Cont
Output:
Enter the day number: 3
TuesdayWednesday
Enter the day number: 4
Wednesday

With Break Statement :Output the days of the week


#include<stdio.h>
void main()
{
int day;
printf("Enter the day number:");
scanf("%d",&day);
switch(day)
{
case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednesday");
break;
}
}

Cont
Output:
Enter the day number: 3
Tuesday
Enter the day number: 5

With Default Case: Output the days of the week

#include<stdio.h>
void main()
{
int day;
printf("Enter the day number:");
scanf("%d",&day);

switch(day)
{
case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednesday");
break;
default:
printf("Invaild day number.");
break;
}
}

Cont
Output:
Enter the day number: 3
Tuesday
Enter the day number: 5
Invaild day number.

Exercise
Class ID

Ship Class

B or b

Battleship

C or c

Cruiser

D or d

Destroyer

F or f

Frigate
4-47

FExample of a switch Statement


with char Case Labels

4-48

Exercise
Display number of days in a month
using Switch Statement
Input : Read month number and year.
Output : Display days in a month as 30, 31,
28/29.

Cont
Output
Month No: 2
Enter the year: 2000
Month have 29 days.

Exercise
Check whether a character entered by the
user is a vowel or not.
Input : Read the character.
Processing : a,e,i,o,u characters are vowels.
Output : Display entered character is vowel
or not

Exercise
Write a program to carry out the
arithmetic operations addition,
subtraction, multiplication and division
using switch statement.
Input : Read the two numbers and operator.
Processing : Perform the +,-,/,* operation.
Output : Display the result.

Exercise
Write a menu driven program to carry out
the arithmetic operations addition,
subtraction, multiplication and division
using switch statement
Input :
1. Display Menu (1. Addition, 2.
Subtraction..etc)
2. Read the option and read the numbers.

Processing : Perform the +,-,/,* operation.


Output : Display Result.

Comparison of Nested if Statements


and The switch Statement
Nested if statement
more general to implement any multiplealternative decision

switch statement
syntax display is more readable in many contexts
each label set contains a reasonable number of
case labels (maximum of ten)
default label will help you to consider what will
happen if the value falls outside your set of case
label values

4-55

Anda mungkin juga menyukai