Sunteți pe pagina 1din 8

Introduction

Control Structure - Specifies the sequence of execution


of a group of statements.

Three types of control structure:


1. Sequential
Control Structures 2. Conditional
3. Repeating (loop)

/ccsrac 2

Sequential Control Structure Conditional Control Structures


• Statements are executed one after the Analyze the following first!
other as they appear in the source code.
Scenario 1:
Example:
a = 1; /* first statement */ If it rains tomorrow, then I won’t go out; I’ll just stay
b = 2; /* second statement */ home and study. Otherwise, I’ll go out on a date.
c = a + b; /*third statement */

/ccsrac 3 /ccsrac 4

Conditional Control Structure


Scenario 2:
You are at the South gate going to the Gokongwei
building. There are several paths to take. Which is
the best path?
W.
Activity MM
SPS Admin Center Shaw

Aristo SJ Miguel What is common


Amphi

Accounting Field Z2 to the two


Registrar

Velasco
Aquarium Gokongwei scenarios?
Mezz-1

Admission Conserv

N. Gate Eng.
Gate
S. Gate Simplified Map
S-N
Gate of DLSU
/ccsrac 5 /ccsrac 6

1
Conditional Control Structure Conditional Control Structure
• A conditional control structure is
organized in such a way that there is always a
condition that has to be evaluated first. Two basic conditional control structures:
1. if statement (including if-else statement)
• The condition will either evaluate to a true or false. 2. switch statement

• The result of the condition will then dictate the course


of action to be taken.

• The conditional control structure allows the program


to make choices depending on a condition.

/ccsrac 7 /ccsrac 8

The if statement Examples


Write a program that will allow the user
Format: to input an integer value. If the value is
greater than or equal to zero, print the word POSITIVE.
if( <expression> )
<statement> /* sample program to determine whether an input
expression integer is a positive number */
#include <stdio.h>
False
True main()
The expression is first evaluated. {
int n;
If it’s true, the <statement> will statement
be executed; otherwise, control printf(“Input an integer value n: ”);
will proceed with the statement scanf(“%d”, &n);
following the if. After if (n >= 0)
if statement printf(“n = %d is POSITIVE\n”, n);
}
/ccsrac 9 /ccsrac 10

Examples The if statement


Write a program to input two integers. For multiple statements, use { } for grouping.
Thereafter, the program should determine if
these two numbers are equivalent. If they are equivalent,
print the word EQUIVALENT. Example:
if (nGrade >= 90)
/* sample program to determine whether 2 integers are
equivalent */
{
#include <stdio.h> printf (“Very Good!”);
main() printf (“Very Intelligent! Keep it up!”);
{
}
int nFirst, nSecond;

What will happen if the grouping


printf(“Input 2 integers: ”);
symbols were removed?
scanf(“%d%d”, &nFirst, &nSecond);
if (nFirst == nSecond)
printf(“EQUIVALENT!”);
}
/ccsrac 11 /ccsrac 12

2
Exercises Exercises
1. Write a program that displays the word 2. Modify your answer in number 1 such that
EVEN if the number entered by the user is even. when the number entered is not even,
the program will display the word ODD.

/ccsrac 13 /ccsrac 14

Exercises The if statement


3. Write a program that asks for the height of a
person. The program displays the messages
Format:
“Height is ok.” and “Have fun on the Enterprise.” when the
height is at least 4.5 feet. if( <expression> )
False
<statement1> expression
[ else
<statement2> ] True

The expression is evaluated. statement1 statement2

If it’s true, the <statement1> will


be executed; otherwise,
After
<statement2> will be evaluated.
if statement

/ccsrac 15 /ccsrac 16

