[go: up one dir, main page]

0% found this document useful (0 votes)
63 views80 pages

cc102 Module

The document discusses loops in C++ programming. It defines loops as repetition structures that allow code to execute repeatedly without rewriting the code each time. The key elements of a loop are identified as the loop control variable, sentinel value, and loop update. Common types of loops in C++ include for, while, do-while, and nested loops. Examples are provided to demonstrate how loops work and how the increment and decrement operators can update the loop control variable.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views80 pages

cc102 Module

The document discusses loops in C++ programming. It defines loops as repetition structures that allow code to execute repeatedly without rewriting the code each time. The key elements of a loop are identified as the loop control variable, sentinel value, and loop update. Common types of loops in C++ include for, while, do-while, and nested loops. Examples are provided to demonstrate how loops work and how the increment and decrement operators can update the loop control variable.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

CC – 102

WorkText

Rodibelle F. Leona
Rodella F. Salas Emilsa T. Bantug
Melgine M. Bauat Domingo B. Bago
Jet C. Aquino Johannah Mae C. Vasquez
Edward M. Mansibang Michael L. De Guzman

0
UNIT 1. LOOPS
Learning Objectives

At the end of the unit, I am able to:


1. identify the loop or repetition structure;
2. identify the different elements of the loop;
3. differentiate the increment and decrement operators; and
4. create simple and complicated programs using loops.

When writing C++ codes, there are times that you need to do a
statement or a block of statements a certain number of times. What you
have to do is to type the statement or block of statements repeatedly
as to the number of times you want it or them to be executed. For
example, you are asked to display your name and age on the screen 5
times, the following code will be part of your C++ program.

cout<<”VeeArbs”<<endl;
cout<<18<<endl;
cout<<”VeeArbs”<<endl;
cout<<18<<endl;
cout<<”VeeArbs”<<endl;
cout<<18<<endl;
cout<<”VeeArbs”<<endl;
cout<<18<<endl;
cout<<”VeeArbs”<<endl;
cout<<18<<endl;

It is okay if the specific number of times is less than 10, but how
about if it is more than 10 times or a hundred times or a thousand times?
C++ provides a structure which will help you do repetitive tasks without
typing them over and over again. It is called the repetition structure
or looping. Another word for looping is iteration.

1
ELEMENTS OF LOOPING

A loop will not function properly without any of its important


elements.

1. Loop Control Variable (LCV)

The loop control variable will hold the value that will be
compared to the limit of the loop. The limit sets when the loop will
end. The loop control variable should be first initialized before it
can be used in the program.

2. Sentinel Value

The sentinel value is the value where the loop control


variable will be compared to. This value is set to decide if the loop
will continue or stop based on the result of the comparison. The
result of the comparison is always a Boolean value, that is, true
or a false.

3. Loop update

Inside the loop, the value of the loop control variable must
be altered. This is called the loop update. You can change the
value by incrementing or decrementing.

The increment operator (++) adds 1 to its operand, and


the decrement operator (--) subtracts 1 from its operand.
Thus:

x = x + 1;

which is the same as


x++;

will evaluate to 5 if the initial value of x is 4.

Similarly,

2
x = x - 1;

which is the same as


x--;

will evaluate to 10 if the initial value of x is 11.

Both the increment and decrement operators can either


precede (prefix) or follow (postfix) the loop control
variable. For example:

x = x + 1;

can be written as
++x;

or as
x++;

The first is the prefix form and the second one is the postfix
form of the statement x = x + 1;

When an increment or decrement is used as part of an


expression, there is an important difference in using the prefix
and postfix forms. If you are using prefix form, the increment or
decrement will be done before evaluating the expression. And if
you are using postfix form, the increment or decrement will be
done after the complete expression is evaluated.

SAMPLE PROBLEM

Create a C++ program that will display the postfix


and prefix increment values of a variable whose initial
value is 21

3
SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7{
8 int a = 21;
9 int c ;
10
11 c = a++;
12
13 cout << "Line 1 - Value of a++ is " << c << endl ;
14 cout << "Line 2 - Value of a is " << a << endl ;
15
16 c = ++a;
17
18 cout << "Line 3 - Value of ++a is " << c << endl ;
19
20 return EXIT_SUCCESS;
21 }

SAMPLE OUTPUT

Line 1 – Value of a++ is 21


Line 2 – Value of a is 22
Line 3 – Value of ++a is 22

4
Increment and decrement are not only for adding or
subtracting 1 from the current value of the loop control variable.
They can be any value you wish to add or subtract from the
value of the loop control variable. The following are examples of
the increment and decrement by other numerals aside from 1.

int x = 5;

UPDATE CURRENT VALUE OF x


x = x + 2; 7
x -= 5; 2
x -= 9; -7
x += 2; -5
x += 10; 5
x -= 6; -1
x = x – 12; -13
x += 7; -6
x -= 14; -20

If you do not alter the loop control variable, it will result with
an infinite loop.

