CONTROL STRUCTURES
do..while loop:
This construct executes the body of the loop exactly once, and then evaluates the test condition. If the loop condition is true, the execution is repeated, otherwise the loop ends and control is passed to the statement following the loops.
syn: do
{
stmt(s);
}
while(boolean_expression);
|
#include<iostream.h> #include<conio.h> void main() { char ch,ans; int asci; clrscr(); do { cout<<"\n\n\n\n\n\t\t\t Enter an alphabet: "; cin>>ch; asci=ch; cout<<"\n\t\t\tThe ASCII value of "<<ch<<" is "<<asci<<endl; getch(); clrscr(); cout<<"\n\t\t Do you want to continue... (y/n): "; cin>>ans; clrscr(); } while(ans=='y' || ans=='Y'); cout<<"\n\n\t\t\t \"THANKS FOR USING\""; getch(); } |
while loop:
The while loop is a looping construct, which executes until the evaluating condition becomes false. The evaluating condition has to be a logical expression and must return a true or false value. The variable that is checked in the Boolean expression is called the loop control variable. Sometimes, there may not be any loop control variable, for example, while(1).
syn:
while(boolean_expression)
{
statement(s);
}
for loop:
The for statement consists of the keyword for, followed by three expressions in parenthesis separated by semicolons. They are the initialization expression, test expression and the increment/decrement expression.
syn: for(initialization; test_expression; iteration)
{
statement(s);
}
// EX-4: PGM TO PRINT ASCII VALUE OF 20 CHAR. USING for LOOP |
#include<iostream.h> #include<conio.h> void main() { char ch='a'; int i, asci; clrscr(); for(i=0;i<20;i++) { asci=ch; cout<<"\n\t The ASCII value of "<<ch<<" is "<<asci; ch++; } getch(); } |
switch..case statement:
C++ has a built-in multiple branch selection statement called switch. This statement successively tests the value of an expression against a list of constants. When a match is found, the statements associated with that condition are executed.
// EX-5: PGM ILLUSTRATES while, do..while, for AND switch STATEMENT |
#include<dos.h> #include<iostream.h> #include<conio.h> void main() { int n1,n2,x; char ch='y'; clrscr(); while(ch=='y' || ch=='Y') { cout<<"\n\t Enter the first number: "; cin>>n1; do { cout<<"\n\t Enter the second number (It should less than first no.): "; cin>>n2; }while(n2>=n1); cout<<"\n\t\t 1. Add two nos."; cout<<"\n\t\t 2. Subtract two nos."; cout<<"\n\t\t 3. Multiply two nos."; cout<<"\n\t\t 4. Divide two nos."; cout<<"\n\n\t\t Enter your choice : "; cin>>x; clrscr(); gotoxy(30,12); switch(x) { case 1: cout<<" SUM = "<<n1+n2; break; case 2: cout<<" DIFFERENCE = "<<n1-n2; break; case 3: cout<<" PRODUCT = "<<n1*n2; break; case 4: cout<<" QUOTIENT = "<<n1/n2; break; default : for(int i=0;i<5;i++) { clrscr(); delay(200); gotoxy(26,12); cout<<"INVALID CHOICE !!! "; delay(300); } break; } cout<<"\n\n\t\t Do you want to continue..(y/n): "; cin>>ch; clrscr(); } } |