loop and one dimensional array in cpp

loop:

it is a process of repeating or iterating a block of code until a condition becomes false.


There are different types of loops:

entry controlled loop: 

loops where conditions are checked before the execution of the specified block of code.

entry controlled loops are:

1. for loop

2. while loop


exit controlled loop : 

loops where conditions are checked after the execution of the specified block of code.

exit controlled loops are:

1. do-while loop




for loop

for loop is used to repeat a block of code with a limit.

for (starting;condition;increment/decrement)

{

//code to repeat

}

note:

example: print from 5 to 0

starting:

            int i=5;

condition:

              i>=0

decrement: subtract a value by one

            i--;


code:

for(int i=5;i>=0;i--)

{

cout<<i<<endl;

}

example: print from 0 to 4

starting:

            int j=0;

condition:

              j<5

increment:add a value by one

            j++;


code:

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

{

cout<<j<<endl;

}


while loop

while loop is used to repeat or iterate a block of code until a condition becomes false.

syntax:

while(condition)

{

//code to repeat

}


int i=7;

while(i<9)

{

cout<<i<<endl;

i++;

}

int j=9;

while(j>6)

{

cout<<j<<endl;

j--;

}


exit controlled loop

========================

1. it is a loop that is used when there is a need to execute a block of code at least one time.

2. do-while loop firstly, executes the block of code and then checks the given condition.

do-while loop

do

{

//code to repeat

}while(condition);


example:

print from 8 to 49

int i=8;

do

{

cout<<i<<endl;

i++;

}while(i<50);

print from 49 to 8

int j=49;

do

{

cout<<j<<endl;

j--;

}while(j<8);


array

1. it is used to hold or store multiple values.

2. it can hold any single type of value.

3. can hold a fixed amount of values.

4. arrays are indexed.

for example:

           the first element is in the 0 position.

           the second element is in the 1 position and so on.


syntax:

data_type var_name[number_of_elements];


example:

#include<iostream>

using namespace std;

int main()

{

int nums[9];

char data[6];

float heights[8];

string names[89];

return 0;

}



how to initialize an array


or


how to store values in an array


manual

1. one-dimensional array


example:

float heights[7]={5.4,3.6,7.8,2.4,6.5,7.8,9.7};


how to single element of an array

#include<iostream>

using namespace std;

int main()

{

int ages[9]={4,6,3,7,9,4,7,9,3}

        cout<<ages[0]; //how to print first element

        cout<<ages[1]; //how to print second element

        cout<<ages[8]; //how to print last element

return 0;

}


how to print all elements of an array?

#include<iostream>

using namespace std;

int main()

{

int ages[9]={4,6,3,7,9,4,7,9,3}

        for(int index=0;index<9;index++)//

        {

            cout<<ages[index]<<endl;

        }

return 0;

}

0 Comments