Loop Notes
Loop Notes
Repetition (Loops)
int x = 3;
while (x>0) {
cout<<"x ="<<x;
x--;
}
First time: x = 0;
Second time: x = 1;
Third time: x = 2;
Fourth time: x = 3; (don’t execute the body)
ICT172: Principles to Programming
Lecture Notes 18
for <==> while
for (initialization; loop_condition; update_statement)
{
statements;
}
equals
Initialization;
while (loop_condition)
{
Statement;
Update statement;
}
ICT172: Principles to Programming
Lecture Notes 19
Example
• Assume that the following code is correctly
inserted into a program, what is the final value
of s?
int s = 0;
for (int i = 1; i < 5; i++)
{
s = 2 * s + i;
}
cout << s << endl;
ICT172: Principles to Programming
Lecture Notes 20
Factorial program
int main()
{
int number= 4;
int answer;
int count;
answer= 1;
count= number;
while (count >= 0) {
answer= answer* count;
count--;
}
cout<<answer<<endl;
return 0;
}
ICT172: Principles to Programming
Lecture Notes 21
Attendance Quiz
int sum = 0;
for (int i = 1; i <= 10; ++i) {
sum += i;
cout << "Sum after adding " << i << " is: " <<
sum << endl;
}
int sum = 0;
for (int i = 1; i <= 10; ++i) {
sum += i;
cout << "Sum after adding " << i << " is: " <<
sum << endl;
}
int i = 1;
while (i <= 10) {
if (i % 2 == 0) {
cout << i << " is even" << endl;
} else {
cout << i << " is odd" << endl;
}
++i;
}
ICT172: Principles to Programming
Lecture Notes 25
Quick Quiz: What will be the output when i = 10?
int i = 1;
while (i <= 10) {
if (i % 2 == 0) {
cout << i << " is even" << endl;
} else {
cout << i << " is odd" << endl;
}
++i;
}
ICT172: Principles to Programming
Lecture Notes 26
Quick Quiz: What will be the output for i = 3 in the given code snippet?
int i = 1;
while (i <= 10) {
if (i % 2 == 0) {
cout << i << " is even" << endl;
} else {
cout << i << " is odd" << endl;
}
++i;
}
ICT172: Principles to Programming
Lecture Notes 27
Class Exercise
• Using the concept of loops, write a C++
program that takes the name of a friend and
prints it 15 times on the screen.