You are on page 1of 33

ITERATION STRUCTURE'S

(LOOP)

PROGRAMMING LOGIC AND DESIGN


Computer Engineering Department

MARK JONIEL M. LOPEZ,CpE


(LOOP)
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
Loops can execute a block of code as
long as a specified condition is reached.
Loops are handy because they save time,
reduce errors, and they make code more
readable.
Loops have as purpose to repeat a
statement a certain number of times or
while a condition is fulfilled.
LOOP TYPE AND DESCRIPTION

WHILE LOOP
Repeats a statement or group of statements while
a given condition is true. It tests the condition
before executing the loop body
The syntax of a while loop in C++ is −

while(condition)
{
statement(s);

}
Here, key point of the while loop is that the loop might not ever run.
When the condition is tested and the result is false, the loop body will
be skipped and the first statement after the while loop will be executed
EXAMPLE – WHILE LOOP
Example When the code is compiled and executed, it
#include <iostream>
using namespace std; produces the following result −

int main () {
// Local variable declaration:
value of a: 10
int a = 10; value of a: 11
value of a: 12
// while loop execution
value of a: 13
while( a < 20 ) value of a: 14
{
value of a: 15
cout << "value of a: " << a << endl;
a++; value of a: 16
} value of a: 17
return 0;
value of a: 18
} value of a: 19
LOOP TYPE AND DESCRIPTION

DO WHILE LOOP
Like a ‘while’ statement, except that it tests the condition at
the end of the loop body.
The syntax of a do...while loop in C++ is −

do {
statement(s);
}
while( condition );

Notice that the conditional expression appears at the end of the loop, so
the statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and
the statement(s) in the loop execute again. This process repeats until
the given condition becomes false
EXAMPLE – DO WHILE LOOP
#include <iostream> When the above code is compiled and executed, it
produces the following result −
using namespace std;
int main () {
value of a: 10
// Local variable declaration:
value of a: 11
int a = 10; value of a: 12
// do loop execution value of a: 13
do value of a: 14
{ value of a: 15

cout << "value of a: " << a << endl; value of a: 16

a = a + 1; value of a: 17
value of a: 18
} while( a < 20 );
value of a: 19
return 0;
}
LOOP TYPE AND DESCRIPTION
FOR LOOP
Execute a sequence of statements multiple
times and abbreviates the code that manages
the loop variable.
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.
The syntax of a for loop in C++ is −
for ( initialize; condition; increment )
{
statement(s);
}
EXAMPLE – FOR LOOP
#include <iostream> When the above code is compiled and
using namespace std; executed, it produces the following result −

int main () value of a: 10


