Conditional Statements And Loops In C++

 

Conditional Statements And Loops In C++

A program may consist of a lot of statements in which either we have to choose some specific statements or check some condition repeatedly. So we now introduce the concept of conditional statements(if & else) and loops(for,while,do while).

Conditional structure: if and else

given below is an example which will help us in better understanding of the
if-else construct.

int main()
{
if(x%2==0) // check condition
cout<< “x is even”; // statement 1 is executed
else
cout<< “x is odd” ; // statement 2 is executed
return 0;
}
if a case occurs in which there can be more than two possible results then,

int main()
{
if( x >0)
cout<<” x is positive”
else if(x==0)
cout<” x is zero”
else
cout<<” x is negative”
return 0;
}

Loops In C++(Iteration Structures)

In certain cases we need to check the condition and execute the statements repeatedly. in such cases we use the concept of loops.

The while loop in C++

The loop does not stop unless the condition is met. Here is a program to check whether a no. is palindrome or not.
int main()
{
x=5
while(x!=0) // condition
x–;
cout<< x << ” , ” ; //output of the program is 4,3,2,1,0
return 0;
}

The do while loop C++

The format is : do(statement) while(condition)
atleast once the execution takes place even if the condition is not fulfilled.
void main()
{
{x=5
do{
x–;
cout<< x << ” , ” ;
}while(x!=0) // output of the program is (4,3,2,1,0,-1)
}
here the loop is executed even the 6th time when the condition is not fulfilled whereas in case of while, loop is executed 5 times.

The for loop in C++

Format of for loop is: (initialization,condition,increment)
the value is initialise once and for every true condition statements are executed and then increment occurs.
Here is illustration below.

int main()
{
for ( i=5 ; i>0 ;i–)
cout<< x<< ” , ” ; // output of the program is (5,4,3,2,1)
return 0;
}
Despite all of these above conditional and iterational structures we have some jump statements which change the execution order of loops. These are known as jump statements.

Break Statement in C++

Using this statement we can leave the loop. It is used to end infinite loops. for example

int main()
{
for( i=10 ; i>=5 ; i–)
cout << i << ” , ” ;
if(i==6)
cout<<“stop” // output of the program is (10,9,8,7,6,stop)
return 0;
}

Continue Statement in C++

int main()
{
for( i=10 ; i >=5; i–)
if(i==6)
continue;
cout<< i << ” , ” ; // output of the program is (10,9,8,7,5)
return 0;
}

Switch Case C++

It is used to select the paticular statement. It is similar to if, else if condition.

int main()
{
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}
return 0;
}
as soon as any one of the condition is met, break statement is executed and program jumps to the end.

 

css.php