Examples Examples
/* sample program that determines if a /* sample program that determines if
person can ride the Enterprise or not */ entered number is EVEN or NOT*/
#include <stdio.h>
#include <stdio.h>
main()
{ main()
float fHeight; {
int nNumber;
printf(“Enter Height> ”);
scanf(“%f”, &fHeight);
printf(“Enter Number> ”);
if (fHeight >= 4.5)
{ scanf(“%d”, &nNumber);
printf(“Height is OK.\n”); if (nNumber % 2 == 0)
printf(“Have fun on the Enterprise”); printf(“Number = %d is EVEN”, nNumber);
} else
else
printf(“Number = %d is ODD”, nNumber);
printf(“Sorry, you’re too short ”);
} }
/ccsrac 17 /ccsrac 18

3
Exercises Exercises
4. Write a program to input two integers. 5. Write a program that will allow the user to
Thereafter, the program should determine input an integer value. If the value is greater
if these two numbers are equivalent. If they are than zero, display the word POSITIVE. If the value is
equivalent, print the word EQUIVALENT; otherwise, negative, then display the word NEGATIVE. If the
display NOT EQUIVALENT. value is zero, display the word ZERO.

/ccsrac 19 /ccsrac 20

Watch your braces! Let’s Trace!


main()
Expected Output: Source Code:
{ double x;
Enter n: 3 if (n != 0) printf(“Enter a value: ”);
if (n > 0) scanf(“%lf”, &x);
POSITIVE What’s the screen output if:
printf(“POSITIVE”); if (x >= 0 && x <= 100)
end a) x = 90.1 d) x = 67.7
else if (x > 95)
printf(“A+\n”); b) x = 80 e) x = -10
printf(“ZERO”); else if (x >= 70) c) x = 70
Enter n: 0 printf(“end”); if (x >= 80)
ZERO if (x >= 90)
end Correct Code: printf(“A\n”);
else if (x >= 85)
if (n != 0)
printf(“B+\n”);
{ if (n > 0) else printf(“B\n”);
printf(“POSITIVE”); else if (x >= 75)
} printf(“C+\n”);
else else printf(“C\n”);
else printf(“D\n”);
printf(“ZERO”); else printf(“You\’re playing hard to get!!!\n”);
printf(“end”); }
/ccsrac 21 /ccsrac 22

Common Programming Errors Exercises


main() 6. Write a program which will ask for two
{ integers and determines which value is smaller.
: The program should print ‘FIRST NUMBER IS
SMALLER” if the first integer is indeed smaller than
if n > 1 the second. If the second number is smaller it should
printf(“Greater than 1”); print ‘SECOND NUMBER IS SMALLER.’ If the two
if (n = 1) then numbers are equivalent, print the word ‘TWO
printf(“Equals 1”); NUMBERS ARE EQUIVALENT’.
if (n < 1);
printf(“Less than 1”);
}

/ccsrac 23 /ccsrac 24

4
Exercises Exercises
7. You were hired by PAGCOR as part of a 8. In temperate countries like Japan, there
programming team in-charge of automating its are four seasons. April to June is spring,
BINGO game. Your task is to write a program that will July to September is summer, October to December
accept an integer whose value is 1 to 75. Thereafter, is autumn and January to March is winter. We wish
your program should determine and print the letter to write a program that allows the user to input month
that corresponds to that number. That is, the in its numeric equivalent (i.e., January is 1, February
numbers from 1 to 15 correspond to ‘B’, 16 to 30 is to 2 and so on...).
correspond to ‘I’, 31 to 45 correspond to ‘N’ , 46 to 60
correspond to ‘G’ and 61 to 75 correspond to ‘O’. The output of the program is the season associated
with that month. An example session is as follows:
Input month: 5
It is spring.
Have a nice day.

/ccsrac 25 /ccsrac 26

Answer to number 8 Answer to number 8