An infinite loop is a loop which never stops. You have to


be careful so that you will not end up with an infinite loop.

There are also loops which will not do anything which is


called the empty loop. This happens when the comparison
expression evaluates to false even on the first try. You have to
make sure that the comparison expression will evaluate to true at
least once. What will be the good of using a loop if at the first time
that you compare the value of the loop control variable to the
sentinel value, it evaluates to false? The loop body will not be
executed and it will proceed to the statement right after the loop.
In this case, the loop structure will be like a design in your

5
program and does not do anything. There will be no sense in
including this type of loop in your program.

SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7 {
8 int x;
9
10 x = 10;
11 while (x <= 6)
12 {
13 cout<<“CHOOBAH “;
14
15 x--;
16 }
17
18 cout<<endl;
19 cout<<“Nothing happened inside the loop”;
20
21 return EXIT_SUCCESS;
22 }

SAMPLE OUTPUT

Nothing happened inside the loop

10

6
TYPES of LOOPS

1. for LOOP
2. while LOOP
3. do while LOOP
4. nested LOOP

THE for LOOP

A for loop is a repetition control structure that allows you to


efficiently write a loop that needs to execute a specific number of times.

The syntax of a for loop in C++ is:

for (initialization; comparison expression; update)


{
statement(s);
}

EXAMPLE
comparison of the loop
initialization of the loop control variable to the
control variable sentinel value

for (x = 1; x <= 5; x++) loop update


{
cout<<”*”;
cout<<endl; loop body
}

FLOW OF CONTROL IN A for LOOP

1. The initialization of the loop control variable is executed first,


and only once. In here, the loop control variable is assigned with its
initial value.

7
2. The comparison expression is evaluated next. If it evaluates to
true, the body of the loop is executed. If it is false, the body of the
loop does not execute and the flow of control jumps to the next
statement just after the closing brace (}) of the for loop.

3. After the body of the for loop is executed, the flow of control jumps
back up to the update statement. This statement allows you to
update the loop control variable. The update can be an increment
or a decrement depending on the initial value of the loop control
variable, the comparison operator used and the sentinel value.

FLOW DIAGRAM OF THE for LOOP

8
SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7{
8 int x;
9
10 for (x = 1; x <= 5; x++)
11 {
12 cout<<x<<“ “;
13 }
14
15 cout<<endl;
16 cout<<“This is the code after the loop”;
17
18 return EXIT_SUCCESS;
19 }

SAMPLE OUTPUT

6
12345
5
This is the code after the loop 4
3
2
1

SIMULATION

Line number 7 starts the main method of the program.

On line number 8, the computer will allocate memory space for


variable x where the values that you will place should only be integer
values.
9
Line number 10 sets the initial value of x to 1 (x = 1), then
compare the value of x if it is less than or equal to 5 (x <= 5). It will
ask if 1 <= 5. Since the comparison evaluates to true, the code inside
the loop body on line number 12 will be executed (cout<<x<<” “).
1 will be printed on the screen followed by a space.

Next, x will become 2 since (x++) will add 1 to the current value
of x.

The simulation goes back to the comparison expression where


the computer will evaluate the expression, 2 <= 5 which is true. It will
then execute the loop body and print 2 on the screen and a space.

Next, x becomes 3.

Comparing 3 <= 5 evaluates to true, so 3 will be printed followed


by a space.

Next, x becomes 4.

Comparing 4 <= 5 evaluates to true, so 4 will be printed followed


by a space.

Next, x becomes 5.

Comparing 5 <= 5 evaluates to true, so 5 will be printed followed


by a space.

Next, x becomes 6.

Comparing 6 <= 5 evaluates to false. In this instance, the


execution of the loop body will stop and the computer will execute the
next lines following the for loop.

The computer will now print a newline (cout<<endl) found in


line number 15. Then, it will proceed to line number 16 which prints
the message (cout<<”This is the code after the loop”).

10
Line number 18 will print a message that you have successfully
executed the program.

Line number 19 ends the main method of the program.

11
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 1

I. EVALUATE THE VALUE OF THE FOLLOWING UPDATES.

CODE VALUE OF x

x = 45;

x += 13;

x = x - 23;

x -= 32;

x++;

x -= 2;

x--;

x = x + 6;

x += 17;

x -= 4;

12
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 2

SIMULATE THE FOLLOWING PROGRAM. USE THE SCREEN


FOR THE OUTPUT AND THE BOXES FOR THE MEMORY
ALLOCATIONS OF THE VARIABLES NEEDED. USE ONLY THE
EXACT NUMBER OF BOXES FOR THE DECLARED VARIABLES AND
DISREGARD THE REST OF THE BOXES.

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
int x;

for (x = 5; x >= 1; x--)


{
cout<<x<<“ “;
}

cout<<endl;
cout<<“FINISH”;

return EXIT_SUCCESS;
}

13
14
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 3

SIMULATE THE FOLLOWING PROGRAM. USE THE SCREEN


