CCS003L Demerin (M6-TECHNICAL)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

COLLEGE OF COMPUTER STUDIES AND MULTIMEDIA ARTS

CCS0006L
(COMPUTER PROGRAMMING 1)

EXERCISE

6
REPETITION CONTROL STRUCTURE

Student Name / Group


The BOISS
Name:
Name Role
John Benedict T. Del Analyst/Programmer
Rosario
Members (if Group):
Rowell E. Demerin Analyst/Programmer
Romwell Clarence V. Analyst/Programmer
Venzon
BSIT TC02
Section:
Sir Alex
Professor:
I. PROGRAM OUTCOME/S (PO) ADDRESSED BY THE LABORATORY EXERCISE
• Analyze a complex problem and identify and define the computing requirements appropriate to its solution.
[PO: B]
• Design, implement and evaluate computer-based systems or applications to meet desired needs and
requirements. [PO: C]

II. COURSE LEARNING OUTCOME/S (CLO) ADDRESSED BY THE LABORATORY EXERCISE


• Select and apply appropriate program constructs in developing computer programs. [CLO: 2]
• Develop, test and debug computer programs based on a given specification using the fundamental
programming components. [CLO: 3]

III. INTENDED LEARNING OUTCOME/S (ILO) OF THE LABORATORY EXERCISE


At the end of this exercise, students must be able to:
• Identify the significance of each type of repetition control structures and how to implement it in a C++
program.
• Create C++ programs that use various repetition control structures to solve problems.

IV. BACKGROUND INFORMATION

Loops have as objective to repeat a statement a certain number of times or while a condition is
fulfilled.

A. The while loop

Its format is:

while (expression) statement

and its function is simply to repeat statement while expression is true.


// custom countdown using while Enter the starting number > 8
#include <iostream> 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
using namespace std;

int main ()
{

CCS0003L-Computer Programming 1 Page 2 of 19


int n;
cout << "Enter the starting number >
";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!";
return 0;
}
When the program starts the user is prompted to insert a starting number for the countdown.
Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n be greater
than 0 ), the block of instructions that follows will execute an indefinite number of times while the condition
(n>0) remains true.

B. The do-while loop

Format:

do statement while (condition);

The while loop performs the conditional test first and then executes the loop, so the statements within
a loop may never be executed. The do...while loop performs the statements first and then tests the
condition. This means that the body of the loop is always executed at least once.

The general form of a do...while loop is

do
{
statements;
}while(test_condition);

Look carefully at the end of the loop. There is a semi-colon at the end of the while condition
statement. This terminates the whole statement and results in one more semi-colon than the equivalent
while loop.
// number echoer Enter number (0 to end): 12345
#include <iostream> You entered: 12345
using namespace std; Enter number (0 to end): 160277
You entered: 160277
int main () Enter number (0 to end): 0
{ You entered: 0

CCS0003L-Computer Programming 1 Page 3 of 19


unsigned long n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}

C. The for loop

Its format is:

for (initialization; condition; increment) statement;

Many loops have these characteristics in common:


• initialization,
• a condition which evaluates either to FALSE or TRUE,
• an increment.

The for keyword marks the beginning of the code which will be repeated according to the conditions
supplied in the parenthesis following the for. The general form of the statement is

for (initialization; condition; increment)


{
statements;
} // end for

To make this clearer let's take the following while loop

count = 0; // initialization
while (count < 10) // condition
{
cout << count;
count++; //increment
} // end while

and re-write it using a for loop:

for (count=0; count<10; count++)


{
cout << count;
} // end for

CCS0003L-Computer Programming 1 Page 4 of 19


• The initialization statement is carried out only once when the loop is first entered.
• The condition is tested before each run through the body of the loop. The first test is immediately
after initialization, so if the test fails the statements in the body are not run - just like a while loop.
• The third expression, usually an increment or decrement to alter the test condition variable, is
executed after the loop body and before the next test. This is the same as putting the increment
or decrement at the end of a while loop.

for (count=0; count<10; count++); // for loop stops here because


// of the semicolon
{
cout << count; // this will always run, or cause an error
} // end for

The for loop can be incremented or decremented by any amount, for example the following are all
valid for statements.

for (i = 10.0; i <= 1000; i = i * 2.5) // or i *= 2.5


{
statements;
}
for (k = 1.0; k > 0.001; k = k / 2.0) // or k /= 2.0
{
statements;
}

and its main function is to repeat statement while condition remains true, like the while loop. But
in addition, for provides places to specify an initialization instruction and an increase instruction. So this
loop is specially designed to perform a repetitive action with a counter.

// countdown using a for loop 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!


#include <iostream>
using namespace std;

int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}

CCS0003L-Computer Programming 1 Page 5 of 19


Using the comma operator (,) we can specify more than one instruction in any of the fields included
in a for loop, like in initialization, for example. The comma operator (,) is an instruction separator, it serves
to separate more than one instruction where only one instruction is generally expected. For example,
suppose that we wanted to initialize more than one variable in our loop:

for ( n=0, i=100 ; n!=i ; n++, i-- )


{
// whatever here...
}

This loop will execute 50 times if neither n nor i are modified within the loop:

n starts with 0 and i with 100, the condition is (n!=i) (that n be not equal to i). Because n is
increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when
both n and i will be equal to 50.

D. The break instruction


Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end
an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count
down before it naturally finishes:

// break loop example 10, 9, 8, 7, 6, 5, 4, 3, countdown


#include <iostream> aborted!
using namespace std;

int main ()
{ int n;
for (n=10; n>0; n--) {
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}}
return 0; }

CCS0003L-Computer Programming 1 Page 6 of 19


E. The continue instruction

The continue instruction causes the program to skip the rest of the loop in the present iteration as if
the end of the statement block would have been reached, causing it to jump to the following iteration. For
example, we are going to skip the number 5 in our countdown:

// break loop example 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!


#include <iostream>
using namespace std;

int main ()
{ for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!";
return 0; }

F. The goto instruction.

It allows making an absolute jump to another point in the program. You should use this feature
carefully since its execution ignores any type of nesting limitation.
The destination point is identified by a label, which is then used as an argument for the goto
instruction. A label is made of a valid identifier followed by a colon (:).
// goto loop example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
#include <iostream>
using namespace std;
int main ()
{ int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!";
return 0; }
G. The exit function

exit is a function defined in cstdlib (stdlib.h) library.

The purpose of exit is to terminate the running program with a specific exit code. Its prototype
is:

CCS0003L-Computer Programming 1 Page 7 of 19


void exit (int exit code);

The exit code is used by some operating systems and may be used by calling programs. By
convention, an exit code of 0 means that the program finished normally and any other value means an
error happened.

V. LABORATORY ACTIVITY

ACTIVITY 6.1: Loop to Multiply

Using while loop, calculate the product of two numbers without using the multiplication (*) operator.

Sample Output:
Enter 1st number: 2
Enter 2nd number: 2
Product: 4

Program: (save as [surname_6_1.cpp])

CCS0003L-Computer Programming 1 Page 8 of 19


Output:(screenshot of the output)

ACTIVITY 6.2: Getting the Factorial

Using do while loop, write a program that will ask the user to input an integer number. Compute for the
factorial value. Factorial is the product of all positive integers less than or equal to n.

Example: 5! = 5*4*3*2*1 = 120

Sample Output:
Enter an integer number: 5
The factorial of 5 is: 120

Program: (save as [surname_6_2.cpp])

CCS0003L-Computer Programming 1 Page 9 of 19


Output:(screenshot of the output)

ACTIVITY 6.3: The Rise in Our Stars

Using for nested loop, write a program that will ask for a positive integer number. The program will display
an increasing number of printed star/s from 1 to the integer entered by the user. If the user entered an invalid
input such as 0 or any other input, display an error message.

Sample Output:
Enter a number: 5
*
**
***
****

CCS0003L-Computer Programming 1 Page 10 of 19


*****

