Midterm Looping
Midterm Looping
Statement
COMPUTER PROGRAMMING 1
LEARNING OBJECTIVES
1. Loop Statements
2. Parts of a loop
3. Types of Loops
While Loop
For Loop
Do-while Loop
4. Nested Loops
5. Jump Statements
Why Is Repetition Needed?
Output
Program Code:
#include <iostream>
Write a program using namespace std;
Int i = 0;
while ( i < 10 ) {
cout << i;
i += 2;
}
Test Yourself– While loop
int i = 1;
while ( i < 10 ) {
cout << i
<<endl;
i += 2;
}
Test Yourself – While loop
}
return 0;
}
DO-WHILE LOOP
Program Code:
Output
int i = 0; #include <iostream>
using namespace std;
do {
int main() {
cout << i << "\ int i = 0;
do {
n"; cout << i << "\n";
i++; }
i++;
Program Code:
Write a program that
display this output #include <iostream>
using Do-While loop. using namespace std;
int main(){
int num=1;
do{
cout<<"Value of num: "<<num<<endl;
num++;
}while(num<=6);
return 0;
}
LOGIC for DO WHILE LOOP
Test Yourself – DO WHILE
Output
Write a program that Program Code:
#include <iostream>
display counting from using namespace std;
1 to 10 using do-
while loop. int main() {
int i = 1;
do {
cout << i << "\n";
i++;
}
while (i <= 10);
return 0;
}
Test Yourself – DO WHILE
Write the complete code of the given output using DO WHILE LOOP.
int i = 0;
do {
cout<<i;
i++;
}
while (i<10);
Test Yourself – DO WHILE
int i = 0;
do
{
cout << i;
i += 2;
}
while ( i < 10 );
FOR LOOP
Output
Program Code:
} int main() {
for (int i = 0; i < 5;
i++) {
cout << i << "\n";
}
return 0;
}
Example 2 – For Loop
Outp
Program Code:
Write a program ut
B
D
C
A
NESTED LOOP
Nested loops consist of an outer loop with one or more inner loops.
int main() {
int row;
Output
Write a program that cout<<"Enter number
display a pattern of a of rows:";
given numbers using cin>>row;
nested loop.
for (int x=1; x<=row;
x++)
{
for (int z=1;
z<=x; z++)
{
cout<<z<<" ";
}
cout<<"\n";
}
cout << "Enter number of rows: ";
cin >> rows;
Outpu
Program Code:
The continue statement breaks one using Continue and For loop
t
iteration (in the loop), if a specified #include <iostream>
condition occurs, and continues with using namespace std;
the next iteration in the loop. int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
for (int i = 0; i < 10; i+ continue;
+) { }
if (i == 4) { cout << i << "\n";
continue; }
} return 0;
cout << i << "\n"; }
}
EXAMPLE – CONTINUE using WHILE loop
Program Code
Write a c++ program to print the numbers from 0 to 10 using for loop
#include <iostream>
using namespace std;
int main(){
Write a c++ program to print the even numbers from 10 to 0 using for
loop.
#include <iostream>
using namespace std;
int main(){
Write a c++ program asks the user to enter 5 characters using for loop,
if the user enters 'n' exit the loop.
#include <iostream>
using namespace std;
int main(){
char ch;
for (int i = 0; i <= 5; i++){
cout << "Enter charactar " << i <<" :";
cin >> ch;
if (ch == 'n')
break;
}
return 0;
}
TEST YOURSELF