VKS-LEARNING HUB

Home » Class-XI » C++ XI » Conditions

Conditions

Condition or Logical expression

As a Programmer, you will ask the computer to check various kinds of situations(condition) and to act accordingly. The computer performs various comparisons of various kinds of statements. These statements come either from you or from the computer itself, while it is processing internal assignments
It has the ability to control the flow of your program, letting it make decisions on what code to execute. One of the important functions of the conditional  statement is that it allows the program to select an action based upon the user’s input.
For example, by using an if statement to check a user entered password, your program can decide whether a user is allowed access to the program or not.
In C++ a Condition or a Logical expression compares two values using logical operators. Logical operators supported by C++ are >, >=, <, <=, == and !=. Either two integer values or two floating point values or two characters can be compared using logical operators. Two characters are compared by comparing the ASCII codes of two the characters. Two strings cannot be compared using logical operators. String comparison will be discussed later. Condition is either TRUE or FALSE. In C++ condition is TRUE => logical expression has value 1 and condition is FALSE => logical expression has value 0. List of logical operators are given below:
Operator
Meaning
Condition
Result
Meaning
>
Greater than
20>10
1
TRUE
10>20
0
FALSE
2.5 > 13.5
0
FALSE
‘T’ > ‘B’
1
TRUE
>=
Greater than equal to
20>=10
1
TRUE
20>=20
1
TRUE
20>=40
0
FALSE
13.5 >= 10.25
1
TRUE
‘A’ >= ‘f’
0
FALSE
<
Less than
10<20
1
TRUE
20<10
0
FALSE
2.5 < 13.5
1
TRUE
‘T’ < ‘B’
0
FALSE
<=
Less than equal to
10<=20
1
TRUE
10<=10
1
TRUE
40<=10
0
FALSE
13.5 <= 10.25
0
FALSE
‘A’ <= ‘f’
1
TRUE
==
Equal to
40==40
1
TRUE
50==40
0
FALSE
‘B’ == ‘B’
1
TRUE
2.5 == 13.5
0
FALSE
!=
Not equal to
30!=10
1
TRUE
40!=40
0
FALSE
‘B’ != ‘B’
0
FALSE
13.5 != 10.25
1
TRUE

IF -ELSE

The if statement can be used to test conditions so that we can alter the flow of a program. In other words: if a specific statement is true, execute some instructions. If not true, execute these instructions.In C++ condition or logical expression is used with if-else. if-else statement provides a way to change program flow based on a condition. We can have if statement without else but we cannot have else without if.

Rule 1

if (Condition) true than execute the statement/Block after If    if Condition is not true  do nothing

if

Example the user can input a two number. The numbers is stored in the variable A and B. Now take a look at the “if statement”: if the number stored in the variable A is greater  than  number stored in Variable B  then  “A is Greater” is printed on the screen. If the value stored in variable A is not greater than B, then nothing is printed. Take a look at the example: #include<iostream.h> void main() { int A,B; cin >> A>>B; if ( A > B ) cout << “A is Greater” << ‘\n’; } Now take another look at the “if statement”: look at the placement of the { }. As you can see there is no {  behind the “if statement”. If there is just one instruction (if the statement is true), you can place it after the “if statement” (with an indentation). Are multiple instructions necessary then you will have to use curly brackets, like so: if ( A > B  ) { cout << “A is Greater” << ‘\n’; cout << “Hello” << ‘\n’; }

Rule 2

if (Condition) true than execute the statement/Block after If                                                                                                                                                                                                                                                                                           if Condition is not true   execute the statement/Block after else

ifelse

Now we like to also print something if the “if statement” is not true that is  A is not greater than B. We could do this by adding another “if statement” but there is an easier / better way. Which is using the so called “else statement” with the “if statement”. #include<iostream.h> void main() { int A,B; cin >> A>>B;

        if ( A > B  )

                 {

cout << “A is greater” << ‘\n’;

cout << “closing program” << ‘\n’;

}

else

{

cout << “A is lesser than Bl” << ‘\n’;

cout << “closing program” << ‘\n’;

}

}

Usage of if-else

Example 2

#include<iostream.h>

void main()

{

double marks;

cout<<“Input marks[0-100]? “;

cin>>marks;

if (marks>=40)

cout<<“Pass”<<endl;

else

cout<<“Fail”<<endl;

}

Running of the program

Input marks[0-100]? 35

Fail

Explanation  Condition (marks>40) is not true so else statement will be executed

Running of the program

Input marks[0-100]? 85

Pass

Explanation  Condition (marks>40) is  true so statements after if will be executed

Ternary Operator (Conditional Operator)
Ternary operator is used in place of ifelse statement. But all ifelse statement cannot be replaced by Ternary operator. It is called ternary operator since an expression involving ternary operator requires three (3) operands and two (2) operators. The two Ternary operator is more compact compared to ifelse statement.
Rule:          Condition? Action1: Action2

