You are on page 1of 17

EARNING ACTIVITY SHEET 2

Quarter 2
WEEK 3-4 ICT Computer Programming
Grade 10 - STE

MELC:
• Apply different control statements in a program.

ITERATION STRUCTURE (LOOPS)

- Every pass through the loop is known as iteration, which is one of the three structures of
programming (sequence, selection and iteration).
- A loop is any program construction that repeats a statement or sequence of statements a
number of times. The code that is repeated in a loop is called the loop body.
- In computer programming, loops are used to repeat a block of code.
- For example, let's say we want to show a message 100 times. Then instead of writing the
print statement 100 times, we can use a loop.
- That was just a simple example; we can achieve much more efficiency and sophistication
in our programs by making effective use of loops.

PARTS OF THE LOOP

➢ Initialization expression(s) initialize(s) the loop variables in the beginning of the loop.
➢ Test expression decides whether the loop will be executed (if test expression is true) or not
(if test expression is false)
➢ Update Expression(s) update(s) the values of loop variables after every iteration of the
loop.
➢ The Body-of-the-Loop contains statements to be executed repeatedly.

THE WHILE LOOP STATEMENT


- While loops will repeat a statement while a condition is true. This loop is the only loop that
will test the condition before the loop command is executed.
- While loops are based on Boolean conditions just like conditional statements.

How While loop works?


- In while loop, condition is evaluated first and if it returns true then the statements inside while
loop execute, this happens repeatedly until the condition returns false. When condition
returns false, the control comes out of loop and jumps to the next statement in the program
after while loop.
Note: The important point to note when using while loop is that we need to use increment or
decrement statement inside while loop so that the loop variable gets changed on each iteration,
and at some point condition returns false. This way we can end the execution of while loop
otherwise the loop would execute indefinitely.

Syntax of While Loop


while (condition) {

// body of the loop

1
FLOWCHART OF WHILE LOOP

Initialization

False
Condition

True

Code inside the body


End of Loop of while loop

Sample C++ program using While loop statement

1. C++ program to display numbers from 1 to 5


// C++ Program to print numbers from 1 to 5
#include <iostream>
using namespace std;
Output:

int main() {
1 2 3 4 5
int i = 1;
// while loop from 1 to 5
while (i <= 5) {
cout << i << " ";
++i;
}
return 0;
}

Here is how the program works.

Iteration Variable i <= 5 Action

1st i=1 true 1 is printed and i is increased to 2.

2nd i=2 true 2 is printed and i is increased to 3.

3rd i=3 true 3 is printed and i is increased to 4

4th i=4 true 4 is printed and i is increased to 5.

5th i=5 true 5 is printed and i is increased to 6.

6th i=6 false The loop is terminated

2
Or we can write the program just like this:

#include <iostream>
using namespace std;
int main(){
int i=1;
/* The loop would continue to print
* the value of i until the given condition
* i<=6 returns false.
*/
while(i<=6){
cout<<"Value of variable i is: "<<i<<endl; i++;
}
}

Output:
Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6

2. C++ program to display the sum of the positive numbers only


// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

// take input from the user


cout << "Enter a number: ";
cin >> number;

while (number >= 0) {


// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum is " << sum << endl;
return 0;
}
Output
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25
- In this program, the user is prompted to enter a number, which is stored in the
variable number. In order to store the sum of the numbers, we declare a variable sum and
initialize it to the value of 0. The while loop continues until the user enters a negative number.
During each iteration, the number entered by the user is added to the sum variable. When
the user enters a negative number, the loop terminates. Finally, the total sum is displayed.
3
3. C++ program to compute factorial of a number.

THE DO…WHILE LOOP STATEMENT

- The do...while loop is a variant of the while loop with one important difference: the body
of do...while loop is executed once before the condition is checked.

SYNTAX OF DO..WHILE LOOP

do {
// body of loop;
}
while (condition);

HOW DO…WHILE LOOP WORKS?

• The body of the loop is executed at first. Then the condition is evaluated.
• If the condition evaluates to true, the body of the loop inside the do statement is executed
again.
• The condition is evaluated once again.
• If the condition evaluates to true, the body of the loop inside the do statement is executed
again.
• This process continues until the condition evaluates to false. Then the loop stops.

4
FLOWCHART OF DO…WHILE LOOP

Code inside the body


of do..while loop

True

Condition

False

End of Loop

Sample C++ Program using Do…while loop

1. C++ program to display numbers from 1 to 5


// C++ Program to print numbers from 1 to 5

#include <iostream>
using namespace std;
Output:
int main() {
int i = 1;
1 2 3 4 5
// do...while loop from 1 to 5
do {
cout << i << " ";
++i;
}
while (i <= 5);

return 0;
}
Here is how the program works

Iteration Variable i <= 5 Action


i=1 not checked 1 is printed and i is increased to 2
1st i=2 true 2 is printed and i is increased to 3
2nd i=3 true 3 is printed and i is increased to 4
3rd i=4 true 4 is printed and i is increased to 5
4th i=5 true 5 is printed and i is increased to 6
5th i=6 false The loop is terminated

5
Or we can write the program just like this:
#include <iostream>
using namespace std;
int main(){
int num=1;
do{
cout<<"Value of num: "<<num<<endl;
num++;
}while(num<=6);
return 0;
}
Output:
Value of num: 1
Value of num: 2
Value of num: 3
Value of num: 4
Value of num: 5
Value of num: 6

2. C++ program to display the sum of the positive numbers only


// program to find the sum of positive numbers
// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {

int number = 0;
int sum = 0;

do {
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> number;
}
while (number >= 0);
// display the sum
cout << "\nThe sum is " << sum << endl;
return 0;
}

