Control Structures in C++: Example
Control Structures in C++: Example
1. Sequential Structure
Example:
n1=5 //statement 1
n2=6 //statement 2
sum = n1 + n2 //statement 3
131
The “if” Statement
1. if statement
Syntax:
if (condition)
statement;
Example
if (number < 0)
cout<<“The number is negative\n";
Syntax:
if (condition)
{
statement1;
statement2;
statement3;
statement4;
132
}
2. if-else condition
Syntax:
if (condition)
statement1;
else
statement2;
Example:
if (num<0)
cout<<num<<”is a negative number \n”;
else
cout<<num<<”is a positive number \n”;
if (condition)
{
statement1;
statement2;
133
statement3;
}
Else
{
statement1;
statement2;
statement3;
}
3. if-else-if ladder
Syntax:
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
:
:
else
statement;
134
The conditions are evaluated from top to bottom. As
soon as a true condition is found, the statement associated with
it is executed, and the rest of the ladder is bypassed.
If none of the conditions are true then the final else will
be executed. The final else often acts as a default condition;
that is, if all other conditional tests fail then the last else
statement is performed. If the final else is not present and all
other conditions are false, then no action will take place.
Example:
if (result >= 75)
cout<<“Passed: Grade A\n";
else if (result >= 60)
cout<<“Passed: Grade B\n";
else if (result >= 45)
cout<<“Passed: Grade C\n";
else
cout<<“Failed\n";
#include<iostream>
int main()
{
int grade;
cout<<“\nEnter your grade: ";
cin>>grade;
if(grade>=75)
135
cout<<“Passed \n";
else
cout<<“Failed \n";
return 0;
}
Begin
grade=0
Read grade
Y
If
Print “PASSED”
grade>=75
Print “FAILED”
END
136
Figure 5-1b Output
(Sample Problem 5-1 Using if-else statement)
#include<iostream.h>
int main()
{
int grade;
cout<<“\nEnter your grade: ";
cin>>grade;
if(grade>=75)
cout<<“Passed \n";
else if (grade>=70)
cout<<“Incomplete \n";
else
cout<<“Failed \n";
return 0;
}
137
Figure 5-2b Output
(Sample Problem 5-1 Using if-else if statement)
138
Name: Section:
Instructor: Time/Day:
FILENAME: PTASK10.cpp
PROGRAM
139
Sample Problem 5-2: Draw a flowchart and write a program
that will read values of a student’s grade. If the student grade is
A - Print “OUTSTANDING”
B - Print “VERY GOOD”
C - Print “GOOD”
D - Print “STUDY HARD”
140
Program (Sample Problem 5-2)
#include<iostream.h>
int main()
{
char grade;
cout<<"Enter your grade: ";
cin>>grade;
if (grade=='A')
cout<<“Outstanding \n";
else if (grade=='B')
cout<<“VERY GOOD \n ";
else if (grade=='C')
cout<<“GOOD \n ";
else if (grade=='D')
cout<<“STUDY HARD \n”;
else
cout<<“Invalid input \n";
return 0;
}
141
Figure 5-4c: Output (Sample Problem 5-2)
#include<iostream.h>
int main()
{
char grade;
cout<<"Enter grade: ";
cin>>grade;
if ((grade=='A') || (grade=='a'))
cout<<”OUTSTANDING \n";
else if ((grade=='B') || (grade=='b'))
cout<<“VERY GOOD \n";
else if ((grade=='C') || (grade=='c'))
cout<<“GOOD \n";
else if ((grade=='D') || (grade=='d'))
cout<<“STUDY HARD \n";
else
cout<<“Invalid Input \n";
return 0;
}
142
Figure 5-5a: Output (Sample Problem 5-3)
143
Name: Section:
Instructor: Time/Day:
FILENAME: PTASK11.cpp
144
Name: Section:
Instructor: Time/Day:
Sample Output:
Enter room number : 426
Enter room capacity : 30
Enter no. of students enrolled : 20
FILENAME: PTASK12.cpp
145
Name: Section:
Instructor: Time/Day:
NUMBER MESSAGE
0–9 Number read is less than 10
10 Number read is 10
11 – 99 Number read is greater than 10
100 Number read is 100
101 Above Number read is greater than 100
FILENAME: PTASK13.cpp
NOTE: Please copy the correct program
146
Name: Section:
Instructor: Time/Day:
ax2+bx+c=0
FILENAME: PTASK14.cpp
147
Name: Section:
Instructor: Time/Day:
Write a program that will determine the largest and smallest no.
of the three floating point numbers supplied by the user.
FILENAME: PTASK15.cpp
148
The switch-case Statement
Syntax:
switch (variable)
{
case constant1: statement sequence;
break;
case constant2: statement sequence;
break;
case constant3: statement sequence;
break;
default: statement sequence;
}
1. The switch differs from if in that switch can only test for
equality, whereas the if can evaluate a relational or
logical expression.
149
3. If character constants are used in the switch, they are
automatically converted to their integer values.
Break – the break statement has two uses, the first one is to
terminate a case in the switch statement, while the second one
is to terminate a loop and bypass the normal loop conditional
tests. When a break statement is encountered inside the loop,
the loop is immediately terminated and the program control
resumes at the next statement following the loop.
#include<iostream.h>
int main()
{
int num;
cout<<“input a number from 1 to 5: ”;
cin>>num;
switch (num)
{
case 1:cout<<“One”;
break;
case 2:cout<<“Two”;
break;
case 3:cout<<“Three”;
break;
case 4:cout<<“Four”;
break;
case 5:cout<<“Five”;
break;
default: cout<<“Number is out of range”;
150
}
return 0;
}
switch (ch)
{
case ‘A’: /*this has a common statement*/
case ‘a’: cout<<“Apple”;
case ‘B’:
case ‘b’: cout<<“Banana”;
case ‘C’:
case ‘c’: cout<<“Carrot”;
default:cout<<“Not an ABC character”;
}
Duplication of similar actions to several alternatives is avoided
using the switch statement. For example, the switch statement
below has duplicate actions:
switch (major_code)
{
case 1:cout<<“Science Student”;
break;
case 2:cout<<“Art Student”;
break;
case 3:cout<<“Science Student”;
break;
case 4:cout<<“Art Student”;
break;
case 5:cout<<“Science Student”;
151
}
switch (major_code)
{
case 1:
case 3:
case 5:
cout<<“Science Student”;
break;
case 2:
case 4:
cout<<“Art Student”;
}
152
Name: Section:
Instructor: Time/Day:
FILENAME: PTASK16.cpp
NOTE: Please copy the correct program
153
Name: Section:
Instructor: Time/Day:
Choice Value
‘C’ or ‘c’ circumference of a circle
‘A’ or ‘a’ area of a circle
‘D’ or ‘d’ diameter of a circle
FILENAME: PTASK17a.cpp
PROGRAM
154
2. Create a program that will ask the user to input time in a 24-
hour notation and output it in 12-hour notation. For
example, if the input is 13:45, the output should be 1:45pm.
The program should instruct the user always to enter
exactly 5 characters. So for example, nine o’clock should
output 09:00.
FILENAME: PTASK17b.cpp
PROGRAM
155
NAME: SECTION:
INSTRUCTOR: TIME/DAY:
CASE ANALYSIS
Layout Screen
FILENAME: CSTUDY1.cpp
NOTE: Please copy the correct program on the space
provided.
156
Loops/Repetition Statements
157
On the other hand, a posttest repetition statement first
executes the loop body and then computes the predicate. If the
predicate is true, the loop body executes again; otherwise; the
repetition terminates.
for Statement
The for loop lets us keep performing an action over and over on
our data until a condition (which we specify) becomes true.
Syntax:
for (initialization ; condition ; increment)
statement;
158
at the end of the loop, just before the condition tested to see if
we should loop again.
#include <iostream.h>
int main()
{
int index;
for (index=1; index<=5;++index)
{
cout<<“Rizal Technological University \n";
}
return 0;
159
Figure 5-8: Output (Sample Problem 5-5)
#include <iostream.h>
int main()
{
int index;
for (index=0; index<=9;++index)
{
cout<<“Hello, world \n";
}
return 0;
}
160
Name: Section:
Instructor: Time/Day:
Write a C++ program that will display the sine, cosine and
tangent values of numbers from 1-10.
FILENAME: MP6.cpp
SCREEN LAYOUT
PROGRAM
161
while Statement
while ( Expression )
Statement
/* end while */
#include<iostream.h>
int main()
{
int number;
number=0;
while (number<3)
{
cout<<“Congratulations\n";
number=number+1;
}
return 0;
}
162
Figure 5-10: Output (Sample Problem 5-7)
163
A properly constructed while statement works as follows:
This program computes for the sum of two numbers and uses
while statement to ask if you want to continue.
#include<iostream.h>
int main()
{
int num1,num2,sum;
char more='Y';
while (more=='Y' || more== 'y')
{/*begin while*/
cout<<“Enter 1st number: ";
cin>>num1;
cout<<“Enter 2nd number:";
cin>>num2;
sum=num1+num2;
cout<<“The sum is "<<sum<<“\n";
cout<<“Do you want to continue[y/n]";
cin>>more;
}/*end while */
return 0;
}
164
Figure 5-11 Output (Sample Problem 5-8)
165
Name: Section:
Instructor: Time/Day:
Write a program that would ask the user to enter positive float
values from the keyboard when prompted by the program. To
signal end of input the user enters a negative integer. When
data entry has terminated, the program should output the
following:
a) minimum value entered
b) maximum value entered
c) Average of the positive values entered.
If there is no data entry, (the user enters a negative number
initially) then the program should output a message indicating
that no data has been entered.
FILENAME: MP7.cpp
NOTE: Please copy the correct program on the space
provided.
PROGRAM
166
The do-while loop
Unlike the for and while loops, which test the loop
condition at the top of the loop, the do-while loop checks its
condition and the bottom of the loop. This means that a do-
while loop will always execute at least once.
do
{
statement;
}
while(condition);
#include<iostream.h>
int main()
{
int num;
do
{
cin>>num;
}
while(num>100);
return 0;
}
167
Figure 5-12 Output (Sample Problem 5-9)
#include <iostream.h>
int main()
{
int number = 44;
int guess;
cout<<“Guess a number between 1 and 100\n";
do {
cout<<"Enter your guess: ";
cin>>guess;
168
Figure 5-13 Output (Sample Problem 5-10)
} while(choice<1 || choice>4);
After the options have been displayed, the program will loop
until a valid option is selected. Loops can also be nested.
169
Name: Section:
Instructor: Time/Day:
12+22+32=1+4+9=14
FILENAME: MP8.cpp
Screen Layout
FILENAME: MP9.cpp
Screen Layout
170
3. Write a program that computes for the square, the
square root and the fourth power of numbers from 0 to
25. Display the numbers using a neat four-column format
as shown below:
FILENAME: MP10.cpp
Screen Layout
25
FILENAME: MP11.cpp
Screen Layout:
LOAN : 800.00
RATE : 10%
PAYMENT : 200.00
171
YEAR PRINCIPAL INTEREST PAYMENT
1 800 80 200
2 680 68 200
3 548 54.80 200
4 402.80 40.28 200
5 243.08 24.308 200
6 67.388 6.7388 74.1268
FILENAME: MP12.cpp
NOTE: Please copy the correct program
172