cc102 Module
cc102 Module
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
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
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
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.
x = x + 1;
Similarly,
2
x = x - 1;
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;
SAMPLE PROBLEM
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
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;
If you do not alter the loop control variable, it will result with
an infinite loop.
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
10
6
TYPES of LOOPS
1. for LOOP
2. while LOOP
3. do while LOOP
4. nested LOOP
EXAMPLE
comparison of the loop
initialization of the loop control variable to the
control variable sentinel 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.
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
Next, x will become 2 since (x++) will add 1 to the current value
of x.
Next, x becomes 3.
Next, x becomes 4.
Next, x becomes 5.
Next, x becomes 6.
10
Line number 18 will print a message that you have successfully
executed the program.
11
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 1
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
#include <iostream>
#include <cstdlib>
int main()
{
int x;
cout<<endl;
cout<<“FINISH”;
return EXIT_SUCCESS;
}
13
14
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 3
#include <iostream>
#include <cstdlib>
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: _________________
1 PROGRAM CODE
3
5
7
9
11
13
15
17
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
1@4@9@16@25@
18
THE while LOOP
initialization;
while (comparison expression)
{
statement/s;
loop update;
}
EXAMPLE:
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
Next, x becomes 3.
21
Comparing 3 >= 3 evaluates to true, so 3 will be printed followed
by a space.
Next, x becomes 2.
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.
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
23
SIMULATION
On line number 11, the value entered in the prompt by the user
will be placed in variable ans.
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.
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.
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.
25
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 4
26
27
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
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);
loop body
ctr = 1;
do
{
cout<<ctr<<endl; loop update
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
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.
31
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 5
Enter a no: 5
Sum is 15
32
33
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
5
6
7
8
9
10
34
NESTED LOOPS
outer loop
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
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.
Next, y becomes 3.
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 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.
38
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 6
12345
1234
123
12
1
39
40
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
*
**
***
****
*****
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)
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
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:
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];
quiz
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:
EXAMPLE:
int quiz[5] = {85, 75, 69, 81, 95};
46
0 1 2 3 4
85 75 69 81 95
quiz
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.
0 1 2 3 4
85 75 69 0 0
quiz
quiz[0] = 85
quiz[1] = 75
quiz[2] = 69
quiz[3] = 0
quiz[4] = 0
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:
the compiler will allot 4 memory locations for the array quiz.
0 1 2 3
85 75 69 81
quiz
ARRAY VALUES
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
a = choobah[3];
x = choobah[6];
This code will not create an error during compilation but the error
will be seen during runtime.
int quiz[5];
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
x sum
50
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 7
51
52
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 8
53
54
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
55
MULTIDIMENSIONAL ARRAYS
0 1 2 3 4
deron
0 1 2 3 4
deron
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
59
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
CHAPTER TEST
2. It is an array of arrays.
_________________________________________
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] = __________
61
UNIT 3. FUNCTIONS
Learning Objectives
where:
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).
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 }
65
The next line of code in the main method was executed where
the following is printed on the screen:
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 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
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
2. There are functions which do not return a value but only prints
messages on the screen.
SOUND OF VIC TIN
68
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 11
69
Dayle Xylia
13 years old
March 05, 2005
70
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
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: _________________
74
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
Seatwork No. 13
0
1
Seat No.: _____________________ Rating:________________
Name: _________________________ Date: _________________
CHAPTER TEST
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