C++ Conditional Statements: Prepared By: Engr. Yolly D. Austria
C++ Conditional Statements: Prepared By: Engr. Yolly D. Austria
Introduction
The program-control statements are the
essence of any computer language because
they govern the flow of program execution.
They modify the order of statement
execution. This can cause other program
statements to execute multiple times or not
execute at all, depending on the
circumstances.
if Statement
if Statement
Syntax:
if (expression)
single statement;
if (expression)
{
statement1;
statement2; // and so on..
statement_last;
}
Sample Program 1:
#include <iostream.h>
#include <conio.h>
int main ()
{
int a;
cout<<\n<< Enter a number : ;
cin>>a;
if(a<0)
cout<<The number is negative.;
else if(a>0)
cout<<The number is positive.;
else
cout<<The number is zero;
return 0;
}
Sample Program 2:
#include <iostream.h>
int main()
{
int number;
cout << "Enter a number between 1 and 99: ";
cin >> number;
if (number > 0 && number < 100 )
{
if (number < 10)
cout << "One digit number\n";
else
cout << "Two digit number\n";
}
else
cout << "Number not in range\n";
return 0;
}
switch Statement
Syntax:
switch (expression)
{
case const_expr_1:
statements 1
break;
case const_expr_2:
statements 2
break;
default:
statements n
}
Sample Program 1:
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int code;
cout<<Enter a code: ;
cin>>code;
switch (code)
{
case 1:
cout<<\nFirst Year ;
break;
case 2:
cout<<\nSecond Year ;
break;
case 3:
cout<<\nThird Year ;
break;
case 4:
cout<<\nFourth Year ;
break;
case 5:
cout<<\nFifth Year ;
break;
default:
cout<<\nNot in the choices ;
}
getch();
return 0;
}
Sample Program 2:
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
char LtrGrade;
cout <<Enter a letter grade: ;
cin>> LtrGrade;
switch (LtrGrade)
{
case a:
case A:
cout<<\nExcellent ;
break;
case b:
case B:
cout<<\nSuperior ;
break;
case c:
case C:
cout<<\nAverage ;
break;
case d:
case D:
cout<<\nPoor ;
break;
case e:
case E:
cout<<\nTry Again ;
break;
default:
cout<<\nNo match was found for
the ENTRY<<LtrGrade<<endl;
}
getch();
return 0;
}