/* Program that gives season, given the if (nMonth == 3)
numeric month */ {
#include <stdio.h> printf(“It is winter.\n”);
main() printf(“Have a nice day.”);
{ }
int nMonth; if (nMonth == 4)
{
printf(“Input month: ”); printf(“It is spring.\n”);
scanf(“%d”, &nMonth); printf(“Have a nice day.”);
if (nMonth == 1) }
{ if (nMonth == 5)
printf(“It is winter.\n”); {
printf(“Have a nice day.”); printf(“It is spring.\n”);
printf(“Have a nice day.”);
}
}
if (nMonth == 2)
if (nMonth == 6)
{
{
printf(“It is winter.\n”); printf(“It is spring.\n”);
printf(“Have a nice day.”); printf(“Have a nice day.”);
} }
/ccsrac 27 /ccsrac 28

Answer to number 8 Answer to number 8


if (nMonth == 7) if (nMonth == 10)
{ {
printf(“It is summer.\n”); printf(“It is autumn.\n”);
printf(“Have a nice day.”); printf(“Have a nice day.”);
} }
if (nMonth == 8) if (nMonth == 11)
{ {
printf(“It is summer.\n”); printf(“It is autumn.\n”);
printf(“Have a nice day.”); printf(“Have a nice day.”);
} }
if (nMonth == 9) if (nMonth == 12)
{ {
printf(“It is summer.\n”); printf(“It is autumn.\n”);
printf(“Have a nice day.”); printf(“Have a nice day.”);
} }
}

/ccsrac 29 /ccsrac 30

5
Another answer Still another answer
/* Program that gives season, given the /* Program that gives season, given the
numeric month */ numeric month */
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int nMonth; int nMonth;

printf(“Input month: ”); printf(“Input month: ”);


scanf(“%d”, &nMonth); scanf(“%d”, &nMonth);
if (nMonth == 1 || nMonth == 2 || nMonth == 3) if (nMonth >= 1 && nMonth <= 3)
printf(“It is winter.\n”); printf(“It is winter.\n”);
if (nMonth == 4 || nMonth == 5 || nMonth == 6) else if (nMonth >= 4 && nMonth <= 6)
printf(“It is spring.\n”); printf(“It is spring.\n”);
if (nMonth == 7 || nMonth == 8 || nMonth == 9) else if (nMonth >= 7 && nMonth <= 9)
printf(“It is summer.\n”); printf(“It is summer.\n”);
if (nMonth == 10 || nMonth == 11 || nMonth == 12) else if (nMonth >= 10 && nMonth <= 12)
printf(“It is autumn.\n”); printf(“It is autumn.\n”);
printf(“Have a nice day.”); printf(“Have a nice day.”);
} }
/ccsrac 31 /ccsrac 32

The switch statement Examples


• Used when there are a lot of alternatives Write a program that accepts from the user the
day of the week in numeric form. The program
• Can only check equality relationships converts this to its word equivalent (i.e. Zero (0)
is for Sunday, one (1) for Monday, etc.).
Format: Should evaluate to
either a character,
/* Program that displays the day of the week, given
switch( <expression> ) integer, short, or byte
its numeric form */
{ #include <stdio.h>
case <label 1> : <statement>; [break;] main()
: {
case <label n> : <statement>; [break;] int nDay;
[ default : <statement>; ] printf(“Input day of the week (0-6): ”);
} scanf(“%d”, &nDay);

/ccsrac 33 /ccsrac 34

Examples Examples
/* Program that gives season, given the
numeric month */
switch(nDay)
{ #include <stdio.h>
case 0: printf(“SUNDAY”); break; main()
case 1: printf(“MONDAY”); break; {
case 2: printf(“TUESDAY”); break; int nMonth;
case 3: printf(“WEDNESDAY”); break;
printf(“Input month: ”);
case 4: printf(“THURSDAY”); break; scanf(“%d”, &nMonth);
case 5: printf(“FRIDAY”); break; switch(nMonth)
case 6: printf(“SATURDAY”); {
} case 1:
case 2:
} case 3:
printf(“It is winter.\n”);
break;

/ccsrac 35 /ccsrac 36

6
Examples Be careful of waterfalls!
case 4: /* Program that displays messages
case 5: depending on the grade entered. */
case 6: #include <stdio.h>
printf(“It is spring. \n”); main()
break; {
case 7: char cGrade;
case 8: printf(“Enter the grade: ”);
case 9: scanf(“%c”, &cGrade);
printf(“It is summer.\n”); switch(cGrade)
break; {
case 10: case ‘A’: printf(“V.Good!\n”); break;
case 11: case ‘B’:
case 12: case ‘C’: printf(“Good!\n”); break;
printf(“It is autumn.\n”); case ‘D’: printf(“Fair!\n”); break;
} default: printf(“Poor!\n”);
printf(“Have a nice day.”); }
} }