Output 1
Enter a number: 6 Here, the do...while loop continues until the user enters a
Enter a number: 12 negative number. When the number is negative, the loop
Enter a number: 7
terminates; the negative number is not added to
Enter a number: 0
the sum variable.
Enter a number: -2
The sum is 25

Output 2
Enter a number: -6 The body of the do...while loop runs only once if the user
enters a negative number.
The sum is 0.

6
3. C++ program using Logical operator

THE FOR LOOP STATEMENT

- It is used for a huge variety of tasks and algorithms. It is a fairly straightforward loop, but it
can be as complex or as deep as you can possibly imagine.
- The for-loop is also used to execute some statements repetitively for a fixed number of
times.
- When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
The syntax of for-loop is:
for (initialization; condition; update) {
// body of-loop
}
Here,
• initialization - initializes variables and is executed only once.
• condition - if true, the body of for loop is executed, if false, the for loop is terminated.
• update - updates the value of initialized variables and again checks the condition.

FLOWCHART OF FOR LOOP

Initialization

False
Condition

True
For loop body

End of Loop
Update counter

7
• First step - In for loop, initialization happens first and only once, which means that the
initialization part of for loop only executes once.
• Second step - Condition in for loop is evaluated on each loop iteration, if the condition is true
then the statements inside for loop body gets executed. Once the condition returns false,
the statements in for loop does not execute and the control gets transferred to the next
statement in the program after for loop.
• Third step - After every execution of for loop’s body, the increment/decrement part of for
loop executes that updates the loop counter.
• Fourth step - After third step, the control jumps to second step and condition is re-evaluated.

Note: The steps from second to fourth repeats until the loop condition returns false.

Sample C++ program using for loop statement

1. C++ program to print the value of I 10 times

Here is how this program works

Iteration Variable i < 10 Action


1st i=0 true 0 is printed. i is increased to 1 .

2nd i=1 true 1 is printed. i is increased to 2 .

3rd i=2 true 2 is printed. i is increased to 3 .

4th i=3 true 3 is printed. i is increased to 4 .

5th i=4 true 4 is printed. i is increased to 5 .

6th i=5 true 5 is printed. i is increased to 6 .

7th i=6 true 6 is printed. i is increased to 7 .

8th i=7 true 7 is printed. i is increased to 8 .

9th i=8 true 8 is printed. i is increased to 9 .

10th i=9 true 9 is printed. i is increased to 10 .

11th i = 10 false The loop is terminated

8
2. C++ program to display text 5 times