{ value of a: 11
// for loop execution value of a: 12
for( int a = 10; a < 20; a = a + 1 ) value of a: 13
{
value of a: 14
cout << "value of a: " << a << endl;
value of a: 15
}
value of a: 16
value of a: 17
return 0;
value of a: 18
}
value of a: 19
LOOP CONTROL STATEMENTS
LOOP CONTROL STATEMENTS
Loop control statements change execution from its normal
sequence. When execution leaves a scope, all automatic
objects that were created in that scope are destroyed.
LOOP CONTROL STATEMENTS
B R E A K S TAT E M E N T
Terminates
the loop or switch statement and
transfers execution to the
statement immediately following
the loop or switch.
EXAMPLE – BREAK STATEMENT
#include <iostream>
using namespace std;
When the code is compiled and executed,
it produces the following result −
int main ()
{ value of a: 10
int a = 10; value of a: 11
do value of a: 12
{
cout << "value of a: " << a << endl; value of a: 13
a = a + 1;
if( a > 15)
value of a: 14
{
// terminate the loop
value of a: 15
break;
}
} while( a < 20 );
return 0;
}
LOOP CONTROL STATEMENTS
C O N T I N U E S TAT E M E N T
Causes the loop to skip the remainder of its
body and immediately retest its condition
prior to reiterating.
EXAMPLE – CONTINUE STATEMENT
#include <iostream>
using namespace std; When the code is compiled and executed,
int main () it produces the following result −
{
// Local variable declaration:
value of a: 10
int a = 10;
value of a: 11
// do loop execution
do
value of a: 12
{
if( a == 15)
value of a: 13
{
// skip the iteration.
value of a: 14
a = a + 1;
continue;
} value of a: 16
cout << "value of a: " << a << endl;
a = a + 1; value of a: 17
}
while( a < 20 ); value of a: 18
return 0; value of a: 19
}
LOOP CONTROL STATEMENTS
G O T O S TAT E M E N T
Transfers control to the labeled statement. Though it is
not advised to use goto statement in your program.
A goto statement provides an unconditional jump
from the goto to a labeled statement in the same
function.
NOTE − Use of goto statement is highly discouraged
because it makes difficult to trace the control flow of a
program, making the program hard to understand and
hard to modify. Any program that uses a goto can be
rewritten so that it doesn't need the goto.
EXAMPLE – GOTO STATEMENT
Live Demo
#include <iostream>
When the code is compiled and executed, it
using namespace std; produces the following result −
int main () { value of a: 10
// Local variable declaration:
int a = 10; value of a: 11
// do loop execution value of a: 12
LOOP:do {
if( a == 15) { value of a: 13
// skip the iteration.
a = a + 1; value of a: 14
goto LOOP;
} value of a: 16
cout << "value of a: " << a << endl;
a = a + 1;
value of a: 17
}
while( a < 20 );
value of a: 18
return 0;
value of a: 19
}
SWITCH CASE STATEMENT
SWITCH CASE STATEMENT
switch statement allows a variable to be tested for equality
against a list of values. Each value is called a case, and the
variable being switched on is checked for each case.

The syntax for a switch statement in C++ is as follows −

switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional

// you can have any number of case statements.


default : //Optional
statement(s);
}
SWITCH CASE STATEMENT
The following rules apply to a switch statement −

The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a
single conversion function to an integral or enumerated type.

You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is
reached.

When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch
statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a
break is reached.

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used
for performing a task when none of the cases is true. No break is needed in the default case.
SWITCH CASE STATEMENT
#include <iostream>
using namespace std;

int main () {
// local variable declaration:
char grade = 'D';

switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;

return 0;
}
ARRAY
An array is a series of elements of the same type placed in
contiguous memory locations that can be individually
referenced by adding an index to a unique identifier.

An array is a contiguous series of element of the same type


where each element can be accessed by a name and an index.

To declare an array in C++, the programmer specifies the type


of the elements and the number of elements required by an
array as follows −

type arrayName [ arraySize ];