FOR THE OUTPUT AND THE BOXES FOR THE MEMORY
ALLOCATIONS OF THE VARIABLES NEEDED. USE ONLY THE
EXACT NUMBER OF BOXES FOR THE DECLARED VARIABLES.

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
int x, square;

for (x = 1; x <=10; x += 2)
{
square = x * x;

cout<<square;
}

cout<<endl;

square = 10;

cout<<square<<endl<<endl;

return EXIT_SUCCESS;
}

15
16
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Laboratory Exercise No. 1

MAKE A C++ PROGRAM THAT WILL PRINT THE OUTPUT ON


THE SCREEN USING FOR LOOP.

1 PROGRAM CODE
3
5
7
9
11
13
15

17
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Laboratory Exercise No. 2

MAKE A C++ PROGRAM THAT WILL PRINT THE OUTPUT


ON THE SCREEN USING for LOOP.

1@4@9@16@25@

18
THE while LOOP

Another form of loop is the while loop. Basically, it will do the


repetitive tasks assigned to it just like in a for loop. However, in a while
loop, the initialization of the loop control variable is typed before the
structure of the loop. The loop update on the other hand is placed
inside the loop body. The syntax of the while loop is given below.

initialization;
while (comparison expression)
{
statement/s;
loop update;
}

EXAMPLE:

initialization of the loop


control variable
comparison of the loop
control variable to the
ctr = 1; sentinel value
while (ctr <= 5);
{
cout<<ctr<<endl;
loop body
ctr++;
}

loop update

19
FLOW DIAGRAM

SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7 {
8 int x;
9
10 x = 5;
11 while (x >= 3)
12 {
13 cout<<x<<“ “;
14
15 x--;
16 }
17
18 cout<<endl;
19 cout<<“Loop has terminated”;
20
21 return EXIT_SUCCESS;
22 }

20
SAMPLE OUTPUT

543
Loop has terminated 2
3
4
5

SIMULATION

Line number 7 starts the main method of the program.

On line number 8, the computer will allocate memory space for


variable x where the values that you will place should only be integer
values.

Line number 10 sets the initial value of x to 5 (x = 5).

On line number 11, the value of x is compared if it is greater


than or equal to 3 (x >= 3). It will ask if 5 >= 3. Since the comparison
evaluates to true, the code inside the loop body on line number 13
will be executed (cout<<x<<” “). 5 will be printed on the screen
followed by a space.

Next, line number 15 will update the value of x and it will


become 4 since (x--) will subtract 1 from the current value of x.

The simulation goes back to the comparison expression where


the computer will evaluate the expression, 4 >= 3 which is true. It will
then execute the loop body and print 4 on the screen and a space.

Next, x becomes 3.

21
Comparing 3 >= 3 evaluates to true, so 3 will be printed followed
by a space.

Next, x becomes 2.

Comparing 2 >= 3 evaluates to false. In this instance, the


execution of the loop body will stop and the computer will execute the
next lines following the for loop.

The computer will now print a newline (cout<<endl) found in


line number 18. Then, it will proceed to line number 19 which prints
the message (cout<<”Loop has terminated”).

Line number 21 will print a message that you have successfully


executed the program.

Line number 22 ends the main method of the program.

LOOP UPDATE USING A PROMPT

There are also instances when the loop has no definite number of
times to execute, meaning, it will continue to do the iteration until such
time that the user of the program tells the program to stop the execution
of the looping process.

The loop update will be a question prompting the user if he wants


to continue or stop executing the loop. So, every time the user enters a
positive answer to the question, the loop body will be executed. It will
stop the execution of the loop body when it receives a negative response
to the question.

22
SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7 {
8 char ans;
9
10 cout<<”Do you want to continue? (Y/N): “;
11 cin>>ans;
12
13 while (ans == ‘Y’)
14 {
15 cout<<”DERON”<<endl;
16 cout<<”Do you want to continue? (Y/N): “;
17 cin>>ans;
18 }
19
20 cout<<endl;
21 cout<<“Loop has terminated”;
22
23 return EXIT_SUCCESS;
24 }

SAMPLE OUTPUT

Do you want to continue? (Y/N): Y


DERON
Do you want to continue? (Y/N): Y N
DERON Y
Do you want to continue? (Y/N): N Y

Loop has terminated


ans

23
SIMULATION

Line number 7 starts the main method of the program.

On line number 8, the computer will allocate memory space for


variable ans where the values that you will place should only be
character values.

Line number 10 prints the prompt on the screen (cout<<”Do


you want to continue? (Y/N): “;).

On line number 11, the value entered in the prompt by the user
will be placed in variable ans.

Line number 13 (while (ans == ‘Y’)) will compare if the value


entered by the user is Y.

Since the value entered is Y, the loop body was executed. DERON
was printed on the screen followed by a newline, as the statement
(cout<<”DERON”<<endl;) instructed on line number 15.