Basic Syntax: The basic syntax of using the ternary operator is thus:

(condition) ? (if_true) : (if_false)

Which is basically the same as:

if (condition)

if_true;

else

if_false;

Condition or Logical Expression is evaluated and if the Condition is TRUE then Action1 executed otherwise Action2 is executed.
Usage of Ternary Operator (Conditional Operator)
Program to input two values and displays the bigger value on the screen.
#include<iostream.h>
void main()
{
int a, b;
cout<<“Input 2 integers? “;
cin>>a>>b;
int max = a>b ? a : b;
cout<<“Max value=”<<max;
}
Running of the program
Input 2 integers? 20 10
Max value=20
Input 2 integers? 25 40
Max value=40
Explanation of output
First run:      Inputted values 20, 10; condition a>b is TRUE; action1 is executed; max is assigned the value 20 and therefore program displays Max value=20.
Second run:   Inputted values 25, 40; condition a>b is FALSE; action2 is executed; max is assigned the value 40 and therefore program displays Max value=40.
1.   Write a complete C++ program to input a character; convert it onto an uppercase.
#include<iostream.h>
void main()
{
char ch;
cout<<“Input a character? “; cin>>ch;
ch = ch>=’a’ && c<=’z’ ? char(ch-32) : ch;
cout<<“Uppercase character=”<<ch;
}
2.   Write a complete C++ program to input a character and whether it is digit or not.
#include<iostream.h>
void main()
{
char ch;
cout<<“Input a character? “; cin>>ch;
cout<<(ch>=’0′ && ch<=’9′ ? “Digit” : “Not Digit”);
}

switchcase

In the previous example we observed that each of the conditions that are tested are mutually exclusive (conditions do not overlap). The sequence of mutually exclusive alternatives can be delineated by ifelseif statement, can also be coded using switchcase construct.
 
Rule:   switch (CaseSelector)
{
case Label1:
StatementList1;
break;
case Label2:
Statementlist2;
break;
case Label3:
StatementList3;
break;
:
default:
DefaultStatementList;
}
 
Expression after switch is called Case Selector. A Case Selector is either an int integer (int) or character (char) expression. If the expression is of the type floating point (float/ double), compiler will flag syntax error. But Case Selector may contain a floating value but the final value of the case selector has be either integer type / character type. After the Case Selector comes a block, the block contains Case Labels. Case Labels represent all the possible values of Case Selector. The switch evaluates the Case Selector and looks for its value among the Case Labels. If a match is found, then the statements in StatementList immediately after the matching Case Label are executed until break is encountered or end of switchcase is reached. If no match is found then DefaultStatementList after default is executed. The default is optional and, if it is missing, no action takes place if all matches fail. When a break is encountered in a switchcase, program execution jumps to the immediate statement outside the body of switchcase block.

The break statement has following two usage in C++:

  1. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
  2. It can be used to terminate a case in the switch statement (covered in the next chapter).

If you are using nested loops ( ie. one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

cpp_break_statement

Write a complete C++ program to input date and check whether inputted date is valid or not. A non century year (year not divisible by 100) divisible 4 is a leap year or century year divisible by 400 is a leap year. In a leap year there are 29 days in February. In a non leap year February has 28 days.
#include<iostream.h>
void main()
{
int dd, mm, yy, maxdays=0;
cout<<“Input Day  [1-31]? “; cin>>dd;
cout<<“Input Month[1-31]? “; cin>>mm;
cout<<“Input Year [yyyy]? “; cin>>yy;
cout<<“Inputted date “<<dd<<‘-‘<<mm<<‘-‘<<yy;
if (yy>0)
{
switch (mm)
{
case 2:
if (yy%400==0 || yy%4==0 && yy%100!=0)
maxdays=29;
else
maxdays=28;
break;
case 4:
case 6:
case 9:
case 11: maxdays=30; break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: maxdays=31;
}
if (dd>=1 && dd<=maxdays)
cout<<” Is Valid”;
else
cout<<” Is Invalid”;
}
else
cout<<” Is Invalid”;
}

Q2

#include <iostream.h>
 int main ()
{
// local variable declaration:
char grade = ‘D’;
switch(grade)
{
case ‘A’ : cout << “Excellent!” << endl;
break;
case ‘B’ :
case ‘C’ :
cout << “Well done” << endl;
break;
case ‘D’ :
cout << “You passed” << endl;
break;
case ‘F’ :
cout << “Better try again” << endl;
break;
default : cout << “Invalid grade” << endl;
}
cout << “Your grade is ” << grade << endl;
return 0;
}
This would produce following result:
You passed
Your grade is D

Previous

Solved Examples

Unsolved Questions for Practice

Next


Leave a comment