C++ Programming: Academic Year 2018-2019 Lecturer Zanco A. Taha (MSC.)
C++ Programming: Academic Year 2018-2019 Lecturer Zanco A. Taha (MSC.)
C++ Programming
Academic Year
2018-2019
Lecturer
Zanco A. Taha (MSc.)
Outlines
2
Iteration structures: loops
Loops have as purpose to repeat a statement a certain number of
times or while a condition is fulfilled
• For loop
• While loop
• Do while loop
The For Loop
for (initialization; condition; increase)
statement;
// number echoer
#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}
The break statement
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.
// break loop example
#include <iostream>
using namespace std;
int main () {
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;}
The Continue statement
The continue statement causes the program to skip the rest of the loop in the
current iteration as if the end of the statement block had been reached,
causing it to jump to the start of the following iteration.
// continue loop example
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Homework
Use both for and while loop to solve the following problems:
1-Write a program to print all even numbers between 1 and 100.
2-Write a program to find sum of odd numbers between 1 and 50.
3-Write a program to input a number and then check the number is
prime or not.