Line number 17 (cout<<”Do you want to continue? (Y/N):


“;) will print the prompt on the screen again and wait for the user to
enter a value.

Variable ans will get the value entered in the prompt as instructed
on line number 18 (cin>>ans;) which is the character Y. This will
serve as the update of the loop.

The execution of the code will go back to line number 13 and


compare if Y is equal to Y. Since the expression evaluates to true, the
loop body will again be executed and a new value for ans will be set and
the value of ans will again be compared to Y.

Since the new value of ans is N, the loop terminates and the next
line following the loop will be executed. Line number 21
(cout<<endl;) will print a new line on the screen.

24
Next will be line number 22 (cout<<“Loop has terminated”;)
which will print the literal string on the screen.

Line number 24 will print a message that you have successfully


executed the program.

Line number 25 ends the main method of the program.

25
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 4

Make a C++ program using while loop to find the


factorial of a positive integer entered by user. (Factorial of
n = 1*2*3...*n).

26
27
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Laboratory Exercise No. 3

Make a C++ program that will print the output on the


screen using while loop.

0
25
100
225
Ay ad payb end iskweyrd da namber.

28
THE do while LOOP

The do while loop functions just like a for loop or a while loop.
The only difference is that the comparison happens at the end of the do
while loop so the body of the loop is executed at least once even if
the comparison expression evaluates to false, unlike in the for loop and
the while loop where the comparison expression happens before the
loop body. This is the reason why, in the for and while loops, when the
comparison evaluates to false, the loop body will not be executed even
once. The structure of a do while loop is shown below.

initialization;
do
{
statement/s;
loop update;
} while (comparison expression);

EXAMPLE initialization of the loop


control variable

loop body
ctr = 1;
do
{
cout<<ctr<<endl; loop update

ctr++; Don’t forget the


} while (ctr <= 5); semicolon here

comparison

29
SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7 {
8 int x;
9
10 x = 5;
11 do
12 {
13 cout<<x<<“ “;
14
15 x--;
16 } while (x >= 3);
17
18 cout<<endl;
19 cout<<“Loop has terminated”;
20
21 return EXIT_SUCCESS;
22 }

SAMPLE OUTPUT

543
2
Loop has terminated
3
4
5

SIMULATION

Line number 7 starts the main method of the program.

30
On line number 8, the computer will allocate memory space for
variable x where the values that you will place should only be integer
values.

Line number 10 sets the initial value of x to 5 (x = 5). Line


number 11 will start the do while loop.

Line number 13 will be executed (cout<<x<<” “). 5 will be


printed on the screen followed by a space.

Next, line number 15 will update the value of x and it will


become 4 since (x--) will subtract 1 from the current value of x.

Then, the comparison expression on line number 16 will be


executed, where the computer will evaluate the expression, 4 >= 3
which is true. It will then execute the loop body and print 4 on the
screen and a space.

Next, x becomes 3. Comparing 3 >= 3 evaluates to true, so 3


will be printed followed by a space. Next x becomes 2.

Comparing 2 >= 3 evaluates to false. In this instance, the


execution of the loop body will stop and the computer will execute the
next lines following the for loop.

The computer will now print a newline (cout<<endl) found in


line number 18. Then, it will proceed to line number 19 which prints
the message (cout<<”Loop has terminated”).

Line number 21 will print a message that you have successfully


executed the program.

Line number 22 ends the main method of the program.

31
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 5

Make a C++ program that will input a number and


display the sum of the numbers from 1 to the input number.
Be guided by the sample output given.

Enter a no: 5

Sum is 15

32
33
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Laboratory Exercise No. 4

Make a C++ program that will print the output on the


screen using do while loop.

5
6
7
8
9
10

34
NESTED LOOPS

A nested loop is a loop within a loop. It is consisting of an outer


loop and an inner loop. The outer loop will be executed first. When the
evaluation of the comparison operators evaluates to true, the loop body
of the outer loop will be executed. Inside the loop body of the outer
loop, the inner loop is embedded. When the inner loop executes and the
comparison of the inner loop evaluates to true, the loop body of the
inner loop will be executed until such time that the comparison
expression results to false. The inner loop terminates at this point and
the rest of the statements inside the loop body of the outer loop will be
executed. Then, the update of the outer loop will be performed and the
process will be repeated until the outer loop terminates.

outer loop

for (x = 1; x <= 5; x++)


{
for (y = 1; y <= 3; y++)
{ inner loop
cout<<”*”;
cout<<endl;
}
cout<<endl;
}

The number of times the nested loop will execute is equal to the
number of times the outer loop executes and the number of times the
inner loop executes.

tLoop = o * i;

Let’s say that the outer loop will iterate 3 times and the inner
loop will iterate 5 times, the total iteration will be 15.

