Saturday, May 3, 2014

[Tutorial C++] Basics of Programming Part 5

Loops
 
 
While

Definition

While statement is known as loop or iterated structure because it keeps on executing a code written inside it till the condition given to it does not becomes true.

Syntax

while(condition){

//code to be iterated
}


Example

#include<iostream>

#include<conio.h>

void main(){

int a=0;

while(a<10)// condition is that while a<10 perform the below code, something must be done to  //change the condition to false otherwise the loop will go on endlessly this is the reason why

//a is incremented inside the code

{

cout<<"Hello"<<endl;

a++;

}

getch();

}

 
Do-while loop

Definition
 
Do-while is also an iteration statement or loop but it performs the code first then checks the condition this can be sometimes an advantage or disadvantage.

Syntax

do{

//code to be iterated

}

while(condition);


Example

#include<iostream>

#include<conio.h>

void main(){

int a=0;

do{

cout<<"Hello"<<endl;

a++;

}

while(a<0); //same as while except code is performed first then condition is checked 

//so that loop should 

getch();

}
 
For loop

Definition

For loop keeps on iterating itself given an initial value, condition and increment value.

Syntax

for(initial value; condition; increment value)

{

//code to be iterated

}


Example

#include<iostream>//Declaring header files

#include<conio.h>

void main(){

int a[5];  //Declaring an array having 5 values

cout<<"Enter the values in the array:"<<endl; //Displaying a message

for(int i=0; i<5; i++)//for loop which starts with an initial value of 0,

//condition is i<5 and while condition is true increment 1 to i

{

cin>>a[i];

}

cout<<"Displaying the values stored in array in reversed order:"<<endl;

for(int i=4; i>=0; i--)//for loop which starts with an initial value of 4,

//condition is i>=5 and while condition is true decrement 1 to i

{

cout<<a[i]<<endl;

}

getch();

}



*iteration:-the repetition of a process


Widgets

 

Copyright @ 2014 CPP Fuzz.