Here is how this program works

Iteration Variable i < 10 Action


1st i=5 true I love Programming!!! is printed and i is increased to 6.
2nd i=6 true I love Programming!!! is printed and i is increased to 7.
3rd i=7 true I love Programming!!! is printed and i is increased to 8.
4th i=8 true I love Programming!!! is printed and i is increased to 9.
5th i=9 true I love Programming!!! is printed and i is increased to 10.
6th i = 10 false The loop is terminated

3. Find the sum of first n Natural Numbers


// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers

#include <iostream>
using namespace std;
Output
int main() {
int num, sum;
sum = 0; Enter a positive integer: 10
Sum = 55
cout << "Enter a positive integer: ";
cin >> num;

for (int count = 1; count <= num; ++count) {


sum += count;
}
cout << "Sum = " << sum << endl;

return 0;
}

9
In the above example, we have two variables num and sum. The sum variable is assigned
with 0 and the num variable is assigned with the value provided by the user.

Note that we have used a for loop.

for(int count = 1; count <= num; ++count)

Here,
• int count = 1: initializes the count variable
• count <= num: runs the loop as long as count is less than or equal to num
• ++count: increase the count variable by 1 in each iteration
• When count becomes 11, the condition is false and sum will be equal to 0 + 1 + 2 + ... + 10.

break; STATEMENT
• In C++, the break statement terminates the loop when it is encountered.
• You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.
• The break statement can also be used to jump out of a loop.

The syntax of the break statement is:

break;
The break statement is used in following two scenarios:

❖ Use break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop terminating it. It is used
along with if statement, whenever used inside loop so that it occurs only for a particular
condition.
❖ It is used in switch case control structure after the case blocks. Generally, all cases in switch
case are followed by a break statement to avoid the subsequent cases execution.
Whenever it is encountered in switch-case block, the control comes out of the switch-case
body.
How break statement works

Sample program using break statement

1. Use of break statement in a while loop


#include <iostream>
using namespace std;
int main(){
int num =10;
while(num<=200) {
cout<<"Value of num is: "<<num<<endl;
if (num==12) {
break;
}

10
num++;
}
cout<<"Hey, I'm out of the loop";
In the example below, we have a while loop
return 0;
} running from 10 to 200 but since we have a break
statement that gets encountered when the loop
Output: counter variable value reaches 12, the loop gets
Value of num is: 10 terminated and the control jumps to the next
Value of num is: 11 statement in program after the loop body.
Value of num is: 12
Hey, I'm out of the loop

2. Use of break statement in a for loop


// program to print the value of i
In the program, the for loop is used to print the
#include <iostream>
value of i in each iteration. Here, notices the
using namespace std;
code:
int main() { if (i == 3) {

for (int i = 1; i <= 5; i++) { break;


// break condition
}
if (i == 3) {
break; This means, when i is equal to 3,
} the break statement terminates the loop.
cout << i << endl; Hence, the output doesn't include values
}
greater than or equal to 3.
return 0;
}

Output
1

Note: The break statement is usually used with decision-making statements.

Try it yourself

• Try to run this program and analyze how the program works.

int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

continue; STATEMENT
• In computer programming, the continue statement is used to skip the current iteration of
the loop and the control of the program goes to the next iteration.
• Continue statement is used inside loops. Whenever a continue statement is encountered
inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping
the execution of statements inside loop’s body for the current iteration.

11
Syntax of continue statement
continue;

How continue statement works?

Sample program using continue

1. continue with for loop

// program to print the value of i


#include <iostream>
Output
using namespace std;

int main() { 1
for (int i = 1; i <= 5; i++) { 2
// condition to continue
4
if (i == 3) {
5
continue;
}
cout << i << endl;
}
return 0;
} L;

In the above program, we have used the for loop to print the value of i in each iteration. Here,
notices the code,

if (i == 3) {
continue;
}
This means

• When i is equal to 3, the continue statement skips the current iteration and starts the next
iteration
• Then, i becomes 4, and the condition is evaluated again.
• Hence, 4 and 5 are printed in the next two iterations.