35
SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main()
7 {
8 int x, y, loopCounter = 0;
9
10 for (x = 1; x <= 3; x++)
11 {
12 for (y = 1; y < 4; y++)
13 {
14 cout<<y<<“ “;
15
16 loopCounter++;
17 }
18
19 cout<<endl;
20 }
21
22 cout<<endl;
23 cout<<“This loop iterates “<<loopCounter<<” times.”<<endl<<endl;
24
25 return EXIT_SUCCESS;
26 }

SAMPLE OUTPUT

123 4 4 4 4
123 3 3 3 3
123 2 2 2 2
1 1 1 1
This loop iterates 9 times
x y

5
4
3 9
2 8
1 7
0 6

loopCounter

36
SIMULATION

Line number 7 starts the main method of the program.

On line number 8, the computer will allocate memory spaces for


variable x, variable y and variable loopCounter which will hold integer
values only. It will also initialize loopCounter with a value of 0.

Line number 10 sets the initial value of x to 1 (x = 1), then


compare the value of x if it is less than or equal to 3 (x <= 3). The
answer will be true.

Line number 12 will then be executed setting the initial value of


1 to variable y. Comparison comes next with (x < 4) which evaluates
to true.

The inner loop body will be executed and from line number 14
(cout<<y<<” “), the value of y which is 1 will be printed on the screen
followed by a space.

Line number 16 will add 1 to loopCounter.

Next, y will become 2 since (y++) in line number 10 will add 1


to the current value of x.

The simulation goes back to the comparison expression where


the computer will evaluate the expression, 2 < 4 which is true. It will
then execute the loop body and print 2 on the screen and a space. 1
will be again be added to the current value of loopCounter.

Next, y becomes 3.

Comparing 3 < 4 evaluates to true, so 3 will be printed followed


by a space. 1 will be again be added to the current value of
loopCounter.

Next y becomes 4.

37
Comparing 4 < 4 evaluates to false. In this instance, the
execution of the inner loop body will stop and the computer will execute
the next lines following the for loop.

The computer will now print a newline (cout<<endl) found in


line number 19.

The outer loop body will finish on line number 20 and it will
increment variable x. So from (x++) on line number 10, x will now
have a value of 2.

The process will be repeated again until the update of the outer
loop evaluates to 4 and the comparison results to false.

Then, it will proceed to line number 22 which prints a newline


(cout<<endl) and the message (cout<<”This loop iterates
“<<loopCounter<<” times”) from line number 23.

Line number 25 will print a message that you have successfully


executed the program.

Line number 26 ends the main method of the program.

38
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 6

Make a C++ program that will display the sample output.

12345
1234
123
12
1

39
40
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Laboratory Exercise No. 5

Make a C++ program that will print the output on the


screen using do while loop. (NOTE: There are no spaces in
between rows)

*
**
***
****
*****

41
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

CHAPTER TEST
I. FILL-OUT THE CROSSWORD PUZZLE. THE NUMBER AFTER
THE CLUES CORRESPONDS TO THE NUMBER OF WORDS THE
ANSWER HAS.

42
ACROSS
1. Variable that controls the loop (3)
7. Increment or decrement (2)
8. The value where the lcv was compared to (2)
10. Increment or decrement after evaluation (1)
11. Increment or decrement before evaluation (1)
12. Loop within the loop (2)
14. Another term for looping or repetition structure (1)
15. A loop that never ends (2)

DOWN
2. Determines when the loop continues or ends (2)
3. Setting a first value to a variable (1)
4. True or false (2)
5. Loop that does nothing (2)
6. Increase the value of a variable (1)
9. Decrease the value of a variable (1)
13. A control structure that do a statement or a block of
statements a certain number of times (1)

II. WHAT IS THE DIFFERENCE BETWEEN A for AND A while


LOOP TO A do while LOOP.

43
III. WRITE A C++ PROGRAM THAT WILL PRINT THE OUTPUT
GIVEN. USE ANY COMBINATION OF NESTED LOOPS.
CLUE: THE OUTPUT HAS SPACES BETWEEN NUMBERS AND
THE PROGRAM MUST HAVE 2 NESTED LOOPS.

1
12
123
1234
12345
1234
123
12
1

44
UNIT 2. ARRAYS
Learning Objectives

At the end of the unit, I am able to:


5. identify the array structure;
6. differentiate the different types of arrays; and
7. create simple and complicated programs using arrays.

An array is a series of elements with the same data type which


are placed in adjoining memory locations. Each element of an array can
be individually referenced by adding an index to the array’s identifier.

Let’s say that you are to use the five quizzes of a student in a C++
program. In a regular C++ code, you have to declare each quiz with its
corresponding variable name. So you will have to declare five variable
names for the five quizzes, for example:

int quiz1, quiz2, quiz3, quiz4, quiz5;

Since the quizzes will be of the same type, say, int, you can use
an array to declare and use the quizzes. With an array declaration, you
can place the quizzes in adjoining memory locations and each quiz can
be accessed by calling the array name and its corresponding index. The
index represents the memory location of an element in an array. The
first element is always at index [0], therefore, the second will be at
index [1], the third at index [2] and so on. The syntax for the
declaration of an array is:

data_type array_name[no_of_elements];

where data_type is any valid data type such as int, float, short, char
and others, array_name is a valid identifier and the number of
elements enclosed in the open and close brackets signifies the length
of the array. The number of elements must be a constant value since
arrays are blocks of static memory whose size must be determined at
compile time, before the program runs.

45
For an array of five quizzes, the declaration will be:

array name
data type number of
elements

int quiz[5];

The compiler will allocate five adjoining memory locations for


array quiz.
0 1 2 3 4

quiz

In C++, the first element in an array is always numbered with a


zero (not a one), no matter its length. So since array quiz have 5
elements, the memory address starts with quiz[0] and ends with
quiz[4].

INITIALIZING ARRAYS

Usually, arrays are not initialized, meaning, they are not given
values in the declaration part of the code. But you can initialize arrays
by placing specific values when they are declared enclosed in opening
and closing braces. The syntax for initializing an array is:

dataType arrayName[no_of_elements] = {val1, val2,…, valn};

EXAMPLE:
int quiz[5] = {85, 75, 69, 81, 95};

This initialization will cause the compiler to allot 5 adjoining


memory locations with the following values.

46
0 1 2 3 4

85 75 69 81 95

quiz

The following shows the value of each element in the array.

quiz[0] = 85
quiz[1] = 75
quiz[2] = 69
quiz[3] = 81
quiz[4] = 95

The number of values inside the braces MUST not be greater than
the length of array. If the number of values is less, the remaining
elements will have the default value of 0.

int quiz[5] = {85, 75, 69};

This initialization will cause the computer to allot 5 adjoining


memory locations with the following values.

0 1 2 3 4

85 75 69 0 0

quiz

The value of each element in the array will be like this:

quiz[0] = 85
quiz[1] = 75
quiz[2] = 69
quiz[3] = 0
quiz[4] = 0

If the braces have no value inside, then the resulting memory


locations allotted will look like this:
47
0 1 2 3 4

0 0 0 0 0

quiz

and the value of each element in the array will be like this:
quiz[0] = 0
quiz[1] = 0
quiz[2] = 0
quiz[3] = 0
quiz[4] = 0

Also, the brackets of the array can be empty, meaning that the
length of the array is not specified in the declaration. If this is the case,
the compiler will assume the number of values in the array as its length.
In this example:

int quiz[] = {85, 75, 69, 81};

the compiler will allot 4 memory locations for the array quiz.

0 1 2 3

85 75 69 81

quiz

ARRAY VALUES

Assigning the value of an element in an array is just like assigning


the value of any regular variable. The syntax to do this is:
array_name[index_no];

For example,

choobah[3] = 32;

will store the value 32 in the fourth element of the array choobah.

48
0 1 2 3 4

32

Since, the index of an array always starts with 0 and is therefore


the first element of the array, choobah[1] will be the second element,
choobah[2] is the third element, choobah[3] is the fourth element
and choobah[4] will be the fifth element.

You can also transfer/copy the value of an array element into a


variable, let’s say,

a = choobah[3];

therefore, variable a will have a value of 32.

In C++, it is syntactically correct to exceed the valid range of


indices for an array, meaning you will not encounter an error message
when you compile your program. The problem will be on the output of
the code. For example,

x = choobah[6];

This code will not create an error during compilation but the error
will be seen during runtime.

At this point, it is important to be able to clearly distinguish


between the two uses that brackets [] have related to arrays. They
perform two different tasks: one is to specify the size of arrays when
they are declared;

int quiz[5];

and the second one is to specify indices for concrete array


elements when they are accessed.

a = quiz[3];
Do not confuse these two possible uses of brackets [] with arrays.

49
SAMPLE PROBLEM

Make a C++ program that will add the values of an array with 5
elements.

SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int main ()
7 {
8 int num[] = {23, 21, 45, 8, 7};
9 int x, sum=0;
10
11 for ( x=0 ; x<5 ; x++ )
12 {
13 sum += num[x];
14 cout<<sum<<endl;
15 }
16
17 cout <<”The sum is “<<sum;
18
19 return EXIT_SUCCESS;
20 }

SAMPLE OUTPUT

23 21 45 8 7

num[0] num[1] num[2] num[3] num[4]

5 104 The sum is 104


4 97
3 89
2 44
1 23

x sum

50
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 7

Make a C++ program that will display all the contents of


an integer array with a length of 5. Use a for loop.

51
52
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 8

Make a C++ program that will display the sum of the


values of an integer array with a length of 6. The values of
the array will be input values from the user. Use for loops.

53
54
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Laboratory Exercise No. 6

Make a C++ program that will print the average of the


values of an array named areas with values {45, 82, 93} using
while loop.

55
MULTIDIMENSIONAL ARRAYS

A multidimensional array is an array of arrays. The most


