while and for loop in C++
DEPARTMENT OF
GEOPHYSICS
Under the Supervision KURUKSHETRA
of : UNIVERSITY
KURUKSHETRA Presented by:
Dr. Atul Jhajhria
Assistant Professor
Ritik Kumar
Department of Geophysics GP-26, Semester 2nd
Kurukshetra University M.Sc.(Tech.) Applied
Presentation
Outline
Introduction to loop
Types of loop
while loop
do while loop
for loop
References
LOOP IN C++
A LOOP IS USED TO REPEAT A BLOCK OF
CODE UNTIL THE SPECIFIED CONDITION IS
MET.
LOOP IS USED TO EXECUTE A GROUP OF
INSTRUCTIONS OR A BLOCK OF CODE
MULTIPLE TIMES, WITHOUT WRITING IT
REPEATEDLY.
TYPES OF LOOPS
There are three types of loops
in C++.
1.while loop
2.do while loop
3.for loop
while loop
while loop is an entry control function
its function is simply to repeat statement while expression is true.
Syntax
while(condition)
{
statement…..
}
Flowchart for while loop
Print 1 to 10 numbers using while
loop
#include <iostream>
int main()
{
int num = 1;
while (num <= 10)
{
std::cout << "\n" << num;
num++;
}
Program to print one statement
for n time using while loop:
#include <iostream>
using namespace std;
int main()
{
int n, i = 1;
cout << "Enter number:" << endl;
cin >> n;
cout << endl;
while (i <= n)
{
cout << "Hello C++" << endl;
i++;
}
return 0;
}
do while loop
do-while is an exit control loop.
Based on a condition, the control is transferred
back to a particular point in the program
A do...while loop is similar to a while loop,
except the fact that it is guaranteed to execute
at least one time
Syntax
. do
{
statement(s);
}
while( condition );
Print 1 to 10 numbers using do-while
loop
#include <iostream>
int main()
{
int num = 1;
{
do
{
std::cout << "\n" << num;
num++;
}
while (num <= 10);
}
for loop
for loop is an Entry control loop when action
is to be repeated for a predetermined number
of times.
Normally used for counting
Four parts – Initialise expression – Test
expression – Body – Increment expression
Syntax
for(initialization;condition;increment)
{
statements
}
C++ program to display a text 5
time
// C++ Program to display a text 5 times
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << “I know you are hungry " << endl;
}
return 0;
}
Print 1 to 10 numbers using for loop
#include <iostream>
using namespace std;
int main ()
{
cout<<"The first 10 numbers are as follows: n";
for (int i=1;i<=10;i++)
{
cout<<i<<endl;
}
return 0;
THANKYOU