Unit-2 If Else Switch owLTTM29hK
Unit-2 If Else Switch owLTTM29hK
Control Structure
Example:1
#include <iostream>
using namespace std;
int main() {
// prints the string enclosed in double quotes
cout << "This is C++ Programming";
return 0;
}
Run Code
Output
This is C++ Programming
Run Code
Output
70
256.783
character: A
Notes:
The endl manipulator is used to insert a new line. That's why each output is displayed in a new line.
The << operator can be used more than once if we want to print different variables, strings and so on in a single statement.
For example:
Example 3: Integer Input/Output Example 4:
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() { int main() {
int num; char a;
cout << "Enter an integer: "; int num;
cin >> num; // Taking input cout << "Enter a character and an integer: ";
cout << "The number is: " << num; cin >> a >> num;
return 0; cout << "Character: " << a << endl;
} cout << "Number: " << num;
Run Code return 0;
Output }
Run Code
Enter an integer: 70 Output
The number is: 70
Enter a character and an integer: F
23
Character: F
Number: 23
The largest number out of three numbers using ternary The largest number out of three numbers using ternary operator in
operator in C++ language C++ language
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int num1, num2, num3, largest; int num1,num2,num3;
cout<<"Enter three numbers: "; cout<<" Enter value for first number,second and third number";
cin >> num1 >> num2 >> num3; cin>>num1>>num2>>num3;
largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : if(num1>num2&&num1>num3)
(num2 > num3 ? num2 : num3) ; {
cout << largest << " is the largest number."; cout<<" First number is greatest:"<<endl<<"whick is= "<<num1;
return 0; }
} else if(num2>num1&&num2>num3)
{
cout<<" Second number is greatest"<<endl<<"whick is= "<<num2;
}
else
{
cout<<" Third number is greatest"<<endl<<"whick is= "<<num3;
Output: }
Please Enter three numbers: return 0;
45 }
78
60
Largest number is: 78
sizeof Operator in C++
#include <iostream>
using namespace std;
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
Output:
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
Check Alphabet or Not in C++ Print ASCII Value in C++
#include<iostream>
using namespace std; #include <iostream>
int main() using namespace std;
{ int main() {
char ch; char c;
cout<<"Enter a Character: "; cout << "Enter a character: ";
cin>>ch; cin >> c;
if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z')) cout << "ASCII Value of " << c << " is " << int(c);
cout<<endl<<ch<<" is an Alphabet"; return 0;
else }
cout<<endl<<ch<<" isn't an Alphabet";
cout<<endl;
return 0; Output
} Enter a character: p
ASCII Value of p is 112
Compute quotient and remainder
#include <iostream>
using namespace std;
int main()
{
int divisor, dividend, quotient, remainder;
cout << "Enter dividend: ";
cin >> dividend;
cout << "Enter divisor: ";
cin >> divisor;
quotient = dividend / divisor;
remainder = dividend % divisor;
cout << "Quotient = " << quotient << endl;
cout << "Remainder = " << remainder;
return 0;
}
Output:
Enter a two digit number:
34
Reversed no is:
43
Reverse a four digit number
#include<iostream>
using namespace std;
int main()
{
int n,f,x,s,y,t,l,rev;
cout<<"Enter Four Digit Number : "<<endl;
cin>>n;
f=n/1000;
x=n%1000;
s=x/100;
y=x%100;
t=y/10;
l=y%10;
rev=l*1000+t*100+s*10+f;
cout<<"\nReverse Number :"<<endl<<rev;
return 0;
}
#include <iostream>
using namespace std;
int main ()
{
num2 = (float) num1;
cout << " The value of int num1 is: " << num1 << endl;
cout << " The value of float num2 is: " << num2 << endl;
return 0;
}
Output
By Prof.Avani Shah 19
Diagram
q Sequence
q
no yes
q Selection
q
q
q no
q yes
q
q Repetition
q By Prof.Avani Shah 20
C++ if
In computer programming, we use the if...else statement to run one block of code under certain conditions and another block
of code under different conditions.
There are three forms of if...else statements in C++:
1. if statement
2. nested if statement
3. if...else statement
4. if...else if...else statement
C++ if Statement
The syntax of the if statement is:
if (condition) {
// body of if statement
}
The if statement evaluates the condition inside the parentheses ( ).
If the condition evaluates to true, the code inside the body of if is executed.
If the condition evaluates to false, the code inside the body of if is skipped.
Note: The code inside { } is the body of the if statement.
Example 1: C++ if Statement
Output 1
// Program to print positive number entered by the user Enter an integer: 5
// If the user enters a negative number, it is skipped You entered a positive number: 5
#include <iostream> This statement is always executed.
When the user enters 5, the condition
using namespace std; number > 0 is evaluated to true and the
int main() statement inside the body of if is executed.
{
Output 2
int number; Enter a number: -5
cout << "Enter an integer: "; This statement is always executed.
When the user enters -5, the condition
cin >> number;
number > 0 is evaluated to false and the
if (number > 0) statement inside the body of if is not
{ executed.
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}
C++ if...else
The if statement can have an optional else clause. Its syntax is:
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
The if..else statement evaluates the condition inside the parenthesis.
If the condition evaluates true,
the code inside the body of if is executed
the code inside the body of else is skipped from execution
If the condition evaluates false,
the code inside the body of else is executed
the code inside the body of if is skipped from execution
Example 2: C++ if...else Statement
// Program to check whether an integer is positive or negative Output 1
// This program considers 0 as a positive number Enter an integer: 4
#include <iostream> You entered a positive integer: 4.
using namespace std; This line is always printed.
int main() In the above program, we have the condition
{
number >= 0. If we enter the number greater or
int number;
equal to 0, then the condition evaluates true.
cout << "Enter an integer: ";
Here, we enter 4. So, the condition is true. Hence,
cin >> number;
if (number >= 0)
the statement inside the body of if is executed.
{ Output 2
cout << "You entered a positive integer: " << number << endl; Enter an integer: -4
} You entered a negative integer: -4.
else { This line is always printed.
cout << "You entered a negative integer: " << number << endl;
} Here, we enter -4. So, the condition is false.
cout << "This line is always printed."; Hence, the statement inside the body of else is
return 0;
executed.
}
C++ Nested if
Sometimes, we need to use an if statement inside another if statement. This is known as nested if statement.
Think of it as multiple layers of if statements. There is a first, outer if statement, and inside it is another, inner if statement. Its syntax is:
// outer if statement
if (condition1) {
// statements
// inner if statement
if (condition2) {
// statements
}
}
Notes:
We can add else and else if statements to the inner if statement as required.
The inner if statement can also be inserted inside the outer else or else if statements (if they exist).
We can nest multiple layers of if statements.
Example 4: C++ Nested if
}
// C++ program to find if an integer is positive, negative or zero
// using nested if statements
// outer else condition
#include <iostream> else {
using namespace std; cout << "The number is 0 and it is neither positive nor
int main() { negative." << endl;
int num; }
cout << "Enter an integer: ";
cout << "This line is always printed." << endl;
cin >> num;
// outer if condition
return 0;
if (num != 0) { }
// inner if condition
if (num > 0) { Output 1
cout << "The number is positive." << endl;
Enter an integer: 35
}
// inner else condition
The number is positive.
else { This line is always printed.
cout << "The number is negative." << endl;} Output 2
Enter an integer: -35
The number is negative.
This line is always printed.
Output 3
Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.
In the above example,
We take an integer as an input from the user and store it in the variable num.
We then use an if...else statement to check whether num is not equal to 0.
If true, then the inner if...else statement is executed.
If false, the code inside the outer else condition is executed, which prints "The number is 0 and it is neither positive nor
negative."
The inner if...else statement checks whether the input number is positive i.e. if num is greater than 0.
If true, then we print a statement saying that the number is positive.
If false, we print that the number is negative.
Note: As you can see, nested if...else makes your logic complicated. If possible, you should always try to avoid nested
if...else.
C++ if...else...else if statement / if-else-if ladder
The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice
between more than two alternatives, we use the if...else if...else statement.
The syntax of the if...else if...else statement is:
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Here,
If condition1 evaluates to true, the code block 1 is executed.
If condition1 evaluates to false, then condition2 is evaluated.
If condition2 is true, the code block 2 is executed.
If condition2 is false, the code block 3 is executed
Note: There can be more than one else if statement but only one if and else statements.
Example 3: C++ if...else...else if
// Program to check whether an integer is positive, negative or zero Output 1
#include <iostream> Enter an integer: 1
using namespace std;
You entered a positive integer: 1.
int main() {
int number;
This line is always printed.
cout << "Enter an integer: "; Output 2
cin >> number; Enter an integer: -2
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
You entered a negative integer: -2.
} This line is always printed.
else if (number < 0) { Output 3
cout << "You entered a negative integer: " << number << endl;
}
Enter an integer: 0
else { You entered 0.
cout << "You entered 0." << endl; This line is always printed.
}
cout << "This line is always printed.";
return 0;
}
In this program, we take a number from the user. We then use the if...else if...else
ladder to check whether the number is positive, negative, or zero.
If the number is greater than 0, the code inside the if block is executed. If the
number is less than 0, the code inside the else if block is executed. Otherwise, the
code inside the else block is executed.
// C++ program to illustrate if-else-if ladder
#include <iostream>
using namespace std;
int main()
{
int i = 20;
// Check if i is 10
if (i == 10)
cout << "i is 10";
// Since i is not 10
// Check if i is 15
else if (i == 15)
cout << "i is 15";
// Since i is not 15
// Check if i is 20
else if (i == 20)
cout << "i is 20";
// If none of the above conditions is true
// Then execute the else statement
else
cout << "i is not present";
return 0; }
#include <iostream> Output:
using namespace std; enter value of i: 45
int main() i is greater than 20
{
int i ;
cout<<"enter value of i";
cin>>i;
// Check if i is between 0 and 10
if (i >= 0 && i <= 10)
cout << "i is between 0 and 10" << endl;
// Since i is not between 0 and 10
// Check if i is between 11 and 15
else if (i >= 11 && i <= 15)
cout << "i is between 11 and 15" << endl;
// Since i is not between 11 and 15
// Check if i is between 16 and 20
else if (i >= 16 && i <= 20)
cout << "i is between 16 and 20" << endl;
// Since i is not between 0 and 20
// It means i is greater than 20
else
cout << "i is greater than 20" << endl;}
Example: Check Vowel or a Consonant
#include <iostream>
using namespace std;
int main()
{
char alphabet;
cout<<"Enter alphabet";
cin>>alphabet;
if (alphabet == 'a' || alphabet == 'e' || alphabet == 'i' ||alphabet == 'o' || alphabet == 'u' || alphabet == 'A' || alphabet ==
'E' || alphabet == 'I' || alphabet == 'O' || alphabet == 'U')
cout <<alphabet<< " is a Vowel" << endl;
else
cout <<alphabet<< " is a Consonant" << endl;
return 0;
}
Example 1: Check Leap Year Output 1
#include<iostream> Enter a year: 1900
using namespace std; 1900 is not a leap year.
int main() { Output 2
int year; Enter a year: 2012
cout<< “enter year”; 2012 is a leap year.
cin>>year;
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
cout<<year<<" is a leap year";
else
cout<<year<<" is not a leap year";
return 0;
}
1. Check Whether Number is Even or Odd using if else 2. Check Whether Number is Even or Odd using ternary
#include <iostream> operators
using namespace std; #include <iostream>
int main() using namespace std;
{ int main()
int n; {
cout << "Enter an integer: "; int n;
cin >> n; cout << "Enter an integer: ";
if ( n % 2 == 0) cin >> n;
cout << n << " is even."; (n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd.";
else return 0;
cout << n << " is odd."; }
return 0;
}
Output
Enter an integer: 23
23 is odd.
C++ program to convert lowercase character to uppercase and vice versa
#include <iostream>
using namespace std;
int main()
{
char ch;
cout<<"Please input a valid character (Alphabet): ";
cin>>ch;
//check for valid alphabet Output:
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z')) Please input a valid character (Alphabet): s
{ converted character is: S
//check case and convert into opposite case
if(ch>='A' && ch<='Z')
ch=ch+32;
else if(ch>='a' && ch<='z')
ch=ch-32;
cout<<"converted character is: "<<ch<<endl;
}
else
{
cout<<"Entered character is not a valid alphabet!!!"<<endl;
}
return 0;
}
#include<iostream> else if(avg>=41 && avg<51)
using namespace std; cout<<"C2";
int main() else if(avg>=33 && avg<41)
{ cout<<"D";
int i; else if(avg>=21 && avg<33)
float mark, sum=0, avg; cout<<"E1";
cout<<"Enter Marks obtained in 5 Subjects: "; else if(avg>=0 && avg<21)
for(i=0; i<5; i++) cout<<"E2";
{ else
cin>>mark; cout<<"Invalid!";
sum = sum+mark; cout<<endl;
} return 0;
avg = sum/5;
cout<<"\nGrade = ";
if(avg>=91 && avg<=100)
cout<<"A1";
else if(avg>=81 && avg<91)
cout<<"A2";
else if(avg>=71 && avg<81)
cout<<"B1";
else if(avg>=61 && avg<71)
cout<<"B2";
else if(avg>=51 && avg<61)
cout<<"C1";
C++ switch..case
Switch case statement is used when we have multiple conditions and we need to perform different action based on the
condition. When we have multiple conditions and we need to execute a block of statements when a particular condition is
satisfied. In such case either we can use lengthy if..else-if statement or switch case. The problem with lengthy if..else-if is
that it becomes complex when we have several conditions. The switch case is a clean and efficient method of handling
such scenarios
switch (variable or an integer expression)
{
case constant:
//C++ code
;
case constant:
//C++ code
;
default:
//C++ code
;
}
Switch Case statement is mostly used with break statement even
though the break statement
is optional. We will first see an example without break
statement and then we will discuss
switch case with brea
C++ switch..case
The switch statement allows us to execute a block of code among many alternatives.
The syntax of the switch statement in C++ is:
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
. How does the switch statement work?
. The expression is evaluated once and compared with the values
. of each case label.
default: • If there is a match, the corresponding code after the matching
// code to be executed if label is executed. For example, if the value of the variable is
// expression doesn't match any constant equal to constant2, the code after case constant2: is executed
} until the break statement is encountered.
• If there is no match, the code after default: is executed. Note:
We can do the same thing with the if...else..if ladder. However,
the syntax of the switch statement is cleaner and much easier to
read and write.
Break statement in Switch Case
Before we discuss about break statement, Let’s see what happens when we don’t use break
statement in switch case. See the example below:
#include <iostream>
using namespace std;
int main(){
int i=2;
switch(i) {
case 1: cout<<"Case1 "<<endl;
case 2: cout<<"Case2 "<<endl;
case 3: cout<<"Case3 "<<endl;
case 4: cout<<"Case4 "<<endl;
default: cout<<"Default "<<endl;
}
return 0;
}
Output:
Case2
Case3
Case4
Default
You can also use characters in switch case. for example
#include <iostream>
using namespace std;
int main(){
char ch='b';
switch(ch) {
case 'd': cout<<"Case1 ";
break;
case 'b': cout<<"Case2 ";
break;
case 'x': cout<<"Case3 ";
break;
case 'y': cout<<"Case4 ";
break;
default: cout<<"Default ";
}
return 0;
}
#include <iostream> case 5:
using namespace std; cout << "Friday";
int main() break;
{ case 6:
int day; cout << "Saturday";
cout<<"enter day"; break;
cin>>day; case 7:
switch (day) cout << "Sunday";
{ break;
case 1: default:
cout << "Monday"; cout<<"enter valid choice";}}
break;
case 2: Output:
cout << "Tuesday"; enter day
break; 4
case 3: Thursday
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
Example: Create a Calculator using the switch Statement
// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}
return 0;
}
Check Vowel or consonant using switch case statements with the break
#include <iostream>
using namespace std;
int main()
{
char ch;
cout<<"enter vowel";
cin>>ch;
switch(ch)
{
case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U':
cout<<"enter alphabet is a vowel";
break;
default:
cout<<"enter alphabet is consonant";
}
}
Write a program to calculate the Goods and Services Tax (GST) for a given amount based on the GST rate. The
program should be able to handle different GST rates and provide a clear breakdown of the total amount, GST
amount, and the amount before GST. Your program should accept the original price of the item and the GST rate.
The rate can be a whole number or a decimal. The program should display the amount of GST applied, price
before GST and after GST. Constraints: The original price should be a positive number and the GST rate should be
a non-negative number and can be a decimal ranging from 0% to 28%.
https://www.bankbazaar.com/tax/gst-rates.html
Input : Netprice = 120, original_cost = 100
Output : GST = 20%