common of which is a bi-dimensional array, a two dimensional array
and can be imagined as a two-dimensional table made of elements with
the same data types.

0 1 2 3 4

deron

This bi-dimensional array named deron is consists of 3 by 5


elements with data type int. To declare this array, the syntax is:
int deron [3][5];

To access the third element vertically and the second horizontally


of this sample array, use the following code:
deron [2][1];

0 1 2 3 4

deron

Multidimensional arrays are not limited to two indices (i.e., two


dimensions). They can contain as many indices as needed.

56
SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 #define WIDTH 5
7 #define HEIGHT 3
8
9 int main ()
10 {
11 int jimmy [HEIGHT][WIDTH];
12 int n, m, x, y;
13
14 for (n=0; n<HEIGHT; n++)
15 {
16 for (m=0; m<WIDTH; m++)
17 {
18 x = n + 1;
19 y = m + 1;
20 jimmy[n][m] = x * y;
21
22 cout<<jimmy[n][m]<<” “;
23 }
24
25 cout<<endl;
26 }
27
28 return EXIT_SUCCESS;
29 }

SAMPLE OUTPUT

12345
2 4 6 8 10
3 6 9 12 14

57
3
2
1
3 5 0

HEIGHT WIDTH n

5 5 5
4 4 4 5 5 5
3 3 3 4 4 4
2 2 2 3 3 3 3
1 1 1 2 2 2 2
0 0 0 1 1 1 1

m x y

58
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 9

Make a C++ program that will create a multiplication table


from 1 to 9 using multidimensional arrays.

59
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

CHAPTER TEST

I. IDENTIFY THE FOLLOWING.

1. It is a series of elements with the same data type which are


placed in adjoining memory locations.
_________________________________________

2. It is an array of arrays.
_________________________________________

3. A two-dimensional array and can be imagined as a two-


dimensional table made of elements with the same data types.
__________ ______________________________

4. The number of elements enclosed in the open and close


brackets signifies the _______ of the array.
_________________________________________

5. It represents the memory location of an element in an array.


_________________________________________

60
II. WRITE THE VALUE OF THE FOLLOWING. LABEL FIRST
THE INDICES OF THE ARRAY.

1 12 85 15 42 95 11 77 52 56 17 32

18 64 78 82 31 59 88 0 3 86 72 45

99 25 75 16 33 54 19 10 44 38 66 69

84 55 47 29 30 20 90 80 70 35 74 22

65 23 61 4 7 8 6 15 37 57 67 60

bato

bato[0][0] = __________
bato[4][11] = __________
bato[3][7] = __________
bato[1][3] = __________
bato[2][9] = __________
bato[3][2] = __________
bato[1][6] = __________
bato[0][4] = __________
bato[2][8] = __________
bato[4][5] = __________

III. WRITE THE INDICES OF THE FOLLOWING VALUES.


11 = _____________________
22 = _____________________
33 = _____________________
44 = _____________________
55 = _____________________
66 = _____________________
77 = _____________________
88 = _____________________
99 = _____________________
17 = _____________________

61
UNIT 3. FUNCTIONS
Learning Objectives

At the end of the unit, I am able to:


8. identify a function structure;
9. identify the different parts of a function structure; and
10. create simple and complicated programs using
functions.

Functions are modules or segments of code that perform


individual tasks. In C++, a function is a group of statements that is
given a name, and which can be called from some point in the program.
The most common syntax to define a function is:

data_type function_name ( parameter_1, ..., parameter_n)


{
statement_1;
statement_2;
.
.
.
statement_n;
}

where:

The data_type is the type of data of the value that will be


returned by the function.

The function_name is the identifier by which the function can be


called.

The parameters can be as many as needed. Each parameter


consists of a data type followed by an identifier, with each parameter
being separated from the next by a comma. Each parameter looks very
much like a regular variable declaration (for example: int x), and in fact
62
acts within the function as a regular variable which is local to the
function, meaning it can only be used by the function. The purpose of
parameters is to allow the passing of arguments to the function from
the location where it is called from.

The statements consists the body of the function. It is a block of


statements surrounded by braces { } that specify what the function
actually does.

SAMPLE PROBLEM

Make a C++ program that will add two numbers using function.

SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int addi(int x, int y)
7 {
8 int r;
9
10 r = x + y;
11
12 return r;
13 }
14
15 int main () Function
16 {
17 int sum;
call
18
19 sum = addi(10, 4);
20
21 cout << "The sum is " << sum;
22
23 return EXIT_SUCCESS;
24 }

63
SAMPLE OUTPUT

The sum is 14

14 14
10 4
sum x y r

SIMULATION

The program starts by declaring variable sum with data type int
at line number 17. The compiler will allocate memory space for this
variable.

Next, variable sum will have the value passed by the function
which will be called in line number 19. The values 10 will be passed to
variable x and 4 will be passed to variable y in function named addi at
line number 6.

Since the function was called, it will now be processed and in line
number 8, variable r will be given a memory allocation. Line number
10 will add the value of x (10) and the value of y (4) and store that
value to r.

