* Programming
Fundamentals
Lecture 04
Instructor: Rao Umer Farooq
*Programming Fundamentals
Loop:
Write a program to print word Write a program to print numbers
“programming” 10 times. from 1-10
main() main()
{ {
cout<< “programming” << endl; cout<< “1” << endl;
cout<< “programming” << endl; cout<< “2” << endl;
cout<< “programming” << endl; cout<< “3” << endl;
cout<< “programming” << endl; cout<< “4” << endl;
cout<< “programming” << endl; cout<< “5” << endl;
cout<< “programming” << endl; cout<< “6” << endl;
cout<< “programming” << endl; cout<< “ 7” << endl;
cout<< “programming” << endl; cout<< “8” << endl;
cout<< “programming” << endl; cout<< “9” << endl;
cout<< “programming” << endl; cout<< “10” << endl;
*Programming Fundamentals
Loop:
*A loop statement allows us to execute a statement or group
of statements multiple times.
*loops are used to repeat a block of code.
Advantages of Loop
*No need to write the same code again and again, if you want
something to happen again and again.
*Helps to reduce many lines of codes.
*Reduce the complexity of program.
*Programming Fundamentals
Types of Loop
* There are four major type of loops (in some literature three types)
a) While loop
Entry control loops
b) For loop
c) Do while loop Exit control loop
d) Nested loop
*Programming Fundamentals
While Loop
*While loop is a most basic loop in C++
*while loop has one control condition, and executes as long
the condition is true.
*The condition of the loop is tested before the body of the
loop is executed, hence it is called an entry-controlled loop.
*Programming Fundamentals
While Loop syntax
*Programming Fundamentals
While Loop
Write a program using while loop that display word “programming”
10 times.
main()
{
int i =1;
while ( i<=10 )
{
cout << “programming” << endl;
i ++;
}
cout<< “program end”
}
*Programming Fundamentals
While Loop
* Write a program using while loop that display numbers from 1 to 20.
* Write a program using while loop that display numbers from 20 to 1.
main() main()
{ {
int i =1; int i =20;
while ( i<=20 ) while ( i>=1 )
{ {
cout << i << endl; cout << i << endl;
i ++; i --;
} }
cout<< “program end” cout<< “program end”
} }