If else Statement C++
Control Structure
A statement used to control the flow of execution in a program is called a control structure. The instructions in a program can be organized into three kinds of control structures to control execution flow. The control structures are used to implement the program logic. and the if-else statement following.
Types of Control Structures
Different types of control structures are as follows:
Sequence
In a sequential structure, the statements are executed in the same order in which they are specified in the program. The control flows from one statements to another in a logical sequence. All statements are executed exactly once. It means that no statement is skipped and no statement is executed more than once
Example
Suppose a program inputs two numbers and displays average on screen. The program uses two statements to input numbers, one statement to calculate the average and one statement to display the average number. These statements are executed in a sequence to find the average number. All statements are executed once when the program is executed. It is an example of a sequence control structure.
Selection
A selection structure selects a statement or set of statements to execute based on a condition. In this structure, statements or sets of statements is execute when a particular condition is true and ignored when the condition is false. There are different types of selections structure in C++. These are if, if…else, and switch.
Example
Suppose programs input the marks of students and display a message on the screen whether the student is pass or fail. It displays Pass if the student gets 40 or more than 40 marks. It displays Fail when the marks are below 34. The programs check the marks before displaying the message. It is an example of a selection structure.
Repetition
Repetitions structures execute a statement or set of statements repeatedly. It is also known as an iteration structure on the loop. There are different types of repetition structures in C++. These are a while, do-while and for.
Example
Suppose we want to display a message “1 love Pakistan” on screen for 100 times. It is time-consuming to perform this task using the control sequence structure. However, it is very easy to perform this task using a repetition structure. A single loop statement can display the message 100 times.
Function call
A function call is a type of statement that moves the control to another block of code. The control returns after executing all statements in the block. The remaining statement is executed immediately after the function call when the controls are returned.
Relational Operators
The relational operator’s arc used to specify conditions in programs. A retainer, operator compares two values. It produces a result as true or false. The relational operators are sometimes called the conditional operators or comparison operators as they test conditions. that is either true or false. C++ provides the following relational operators:
Operator | Description |
> | Greater than operator returns true if the value on the left side of > is greater than the value on the right side. Otherwise returns false. |
< | Less than the operator returns true if the value on the left side of < is less than the value on the right side. Otherwise returns false. |
= = | Equal to operator returns true it the values on both sides of = = are equal. Otherwise returns false. |
>= | Greater than or equal to operator returns true if the value on the left side of >= a is greater than or equal to the value on the right side. Otherwise returns false. |
<= | Less than or equal to operator returns true if the value on the left side of <= is less than or equal to the value on the right side Otherwise returns false. |
!= | Not equal to the operator. Returns true if the value on the left side of <> is no! equal to the value on the right. Otherwise returns false. |
Relational Operators
Relational Expression
A relational expression is a statement that uses relational operators to compare two values. The result of a relational expression can be true or false. Both sides of feta her al expression can be a constant, variable or arithmetic expression.
Examples
some examples of different relational expressions. are as follows:
Relation Expression | Result |
100> 15 | True |
25 < 5 | False |
30 <= 12 | False |
40 >= 20 | True |
!(‘A’ > ‘B’) | True |
0>=0 | True |
0 <= 0 | True |
1 != 2 | True |
5 != 5 | False |
Relational Expressions
‘if’ Statement
if is a keyword in the C++ language. if the statement is a decision-making statement. It is the simplest form of selection constructs. It is used to execute or skip a statement or set of statements by checking a condition.
The condition is given as a relational expression. U the condition is true, the statement or set of statements after if the statement is executed. If the condition is false, the statement or set of statements after if the statement is not executed.
Syntax
The syntax of if the statement is as follows:
if (condition)
statement;
The above syntax is used for a single statement. A set of statements can also be made conditional. In this case, these statements are written in curly brackets I. The set of statements is also called compound statements.
The syntax for compound statements in if the statement is as follows:
if (condition)
{
statement 1;
statement 2;
.
.
statement N;
}
Flowchart
Limitation of simple ‘if’ Statement
if the statement is the simplest selection structure but it is very limited in its use. The statement or set of statements is executed if the condition is true. But if the condition is false then nothing happens. A user may want to:
- Execute one statement or set of statements if the condition is
- Execute other statement or set of statements if the condition is false.
in this situation, simple if statement cannot be used effectively.
Example
For example, a program should display ‘Pass’ if the student gets 40 or more marks. It should display. ‘Fail’ if the student gets less than 40 marks. Simple if statement cannot be used to handle this situation.
Program:
Write a program to input a number and determine whether it is positive, negative or 0.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int z;
cout<<” Enter the number:”;
cin>>z;
if(z>0)
cout<<” Number is positive”;
if(z<0)
cout<<” The number is negative”;
if(z==0)
cout<<” The number is zero”;
getch ();
}
Output:
Enter a number: 10
The number is positive
‘if-else’ Statement
if-else statement is another type of if statement. It executes one block of the statement(s) when the condition is true and the other when it is false. in any situation, one block is executed and the other is skipped. In the if-else statement:
- Both blocks of the statement can never be executed.
- Both blocks of statements can never be skipped.
Syntax
Its syntax is as follows:
if (condition)
statement;
else
statement;
Two or more statements are written in curly brackets { }. The syntax for compound statements in if-else statement is as follows:
if (condition)
{
statement 1;
statement 2;
.
.
statement N;
}
else
{
statement 1;
statement 2;
.
.
statement N;
}
Flowchart
The flowchart of the if-else statement is as follows:
Program:
Write a program that inputs a number and finds whether it is even or odd using the if-else structure.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int n;
cout<<”Enter a number ”;
cin>>n;
if(n%2==0)
cout<<n<<”is even ”;
else
cout<<n<<”is odd”;
getch();
}
Output:
Enter a number 20
20 is even
Multiple ‘if-else-if’ Structure
The if-else-if statement can be used to choose one block of statements from many blocks of statements. It is used when there are many options and only one block of statements should be executed based on a condition.
Syntax
The syntax of this structure is:
if (condition)
{
block 1;
}
else if (condition)
{
block 2;
}
else if (condition)
{
block 3;
}
.
.
.
.
else
{
Block N;
}
Working of if-else-if
The test conditions in an if-else statement with multiple alternatives are executed in a sequence until a true condition is reached. If a condition is true, the block of statements following the condition is executed. The remaining blocks are skipped. If a condition is false, the block of statements following the condition is skipped. The statement after the last else is executed if all conditions are false.
Program:
Write a program that inputs the test score of a student and displays his grade according to the following criteria:
Test Score Grade
>= 90 A
80 — 89 B
70 — 79 C
60 — 69 D
Below 60 F
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int score;
cout<<”Enter your test score: ”;
cin>>score;
if(score >=90)
cout<<”Your Grade is A.”;
else if(score >= 80)
cout<<”Your Grade is B.”;
else if(score >=70)
cout<<”Your Grade is C.”;
else if(score >=60)
cout<<”Your Grade is D.”;
else
cout<<”Your Grade is F.”;
getch();
}
Output:
Enter your test score:74
Your Grade is C.
Nested ‘if’ Structure
An if statement within an if the statement is called nested if statement. In a nested structure, the control enters into the inner if only when the outer condition is true. Only one block of statements is executed and the remaining blocks are skipped automatically.
The user can use as many if statements inside another if statement as required. The increase in the level of nesting increases the complexity of nested if statement.
Syntax
The syntax of nested If is as follows:
Working of Nested IF
In nested if statement, the condition of outer if is evaluated first. If it is true, the control enters the inner if block. If the condition is false, the inner if is skipped and control directly moves to the else part of outer if. If outer if is true, then control enters in the inner if statement. The inner if evaluated according to simple if statement.
Flowchart
The flowchart of nested if the statement is as follows:
Program:
Write a program that inputs three numbers and displays the smallest number by using nested if condition.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int a,b,c;
cout<<”Enter three numbers: ”;
cin>>a>>b>>c;
if(a<b)
if(a<c)
cout<<a<<”is smallest number.”;
else
cout<<c<<”is smallest number.”;
else
if(b<c)
cout<<b<<”is smallest number.”;
else
cout<<c<<”is smallest.”;
getch();
}
Output:
Enter three number: 20 35 13
13 is the smallest number.
How does it work?
The above program inputs three numbers and finds the smallest one. When the control enters the outer box, the first condition if(a<b) is evaluated. if it is true, the controls enter in the smaller box and the condition if(a<c) is evaluated. If it is also true, the value of a is displayed, otherwise, the value of c is displayed. If the first condition if(a<b) is false, the control shifts to else part of if statement. Now the condition if(b<c) is evaluated. If it is true the value of b is displayed, otherwise the value of c is displayed.
Compound Condition
A type of comparison in which more than one condition is evaluated is called a compound condition. It is used to execute a statement or set of statements by testing many. conditions.
Example
For example, a program inputs two numbers. It displays OK if one number is greater than 100 and the second number is less than 100. The compound condition is executed by using logical operators.
Logical Operators
Logical operators are used to evaluating compound conditions. There are three logical operators in the C++ language:
- AND operator (& &) • OR operator ( | | ) • NOT operator (!)
AND Operator (&&)
The symbol used for AND operator is (&&). It is used to evaluate two conditions. It produces a true result if both conditions are true. It produces a false result if any one condition is false.
Condition 1 | Operator | Condition 2 | Result |
False | && | False | False |
False | && | True | False |
True | && | False | False |
True | && | True | True |
Logical AND operator
Example
Suppose we have two variables A = 100 and B = 50. The compound condition (A>10) && (B>10) is true. It contains two conditions and both are true. So the whole compound condition is also true.
Program:
Write a program that inputs three numbers and displays the maximum number by using a logical operator.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int a,b,c;
cout<<”Enter three numbers: ”;
cin>>a>>b>>c;
if(a>b && b>c)
cout<<”Maximum number is ”<<a;
else if (b>a && b<c)
cout<<”Maximum b=number is ”<<b;
else
cout<<”Maximum number is ”<<c;
getch();
}
Output:
Enter three numbers: 10 20 30
The maximum number is 30
OR Operator ( | | )
The symbol-using for OR operators is ( | | ). It is used to evaluate two conditions. It produces a true result if either condition is true. It produces a false result if both conditions are false.
Condition 1 | Operator | Condition 2 | Result |
False | | | | False | False |
False | | | | True | True |
True | | | | False | True |
True | | | | True | True |
Logical OR operator
Example
Suppose we have two variables A = 100 and B = 50. The compound condition (A>50) | | (B>50) is true. It contains two conditions and one condition (A>50) | | is true. So the whole compound condition is also true. The compound condition (A>500) | | (B>500) is false. Because both conditions are false.
Program:
Write a program that inputs a character and displays whether it is a vowel or not.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
char ch;
cout<<”Enter any character:”;
cin>>ch;
if(ch==’A’|| ch==’a’|| ch==’E’||ch==’e’|| ch==’I’ || ch==’i’|| ch==’O’|| ch==’o’|| ch==’U’|| ch==’u’)
cout<<”You Entered a vowel:”<<ch;
getch();
}
Output:
Enter any character: O
You entered a vowel: O
Not Operator (!)
The symbol for NOT operator is (!). It is used to reverse the result of a condition. It produces a true result if the condition is false. It produces a false result if the condition is true.
Operator | Condition | Result |
! | True | False |
! | False | True |
Logical NOT operator
Example:
Suppose we have two variables A = 100 and B = 50. The condition !(A==B) is true. The result of (A==B) is false but NOT operator converts it into true. The condition! (A>B) is false. The condition (A>B) is true but NOT operator converts into false.
Program:
Write a program that inputs a number and displays whether it is even or odd by using the logical operator “!”.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int z;
cout<<”Enter any number ”;
cin>>z;
if(!(n%2==o))
cout<<”You enter odd number.”;
else
cout<<”You Enter even number.”;
getch();
}
Output:
Enter any number: 20
You enter even number.
‘switch’ Structure
The switch statement is another conditional structure. It is a good alternative to nested if-else. It can be used easily when there are many choices available and only one should be executed. Nested if it becomes very different in such a situation.
Working on ‘switch’ Structure
switch statement compares the result of a single expression with multiple cases. The expression can be any valid expression that results in integer or character value. The expression is evaluated at the top of the switch statement and its result is compared with different cases. Each case represents one choice. If the result matches with any case, the corresponding block of statements is executed. Any number of cases can be used in one switch statement.
The default label appears at the end of all case blocks. It is executed only when the result of expression does not match with any case label. Its use is optional. The position of the default label is not fixed. It may be placed before the first case statement or after the last one.
The break statement in each case is used to exit from the switch body. It is used at the end of each case block. When the result of the expression matches a case block, the corresponding statements are executed. The break statement comes after these statements and then control exits from the switch body. If the break is not used, all case blocks that come after the matching case will also be executed.
Program:
Write a program that inputs several week’s days and displays the name of the day. For example, if you enter 1, it displays “Friday” and so on.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int z;
cout<<”Enter number of a weekday: ”;
cin>>z;
switch(n)
{
case 1:
cout<<”Friday”;
break;
case 2:
cout<<”Saturday”;
break;
case 3:
cout<<”Sunday”;
break;
case 4:
cout<<”Monday”;
break;
case 5:
cout<<”Tuesday”;
break;
case 6:
cout<<”Wednesday”;
break;
case 7:
cout<<”Thursday”;
break;
default;
cout<<”Invalid number”;
}
getch();
}
Output:
Enter number of a weekday: 3
Sunday
Difference between nested ‘if-else’ and ‘switch’
The switch statement and nested if-else statements are used when there are multiple 1.1101CP% and only one is to be executed. Difference between if-else and switch is as follows:
Switch | Nested-if | |
1. | It is easy to use when there are multiple choices. | It is difficult to use when there are multiple choices. |
2. | It uses a single expression for multiple choices. | It uses multiple expressions for multiple choices. |
3 | It cannot check a range of values. | It can check a range of values. |
4 | It checks only constant values. You cannot use variables with a case statement. | It can check variables also. You can use a constant or variable in relational expressions. |
Difference between the switch and nested if
Conditional Operator
The conditional operator is a decision-making structure. It can be used in place of a simple if-else structure. It is also called the ternary operator as it uses three operands.
Syntax
The syntax of the conditional operator is as follows:
(condition)? true-case statement: false-case statement;
condition | The condition is specified as a relational or logical expression. The condition is evaluated to true or false. |
true-case | It is executed if the expression evaluates to true. |
false-case | It is executed if the expression evaluates to false. |
Example
Suppose we have a variable A. The following statement:
X = (A>50) ? 1 : 0;
will assign 1 to X if the condition A>50 is true. It will assign 0 to X the condition is false. The above statement can be written using the if-else statement as follows:
(A>50)
X = 1;
else
X = 0;
Program:
Write a program that inputs marks of a student and displays “Pass” if marks are more than 40 and “Fail” otherwise by using conditional operator.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int marks;
cout<<”Enter your marks: ”;
cin>>marks;
cout<<”Result is ”<<(marks>40 ? “Pass ” : “Fail”);
getch();
}
Output:
Enter your marks:92
Result is pass
‘goto’ Statement
The ‘gold statement is used to move the control directly to a particular location of the program by using the label. A label is a name given to a particular line of the program. A label Ls treated with a valid identifier followed by a colon (:).
Syntax
goto Label;
the ‘Label’ indicates the liable to which the control is transferred.
Program:
Write a program that displays “C++” five-time using a goto statement.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int z=1;
loop;
cout<<z<<”C++”<<endl;
z++;
if(z<=5) goto loop;
cout<<”End the Program”;
getch();
}
Output:
1: C++
2: C++
3: C++
4: C++
5: C++
End the Program
How above Program Works?
The above program uses a goto statement to repeal a statement. The if statement checks the value of n. If the value is 5 or less, the control moves back to the loop label. In this way, the required message appears five times.