ARRAY
/* Example Program For Single Dimensional Array In C++ Programming Language

#include <iostream>

using namespace std;

int main()
{

int value[6] = {5, 10, 15, 20, 25, 30};

cout<<"Single Dimensional Array In C++ Example Program\n";

for (int i=0;i<6;i++)


{
cout<<"Position : "<<i<<" , Value : "<< value[i]<<" \n";
}

return 0;
}
ARRAY
#include <iostream>
using namespace std;

int main()
{
int arr[5];

for (int i= 0; i <5; i++)


{
cin >> arr[i];
}

cout << "you enter the values of the array " << endl;
for (int i=0; i<5; i++)
{
cout << arr[i] <<endl;
}
cout << "\nthese are the final one dimensional Array";

return 0;
}
MULTIDIMENSIONAL ARRAY
Multidimensional Arrays in C++
In C++, we can define multidimensional arrays in simple words as array of arrays.

Data in multidimensional arrays are stored in tabular form (in row major order).

General form of declaring N-dimensional arrays:


data_type array_name[size1][size2]....[sizeN];

data_type: Type of data to be stored in the array. Here data_type is valid C++ data type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions
MULTIDIMENSIONAL ARRAY
Examples:

Two dimensional array:


int two_d[10][20];

Three dimensional array:


int three_d[10][20][30];

Size of multidimensional arrays

Total number of elements that can be stored in a multidimensional array can be calculated by multiplying the
size of all the dimensions.

For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
MULTIDIMENSIONAL ARRAY
Two-Dimensional Array
-the simplest form of a multidimensional array. We can see a two – dimensional array as an array of one –
dimensional array for easier understanding.

The basic form of declaring a two-dimensional array of size x, y:


Syntax:
data_type array_name[x][y];
data_type: Type of data to be stored. Valid /C++ data type.

We can declare a two dimensional integer array say ‘x’ of size 10,20 as:
int x[10][20];
Elements in two-dimensional arrays are commonly referred by x[i][j] where i is the row number and ‘j’ is the
column number.
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges
from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3
columns is shown below:
MULTIDIMENSIONAL ARRAY
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges
from 0 to (x-1) and column number ranges from 0 to (y-1).

A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below:
MULTIDIMENSIONAL ARRAY
Initializing Two – Dimensional Arrays
There are two ways in which a Two-Dimensional array can be initialized.

First Method:
int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

The above array have 3 rows and 4 columns. The elements in the braces from left to right are stored in the table
also from left to right. The elements will be filled in the array in the order, first 4 elements from the left in first
row, next 4 elements in second row and so on.

Better Method:
int x[3][4] = { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} };

This type of initialization make use of nested braces. Each set of inner braces represents one row. In the above
example there are total three rows so there are three sets of inner braces.

Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are accessed using the
row indexes and column indexes.
MULTIDIMENSIONAL ARRAY

NOTE:

To output all the elements of a Two-Dimensional array we


can use nested for loops. We will require two for loops. One
to traverse the rows and another to traverse columns.
MULTIDIMENSIONAL ARRAY
// C++ Program to print the elements of a Two-Dimensional array
#include<iostream>
using namespace std;
Output:
int main()
{
// an array with 3 rows and 2 columns.
Element at x[0][0]: 0
int x[3][2] = {{0,1}, {2,3}, {4,5}}; Element at x[0][1]: 1
Element at x[1][0]: 2
// output each array element's value
for (int i = 0; i < 3; i++)
Element at x[1][1]: 3
{ Element at x[2][0]: 4
for (int j = 0; j < 2; j++) Element at x[2][1]: 5
{
cout << "Element at x[" << i
<< "][" << j << "]: ";
cout << x[i][j]<<endl;
}
}
return 0;
}
MULTIDIMENSIONAL ARRAY
//one by one column for given row// all cells for given row
#include<iostream>
cout << " Enter values for [" <<i<<"]["<<j<<" :";
using namespace std; cin >> ARRAY_2D[i][j];
}
int main ()
{ }
// declaration ofVariables
int row, col, I, j; }
int ARRAY_2D[10][10]; // printing given array in table format

cout<< "enter the number of rows :"; cout << endl <<endl << "\t\tYou have entered" <<endl <<endl;
cin >> row; for (i=0; i<row; i++)
{
cout << "enter the number of columns :"; for (j=0; j<col; j++)
cin >> col; {
cout << "\t "<<ARRAY_2D[i][j];
// taking inputs for array........ }
for (i=0; i<row; i++) cout << endl;
{ }
// one by one row (ROW MAJOR FORM)
for (j=0; j<col; j++) return 0;
{ }
MULTIDIMENSIONAL ARRAY
#include<iostream> //Continuation of the program
using namespace std;
// printing the given array in the format
int main ()
{
cout <<endl<<endl<<"\tYou have Entered
// declaration of variables
int row, col,i,j;
"<<endl<<endl;
int arr[10][10]; for (i=0; i<row; i++)
{
cout << "Enter the number of rows : "; for(j=0; j<col; j++)
cin >> row; {
cout << "Enter the number of column : "; cout <<"\t"<<arr[i][j];
cin >> col;
}
cout<<endl;
//taking inputs for array
}
for (i = 0; i <row; i++)
Return 0;
{
}
for(j = 0; j < col; j++)
{
cout << " enter the values for ["<<i<<"]["<<j<<"]:";
cin >> arr[i][j];
}
}

You might also like