Loops

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Lecture 7

Loops

 There may be a situation, when you need to execute a block of code


several number of times. In general, statements are executed
sequentially: The first statement in a function is executed first, followed
by the second, and so on.
 Programming languages provide various control structures that allow for
more complicated execution paths.
 A loop statement allows us to execute a statement or group of
statements multiple times and following is the general from of a loop
statement in most of the programming languages

Loop Types:
C++ programming language provides the following type of loops to handle
looping requirements.

Loop Type Descryption


for loop The initialization, condition and increment/decrement all
put together. Initialization will be done once at the
beginning of loop. Then, the condition is checked by the
compiler. If the condition is false, for loop is terminated.
But, if condition is true then, the statements are executed
until condition is false.

while Loop Repeats a statement or group of statements while given


condition is true. It tests the condition before executing
the loop body.
do...while loop Like a ‘while’ statement, except that it tests the condition
at the end of the loop body.
nested loops You can use one or more loop inside any another ‘while’,
‘for’ or ‘do..while’ loop.
For Loop: A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of times.

Syntax of For Loop

for ( initialization ; condition; increment )


{
Statements ;
}

Here is the flow of control in a for loop:


 The ( initialization step is executed first, and only once. This step allows
you to declare and initialize any loop control variables. You are not
required to put a statement here, as long as a semicolon appears.
 Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of
control jumps to the next statement just after the for loop.
 After the body of the for loop executes, the flow of control jumps back up
to the increment statement. This statement allows you to update any
loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.
 After the condition becomes false, the for loop terminates.
Example:

#include<iostream>

using namespace std;

void main()
{
int a, num;
cout << "Enter any number : ";
cin >> num;
for (a=1;a<=num;a++)
cout << "\nHello...!!"; }

The output:

Enter any number : 5


Hello...!!
Hello...!!
Hello...!!
Hello...!!
Hello...!!
-For Statement:
for(exp1 ; exp2 ; exp3)
When:
exp1: First counter
exp2: End counter
exp3: Increment or Decrement Counter
Example:
for(i=1;i<=10;i++) cout<<i; // = 123…910
for(i=10;i>=1;i--) cout<<i; // = 1098…321
for(i=2;i<=10;i+=2) cout<<i; // = 246810
:‫ماهو الفرق بين السؤالين التاليين‬
‫)؟‬10-1( ‫حساب مجموع االعداد بين‬
‫ اعداد؟‬10 ‫وحساب مجموع‬
‫الفرق سيكون بين المعلوم والمجهول‬

)‫)؟ (معلوم‬10-1( ‫حساب مجموع االعداد بين‬

for(i=1;i<=10;i++)
s+=i;
)‫ اعداد؟ (مجهول‬10 ‫حساب مجموع‬

for(i=1;i<=10;i++)
{ cin>>x;
s+=x; }

EX// W.P. to read 10 integer number and find biggest?


#include<iostream>
using namespace std;
int main()
{
int i,x,larg=0;
cin>>x;
larg=x;
for(i=1;i<=9;i++)
{
cin>>x;
if(x>larg) larg=x;
}
cout<<"larg="<<larg;
return 0;
}
EX// W.P. to find factorial x! ?
#include<iostream>
using namespace std;
int main()
{
int i,x,f=1;
cin>>x;
for(i=1;i<=x;i++)
f*=i;
cout<<"factorial x="<<f;
return 0;
}
y
EX// W.P. to find power x ?
(without using pow function)
#include<iostream>
using namespace std;
int main()
{
int i,x,y,p=1;
cin>>x>>y;
for(i=1;i<=y;i++)
p*=x;
cout<<"power="<<p;
return 0;
}
While Loop
While loop is also called entry control loop because, in while loop, compiler
will 1st check the condition, whether it is true or false, if condition is true
then execute the statements.

Syntax of While Loop

while ( condition )
{
Statmentes;
--- - -- - -- -- - -
}

 Here, statement(s) may be a single statement or a block of


statements.

 The condition may be any expression, and true is any non-zero


value. The loop iterates while the condition is true. When the
condition becomes false, program control passes to the line
immediately following the loop.


 EX/ print even numbers between (4-100)?

 using (For, while, do—while) statement

for (i=4;i<=100;i+=2) 

cout<<i; // 4 6 8 … 98 100 by for 

------------------------------------------------------------------------
i=4;
while (i<=100)
{ cout<<i;
i+=2; } // 4 6 8 … 98 100 by while
---------------------------------------------------------------------------
i=4;
do
{ cout<<i;
i+=2;
} // 4 6 8 … 98 100 by do-while
while (i<=100);
‫اكتب برنامج لحساب مجموع قائمة من االرقام تنتهي بالرقم صفر؟‬/‫س‬
Q// Write a program to calculate the sum of a list of numbers ending the
number zero?
#include<iostream>
using namespace std;
int main()
{
int x,s=0;
Cin>>x;
While(x!=0)
{s+=x; cin>>x; }
cout<<s;
return 0;}
#include<iostream>
using namespace std;
int main()
{
int x,s=0;
do
{cin>>x;
s+=x;} while(x!=0);
cout<<s;
return 0;
}
‫اذا كان عدد اولي او ال؟‬X ‫اكتب برنامج لفحص قيمة‬/‫س‬
Q / Write a program to check X value if the number of first or not?
#include<iostream>
using namespace std;
int main()
{
int x,flag,i; flag=0; cin>>x;
for (i=2;i<x;i++)
if(x%i==0) flag=1;
if (flag==0)
cout<<"x is prime";
else
cout<<"x is NOT prime";
return 0; }

‫ ارقام مختلفة؟‬10 ‫ من‬5 ‫ و‬4 ‫اكتب برنامج لحساب مجموع االرقام الصحيحة التي تقبل القسمة على‬/‫س‬
Q1//write a program to compute the sum of the integers that divisible by 4 and
5 from 10 different integers?
‫اكتب برنامج لحساب مجموع االرقام الموجبة لقائمة من االرقام تنتهي بالرقم صفر؟‬/‫س‬
Q2// Write a program to calculate the sum of the positive numbers to the list of
numbers ending the number zero?
‫الحلقات او التكرارات‬- Loops OR Iterations :
Removing all the expressions gives us an infinite loop. This loop's condition is
assumed to be always true:
for ( ; ; ) // infinity loop
something;
&&&&&&&&&&&&&&&&&&&&&&&&&
int i,j,n=6;
for (i = 0, j = 0; i + j < n; ++i, ++j)
cout << '(' << i << ',' << j << ")\n";

Output :
/-----------
(0,0)
(1,1)
(2,2)
‫الحلقات او التكرارات‬- Loops OR Iterations :
Because loops are statements, they can appear inside other loops. In other
words, loops can be nested. For example,
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << "(" << i << "," << j << ")\n";

Output :
-----------
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
‫الحلقات او التكرارات‬- Loops OR Iterations :
(3,3)
Q//write a program used nested loop to calculate "X" ,where:- X= 1!+ 3!+ 5!+
7!+9!
#include<iostream>
using namespace std;
int main()
{ int i,j,f=1,x=0;
for(i=1;i<=9;i+=2)
{ f=1;
for(j=1;j<=i;j++)
f*=j;
cout<<"factorial " <<i<<"= "<<f<<endl;
x+=f; }
cout<<"Sum ="<<x<<endl;
return 0; }
‫الحلقات او التكرارات‬- Loops OR Iterations :
Q//what’s output:
#include<iostream>
using namespace std;
int main() Output :
{ int i,j;
for(i=1;i<=4;i++)
{
-----------
for(j=1;j<=4;j++)
cout<<"*";
****
cout<<endl;
} ****
return 0;
} ****
****
‫الحلقات او التكرارات‬- Loops OR Iterations :

Output :
Q//what’s output:
#include<iostream>
using namespace std;
-----------
int main()
{ int i,j; *
for(i=1;i<=4;i++)
{ **
for(j=1;j<=i;j++)
cout<<"*";
cout<<endl;
***
}
return 0; ****
}
Example

#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}return o;}

The output:

value of a: 10
value of a: 11
‫يقوم هذا البرنامج بطباعة قيمة‬
value of a: 12
‫المتغير‬a ( ‫( طالما الشرط‬
value of a: 13 a<20 ‫ متحقق او‬TRUE
.
.
value of a: 19
Homework: trace the following c++ cods and Find the final output for
these cods :

#include <iostream>

using namespace std;

int main()
{
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;

for (int i = 1; i <= n; ++i) {


sum += i;
}
cout << "Sum = " << sum;
}
#include <iostream>

using namespace std;


int main()
{
int n = 10 ;
while (n > 0(
{
cout << n << "," ;
-- n ;
} cout << "End of program \n";
return 0;}
Exercises
1. Write C++ program to find the summation of the following series:
Sum= 1+3+5+7+ . . . . . . . . +99
2. Write C++ program to read 10 integer numbers, and find the sum
of the positive numbers only.
3. Write C++ program to find the summation of the following series
:

4. Write C++ program to find the summation of students marks,


and its average, assume the student have 8 marks.
‫‪- Loops OR Iterations :‬الحلقات او التكرارات‬
The break Statement
A break statement may appear inside a loop (while, do, or for) or a switch
statement. It causes a jump out of these constructs, and hence terminates them.
EX// read positive No. and terminate by zero?
for( ; ; ) //infinity loop
{ cin >> num;
if (num < 0) continue;
If (num==0) break;
// process num here...
}

You might also like