CONTROL STRUCTURES 1
CONTROL STRUCTURES [1]
- if and else
- switch case
1.Types of if else:
1.if else
SYNTAX:
if(condition)
{
//code
}
else{}
2.nested if else
SYNTAX:
if(condition1)
{
//code
if(condition2)
{
//code
}
else{}
}
else{}
3.if else ladder
SYNTAX:
if(condition1)
{
//code
}
elseif(condition2)
{
//code
}
elseif(condition3)
{
//code
}
........
........
else{}
Let's take example
Write a
program to check Whether number is positive or negative in C++.
CODE:
#include<iostream>
using namespace std;
int main ()
{
int num;
cout
<< "Write a program to check Whether number is positive or negative
in C++.\n\n\n";
cout
<< "Enter the number to be checked : ";
cin
>> num;
if (num
>= 0)
cout
<< num << " is a positive number.";
else
cout
<< num << " is a negative number.";
return 0;
}
OUTPUT:
2. switch case
SYNTAX
switch(condition)
{
case constant:
//code
break;
............
............
default:
//code
}
Let's take example
Write a program to implement a calculator using switch case statement.
CODE:
# include <iostream>
using namespace std;
int main()
{
cout
<< "Write a program to implement a calculator using switch case
statement.\n\n\n";
char op;
float
num1, num2;
cout
<< "Enter operator either + or - or * or /: ";
cin
>> op;
cout
<< "Enter two operands: ";
cin
>> num1 >> num2;
switch(op)
{
case
'+':
cout << num1+num2;
break;
case
'-':
cout << num1-num2;
break;
case
'*':
cout << num1*num2;
break;
case
'/':
cout << num1/num2;
break;
default:
cout << "Error! operator is not correct";
break;
}
return 0;
}
OUTPUT:
0 Comments