Note: The continue statement is almost always used with decision-making statements.

12
2. continue with while loop
• In a while loop, continue skips the current iteration and control flow of the program jumps
back to the while condition .

// program to calculate positive numbers till 50 only


// if the user enters a negative number,
// that number is skipped from the calculation
// negative number -> loop terminate
// numbers above 50 -> skip iteration

#include <iostream>
using namespace std;

int main() {
int sum = 0;
int number = 0;

while (number >= 0) {


// add all positive numbers
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> number;
// continue condition
if (number > 50) {
cout << "The number is greater than 50 and won't be calculated." <<endl;
number = 0; // the value of number is made 0 again
continue;
}
}
// display the sum
cout << "The sum is " << sum << endl;
return 0;
}

Output
Enter a number: 12
Enter a number: 0
Enter a number: 2
Enter a number: 30
Enter a number: 50
Enter a number: 56
The number is greater than 50 and won't be calculated.
Enter a number: 5
Enter a number: -3
The sum is 99

• In the above program, the user enters a number. The while loop is used to print the total
sum of positive numbers entered by the user, as long as the numbers entered are not
greater than 50 .
Notice the use of the continue statement.

if (number > 50){


continue;
}
13
• When the user enters a number greater than 50 , the continue statement skips the current
iteration. Then the control flow of the program goes to the condition of while loop.
• When the user enters a number less than 0, the loop terminates.
Note: The continue statement works in the same way for the do...while loops.

Try it yourself

• Try to run this program and analyze how the program works.
#include <iostream>
using namespace std;

int main() {
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
return 0;
}

14
LEARNING ACTIVITY SHEET 3
Quarter 3
WEEK 5-6 Computer Programming
Grade 10 - STE

MELC:
• Apply different control statements in a program.

Objectives:
Identify what is Increment, Decrement and Modulus operators.
Differentiate and explain how Increment, Decrement and Modulus operators works in a program.
Create a C++ program using Increment, Decrement and Modulus operators.

❖ What is increment and decrement operators?


- Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one.
- Both increment and decrement operator are used on single operand or variable, so it is
called as unary operator.
- Unary operators are having higher priority than the other operators it means unary
operators are execute before other operators.

Take note!

• The increment (++) and decrement (--) operators are unary operators that works only on
integer variables.

• The increment/decrement operators do not work on constants.

Example
x= 4++; // gives error, because 4 is constant

❖ How do they look like?

❖ Prefix and Postfix


- Both increment and decrement can be prefix or postfix.
- In the example, both prefix and postfix do not make any difference in the output as these
are standalone statements.
- But, when the pre/post increment or decrement are part of an expression the prefix and
postfix notation does matter.

❖ Pre-Increment/Decrement Operators (Prefix)


- In the prefix form, the increment or decrement operation is carried
out before the rest of the following.
❖ Post-Increment/Decrement Operators (Postfix)
- In the prefix form, the increment or decrement operation is carried
out after the rest of the following.

15
Sample program using Pre/Post Increment and decrement operators

➢ Example 1

Output

➢ Example 2

➢ Example 3

16
Take note!
• One of the main uses of the increment operator is to control the iteration of loops.

❖ What is modulus operator?


- The modulus operator (%) computes the remainder when one integer is divided by
another.
- The modulus operator is useful in a variety of circumstances. It is commonly used to take a
randomly generated number and reduce that number to a random number on a smaller
range, and it can also quickly tell you if one number is a factor of another.

Sample program using Modulus operators


➢ Example 1

➢ Example 2
- If you wanted to know if a number was odd or even, you could use modulus to quickly
tell you by asking for the remainder of the number when divided by 2.
#include <iostream>
using namespace std;

int main()
{
int num;
cin >> num;
// num % 2 computes the remainder when num is divided by 2
if ( num % 2 == 0 )
{
cout << num << " is even ";
}

return 0;
}

- The key line is the one that performs the modulus operation: "num % 2 == 0". A number is
even if and only if it is divisible by two, and a number is divisible by another only if there
is no remainder.

Take note!
- Modulus operator cannot be used for floating-type variables.

17

You might also like