/ccsrac 37 /ccsrac 38

Exercises Exercises
9. Write a program that displays the expected 10. Write a program that interacts with the user
brightness of a standard light bulb given its like this:
wattage. Use this table:
(1) Carbon monoxide
(2) Hydrocarbons
Watts Brightness (in Lumens) (3) Nitrogen oxides
15 125 (4) Nonmethane hydrocarbons
25 215 Enter pollutant number>> 2
40 500 Enter number of grams emitted per mile>> 0.35
60 880 Enter odometer reading>> 40112
75 1000 Emissions exceed permitted level of 0.31 grams/mile.
100 1675
Use the table of emissions limits in next slide to determine
Display Unknown bulb if the watts input is not in the the appropriate message.
table.
/ccsrac 39 /ccsrac 40

Exercises New C Constructs


CONSTRUCT EFFECT
if statement
First 5 Years or Second 5 Years or
One Alternative
50,000 Miles Second 50,000
Miles if (x != 0.0) Multiplies fProduct by
fProduct = fProduct * x; x only if x is nonzero
Carbon monoxide 3.4 grams/mile 4.2 grams/mile
Hydrocarbons 0.31 grams/mile 0.39 grams/mile
Double-Alternative
Nitrogen oxides 0.4 grams/mile 0.5 grams/mile
if (fTemp > 32.0) If fTemp is greater than
Nonmethane 0.25 grams/mile 0.31 grams/mile printf(“%.1f: above freezing”, 32.0, it is labeled as
hydrocarbons fTemp); above freezing;
otherwise, it is labeled
else as freezing
printf(“%.1f: freezing”,
fTemp);

/ccsrac 41 /ccsrac 42

7
New C Constructs New C Constructs
CONSTRUCT EFFECT switch statement
if statement switch (cNextChar) {
Multiple-Alternative case ‘A’: Displays one of five
if (x < 0.0) { Displays one of three
case ‘a’: printf(“Excellent”); break; messages based on
messages depending case ‘B’: the value of
printf(“negative”);
on whether x is case ‘b’: printf(“Good”); break; cNextChar (type
fAbsX = -x;
case ‘C’: char). If cNextChar
} negative, positive or
zero. Sets fAbsX to case ‘c’: printf(“O.K.”); break; is ‘D’, ‘d’, ‘F’, or
else if (x == 0.0) { ‘f’, the student is
printf(“zero”); represent the absolute case ‘D’:
value or magnitude of x. put on probation. If
case ‘d’:
fAbsX = 0.0; fNextChar is not
case ‘F’:
} listed in the case
case ‘f’: printf(“Poor, student is”);
else { labels, displays an
printf(“on probation”); error message.
printf(“positive”);
break;
fAbs = x;
default: printf(“Invalid letter grade”);
}
}
/ccsrac 43 /ccsrac 44

More exercises

Arranged according to increasing complexity:


no. 6, 7 (Self-Evaluation Exercises, p. 58 )
no. 4, 5, 9, and 10 (Chapter Exercises on p. 61)
no. 9 (Self-Evaluation Exercises, p. 58)
no. 17 (Chapter Exercises, p. 62). Control Structures
no. 12, and 16 (Chapter Exercises, p. 62) (part 1)
no. 13 (Chapter Exercises, p. 62)

/ccsrac 45

S-ar putea să vă placă și