Program: (save as [surname_6_3.cpp]

Output:(screenshot of the output)

ACTIVITY 6.4: Sum of Natural Numbers

Using any loop structure, write a program that computes for the sum of the natural numbers from 1 up to
the positive integer entered by the user.

Sample Output:

CCS0003L-Computer Programming 1 Page 11 of 19


Enter a number: 5
The sum from 1 to 5 is 15
Program: (save as [surname_6_4.cpp])

Output:(screenshot of the output)

ACTIVITY 6.5: Up To

Using any loop structure, write a program that displays the numbers from the starting number up to the last
number. The starting number should be less than or equal to the last number otherwise display an error
message.

Sample Output:
Enter starting number: 3
Enter last number: 9
The numbers are: 3456789

Program: (save as [surname_6_5.cpp])

CCS0003L-Computer Programming 1 Page 12 of 19


Output:(screenshot of the output)

ACTIVITY 6.6: Complete Me

CCS0003L-Computer Programming 1 Page 13 of 19


Directions: Complete the programs below that satisfy the given problem specification and output. Paste your
completed source code in the Code portion then highlight the statement(s) that you filled in the incomplete
program with color yellow. Note: Indicated inside the parenthesis after the Program No. is the name of the
project.

Program No. 1 (loop1)


The program should ask the user the initial number of asterisks it will display in the first row after the input.
The program then should display a decreasing number of asterisks in the succeeding row until it reaches a
single asterisk. The program should also display the total number of asterisks printed on screen.

Incomplete Program Sample Output


#include<iostream>
using namespace std;

int main() {
int x, no, y, total = 0;
cout << "How many stars? ";
cin >> no;
for (x = no; _____________; x--) {
total = _____________
for (_____________; y > 0; y--)
cout << "*";
cout << "\n";
}
cout << "Wow " << total << " stars in
all!!!";
return 0;
}

Code:

CCS0003L-Computer Programming 1 Page 14 of 19


Program No. 2 (loop2)
The program should ask the user an initial value and a terminal value which will serve as the range of numbers
that will be printed on screen. The program should also display only those numbers divisible by 5 in the given
range. If the value of the initial value is greater than the terminal value, then the program should display
“Invalid entry.”

Incomplete Program Sample Output


#include<iostream>
using namespace std;

int main() {
int initial, terminal;
cout << "Enter initial value:";
cin >> initial;
cout << "Enter terminal value:";
cin >> terminal;
if (______________) {
cout << "Numbers in the range
divisible by 5:\n";
do {
if (______________)
cout << initial << " ";
initial++;
} while (______________);
}
else
cout << "Invalid entry.";
return 0;
}

Code:

CCS0003L-Computer Programming 1 Page 15 of 19


Program No. 3 (loop3)
The program should display the Multiplication Table of a number entered by the user.

Incomplete Program Sample Output


#include<iostream>
using namespace std;

int main() {
int x, no;
cout << "Enter number:";
cin >> no;

CCS0003L-Computer Programming 1 Page 16 of 19


cout << "Multiplication Table of " << no <<
endl;
x = 1;
while (_________) {
cout << no << " x " << x << " =" <<
_________ << "\n";
_________
}
return 0;
}

Code:

VI. QUESTION AND ANSWER

Directions: Briefly answer the questions below.

• What is the significance of using repetition control structures?

CCS0003L-Computer Programming 1 Page 17 of 19


Repetition control structures allow your code to be more efficient. There are some problems that
require repetitive process to reach the final output. Instead of repeating the same line of code
over and over, you can just use a loop which is more efficient and looks better. DEL ROSARIO

Since there are some of the problems that often need to be repeated, repetition controls
structures help the user to repeat a certain segment over and over. It is used when a program
needs to repeatedly process one or more instructions until the condition is met, at which time the
loops end. VENZON

Repetition control structures are used when a program needs to repeat one process or more,
until the condition/s is met, and then the loop ends. It is used to perform the same take over and
over again such as problems like searching, sorting, or optimization algorithms. DEMERIN

• In which problem situation do-while is used for? Explain.

It was used in activity 6.2. It’s used in that activity to repeat the formula as long as the input
number is greater than zero. DEL ROSARIO

do-while is used if the user wants a certain value to be repeated as long as the conditional
expression evaluates to true. Just like in activity 6.5 where to program continuously printing
numbers from the first value until the last number that the user input and then stops when it
reaches the given last value. VENZON

In Activity 6.2 and Activity 6.5, do-while is used. The do-while loop is used when a piece of code
has to be executed once and then repeated as long as a given condition is true. One such
scenario is user input validation, in which you want to check that the user enters a legitimate
value before proceeding with the program logic. Other issue cases where do-while loops are
beneficial include menu-driven applications, debugging and troubleshooting, and iterative
methods that need the code block to be completed at least once. DEMERIN

VII. REFERENCES
• Abraham (2015). Coding for dummies. John Wiley and Sons: Hoboken, NJ
• Zak, D (2015). An Introduction to Programming with C++. 8th Edition
• Cadenhead, R et. Al. (2016). C++ in 24 Hours, Sams Teach Yourself (6th Edition).Sams Publishing

CCS0003L-Computer Programming 1 Page 18 of 19


• McGrath, M. (2017). C++ programming in easy steps (5th ed.). Warwickshire, United Kingdom: Easy
Steps Limited
• Tale, T. (2016). C++: The Ultimate Beginners Guide to C++ Programing. CreateSpace Independent
Publishing Platform
• http://cs.uno.edu/~jaime/Courses/2025/devCpp2025Instructions.html

RUBRIC:

Criteria 4 3 2 1 Score
A completed
A completed solution is An incomplete
A completed
solution is implemented solution is
solution runs
tested and runs on the required implemented
without errors.
but does not platform, and on the required
It meets all the
meet all the uses the platform. It
specifications
specifications compiler does not
and works for
nd/or work for specified. It compile and/or
all test data.
all test data. runs, but has run.
Solution(x5) logical errors.

The program Not all of the


Few of the
The program design selected
selected
design uses generally uses structures are
structures are
appropriate appropriate appropriate.
appropriate.
structures. The structures. Some of the
Program
overall program Program program
elements are
design is elements elements are
not well
appropriate. exhibit good appropriately
Program designed.
design. designed.
Design(x3)

All required There are few


All required
parts of the parts of the Most of the
parts in the
document are document are parts of the
document are
complete and missing but the document are
present and
correct(code, rest are missing and
correct but not
output of complete and incorrect.
Completeness complete.
screenshots) correct.
of
Document(x2)
Total

CCS0003L-Computer Programming 1 Page 19 of 19

You might also like