The stored value will then be passed back to the main function
and stored in variable sum (still at line number 19).

Line number 21 will print the message “The sum is “ followed


by the value of sum and a newline.

Line number 24 ends the program.

64
You can also call the function a multiple number of times. The
argument of the function call is not limited to literal values only. It can
also be variables which hold the same data type as to the arguments of
the function.

SAMPLE PROGRAM
1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 int subt (int a, int b)
7 {
8 int r;
9
10 r = a - b;
11
12 return r;
13 }
14
15 int main ()
16 {
17 int x=5, y=3, z, u, v, w;
18
19 z = subt (7,2);
20
21 cout<<"The first result is " <<z<<endl;
22
23 u = subt(15, 8);
24
25 cout<<"The second result is "<<u<<endl;
26
27 v = subt(x, y);
28
29 cout << "The third result is " <<v<<endl;
30
31 w = 40 + subt(x, y);
32
33 cout << "The fourth result is " <<w<< endl;
34
35 return EXIT_SUCCESS;
36 }

In the sample program, the statement (z = subt (7,2);) calls


the function subt and passes the value 7 to variable a and the value
2 to variable b. The function is then executed and 2 was subtracted
from 7 and the result is 5 which was then stored in variable r. Next,
the function returns the value of r to the function call and stored in
variable z.

65
The next line of code in the main method was executed where
the following is printed on the screen:

The first result is 5

On the statement following the last executed code, function subt


was called again and the value of 15 was passed to variable a and 8
to variable b. The function subt was then executed and returned 7
which was stored in variable u on the main method. The next line of
output is:

The second result is 7

Next statement was the call to function subt again, but this
time, the arguments are variables x and y. Since the value of x is 5,
5 was passed to variable a and 3 was passed to variable b. Then this
output appeared on the screen.

The third result is 2

The last function call passed the same values as the preceding
function call but this time, the returned value was added to 40 so the
display was

The fourth result is 42

void FUNCTIONS

There are functions which do not return a value but only prints
messages on the screen. These are called void functions. Void
functions are created and used just like value-returning functions except
they do not return a value after the function executes. In lieu of a data
type, void functions use the keyword "void." A void function performs a
task, and then control returns back to the caller--but, it does not return
a value. You may or may not use the return statement, as there is no
return value.

66
Let’s say that you want to make a function which will print your
name and age on the screen.

SAMPLE PROGRAM

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5
6 void message()
7 {
8 cout<<”Dayle Xylia”<<endl;
9 cout<<”12 years old<<endl<<endl;
10 }
11
12 int main ()
13 {
14 message();
15
16 return EXIT SUCCESS;
17 }

SAMPLE OUTPUT

Dayle Xylia
12 years old

67
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 10

JUMBLED WORDS. ARRANGE THE LETTERS TO FORM THE


NEEDED WORDS.

1. A module or segment of code that perform an individual task.


IF NOT C NU

2. There are functions which do not return a value but only prints
messages on the screen.
SOUND OF VIC TIN

3. It is a block of statements surrounded by braces { } that


specify what the function actually does.
IN THE FFOOD BY COUNT

4. The purpose of these is to allow the passing of arguments to


the function from the location where it is called from.
MATS ARE REP
5. This is put in the body of the program to access the
function.
U FILL CANTON C

68
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 11

Make a C++ program that will display your name, age


and birthdate on the screen using function.

69
Dayle Xylia
13 years old
March 05, 2005

70
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Laboratory Exercise No.7

Make a C++ program that will print the average of the


values of three quizzes using function. The values of the quizzes
are input from the user.

71
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 12
Make a C++ program that will input two numbers and
display the sum of the numbers. Do this five times. Use
function for the computation of the sum.

72
73
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Laboratory Exercise No. 8

Make a C++ program that will print the highest number of


the three input numbers using function.

74
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

Seatwork No. 13

Make a C++ program that will display netpay of an


employee by inputting the basic pay and overtime pay. It
should compute first the gross pay which is the sum of the
input values and the tax which is 10% of the basic pay. The
netpay is grosspay minus tax. Use a function for each
computation.

0
1
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________

CHAPTER TEST

I. FIND THE LISTED WORDS BELOW WHICH ARE RELATED


TO FUNCTIONS AND THE SUBJECT CODE.

FUNCTIONS DATATYPE FUNCTION NAME


VOID BRACES PARAMETERS
COMMA RETURN FUNCTION CALL

2
II. Make a C++ program that will input the first letter of a
shape (square, triangle, circle or rectangle). It should test
which area will be computed based on the input shape.
There should be an error message if the input value is not
one of the choices. Use a function for the computation of
the area of each shape. The needed value will be passed
through the function call, say for the area of the square,
the side which will be an input from the main function will
be passed to the function that will compute for the area of
the square. Use selection structure to determine the shape
of the area that will be computed.

3
4

You might also like