Вы находитесь на странице: 1из 7

EL – 125 Programming Fundamentals

Experiment # 04

Learning Conditional Operators

Performed on 31st March, 2020

Student Name:
Roll Number:

Maximum Marks Performance = 05 Viva = 05 Total = 10

Marks Obtained
Remarks (if any)

Experiment evaluated by

Instructor Name: Hajra Ahmed

Signature and Date:

Copyright © Department of Electrical Engineering – Usman Institute of Technology


Practical Objectives:
 To learn the concept of if and if-else statements.
 Using Nested if and if-else statements.
 Use of Ternary operators.
 Understanding various variations of conditional statement and difference between them.
 Understanding and using switch case statements.

Theory

1. If Statement

This is used to decide whether to do something at a special point, or to decide between


two courses of action. The following test decides whether a student has passed an exam with
a pass mark of 45.

if (result >= 45)


cout<<"Pass"<<endl;
else
cout<<"Fail"<<endl;

It is possible to use the if part without the else.

if (temperature < 0)
cout<<"Frozen"<<endl;

Each version consists of a test, (this is the bracketed statement following the if). If the test is
true then the next statement is obeyed. If is false then the statement following the else is
obeyed if present. After this, the rest of the program continues as normal. If we wish to have
more than one statement following the if or the else, they should be grouped together between
curly brackets. Such a grouping is called a compound statement or a block.

if (result >= 45)


{ cout<<“Passed"<<endl;
cout<<"Congratulations "<<endl;
}
else
{ cout<<"Failed"<<endl;
cout<<"Good luck in the future"<<endl;
}

Sometimes we wish to make a multi-way decision based on several conditions. The most
general way of doing this is by using the else if variant on the if statement. This works by
cascading several comparisons. As soon as one of these gives a true result, the following
statement or block is executed, and no further comparisons are performed. In the following
example we are awarding grades depending on the exam result.
if (result >= 75)
cout<<"Passed: Grade A"<<endl;
else if (result >= 60)
cout<<"Passed: Grade B"<<endl;
else if (result >= 45)
cout<<"Passed: Grade C"<<endl;
else cout<<”Failed”<<endl;

Copyright © Department of Electrical Engineering – Usman Institute of Technology


In this example, all comparisons test a single variable called result. In other cases,
each test may involve a different variable or some combination of tests. The same
pattern can be used with more or fewer else if's, and the final lone else may be left
out. It is up to the programmer to devise the correct structure for each programming
problem.
2. Multiple if statements:

Consider the following example:

if (exp 1)
{
statement1;
}
if (exp 2)
{
statement 2;
}

3. Else-If Clause:

if (exp 1)
{
statement 1;
}
else if (exp 2)
{
statement 2;
}
else
{
statement 3;
}

In the above example evolving of exp 2 will depend on exp 1. Means, 2 will be evolved if exp
1 evolved as false. But else will be executed if all the test conditions evolve as false. Number
of else-if statements will depend on programmer’s requirement.

4. Nested IF Statement:

It is always legal to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).

if (Boolean_expression 1)
{
//Executes if the Boolean_experession 1 is true
if(Boolean_expression 2)
{
//Executes if Boolean_expression 2 is true
}
}

Copyright © Department of Electrical Engineering – Usman Institute of Technology


5. Nested If-Else Statement:

if (Boolean_expression 1)
{
//Executes if the Boolean experession 1 is true
else
{
if(Boolean_expression 2)
//Executes if Boolean_expression 2 is true else

// Executes if Boolean_expression 2 is false


}
}

6. Ternary Operator:

The conditional operator is an operator used in C and C++ (as well as other languages, such
as C#). The ?: operator returns one of two values depending on the result of an expression.

(Expression 1) ? Expression 2: Expression 3

If expression 1 evaluates to true, then expression 2 is evaluated. If expression 1 evaluates


to false, then expression 3 is evaluated instead.

Example:
#include<iostream>
using namespace std;
int main()
{
int n1,n2;
int val;
char op;
cout<<"Enter operand 1”;
cin>>n1;
cout<<"Enter operand 2”;
cin>>n2;
cout<<"Enter operator ";
cin>>op;
if(op == '+')
val = n1 + n2;
else if(op == '-')
val = n1 - n2;
else if(op == '/')
val = n1 / n2;
else if(op == '*')
val = n1 * n2;
else
cout<<"Invalid Operator “;
cout<<n1<<op<<n2<<endl<<”Answer”<<val;
return 0;
}

Copyright © Department of Electrical Engineering – Usman Institute of Technology


7. else-if clause with logical operators (&& , || and !):

Example:

int main()
{
bool want_to_start;
int age;

cout<< "Do you want to start the application? [0:No][1:Yes]"<<endl;


cin >> want_to_start; //An input of 0 is 'false', and 1 is 'true'

if(!want_to_start)
cout<<"Then why open the application? I'm starting
anyway."<<endl;

cout<<"Application starting."<<endl;
cout<<"Enter your age: ";
cin>>age;

if(age >= 35 && age <= 80)


cout << "You're between 35 and 80 and can save money on your
car insurance!"<< endl;
else if(age < 0 || age > 160)
cout << "You're lying - you CANNOT be that age." << endl;
else
cout << "Sorry, we don't have any deals for you today!"<<endl;
return 0;
}
8. The Switch Statement:

In C++ the switch statement can be used to replace the multi-way test.
When the tests are like this:
if( grade == 'A' ) ...
else if( grade == 'B' ) ...
else if( grade == 'C' ) ...
else if( grade == 'D' ) ...
else ...
testing a value against a series of constants, the switch statement is often clearer and usually
gives better code. Use it like this:

Example:

#include <iostream.h>

int main()
{
char grade;
cout<<"Enter your grade: “;
cin>>grade;
switch (grade)
{
case 'A':
cout<<"Your average must be between 90 – 100”;
break;
case 'B':

Copyright © Department of Electrical Engineering – Usman Institute of Technology


cout<<"Your average must be between 80 - 89";
break;
case 'C':
cout<<"Your average must be between 70 - 79";
break;
case 'D':
cout<<"Your average must be between 60 - 69";
break;
default:
cout<<"Your average must be below 60";
}
}

The case statements label the various actions we want; default gets done if none
of the other cases are satisfied. (A default is optional; if it isn't there, and none of the cases
match, you just fall out the bottom.)

The break statement in this example is new. It is there because the cases are just labels, and
after you do one of them, you fall through to the next unless you take some explicit action to
escape. This is a mixed blessing. On the positive side, you can have multiple cases on a single
statement; we might want to allow both upper and lower
case ‘a’: case ‘A’: . . .
case ‘b’: case ‘B’: . . .

The break statement also works in for and while statements; it causes an immediate exit from
the loop.

Do it yourself

Simple Task:

1. Write a program using if-else, that takes a number as input from user and checks
whether the number is even or odd.

2. Write a program using else if clause to check the age entered by user such that if user
input age is less than 100 message you are young would be displayed if user enter
red age equal to 100 message you are old will be displayed and if range is greater
than 100 message you are too old will be displayed.

3. Write a program using ternary operator to print the value of x depending on the
condition y<10.

4. Write a C++ program to relate two integers entered by user using = or > or < sign
using nested if- else.

Copyright © Department of Electrical Engineering – Usman Institute of Technology


Challenging Task:

1. In a company, worker increment is determined on the basis of the time required for
a worker to complete a particular job. If the time taken by the worker is between 2-3
hours, then the worker is said to be highly efficient. If the time required by the worker
is between 3-4 hours, then the worker is ordered to improve speed and his increment
is 5% of his salary. If the time taken by the worker is more than 4 hours he is
asked to leave the company. If the time taken by the worker and his current salary
is input through the keyboard find the efficiency of the worker and his next month’s
salary.

2. The Department of Defense would like a program that identifies the males who are
single between the age of 18 and 26. Write a program which takes input gender
(‘X’ for male and ‘Y’ for female), marital status (‘M’ for married and ‘S’ for single) and
age of a person and check if the person meets all criteria. Implement it using
a. Multiple if’s
b. Nested if

Home Task:
1. Write a program that declares and initializes two numbers with your_roll_no and
your_friend_roll_no and displays the greater of the two. Use ternary operator.

2. Write a program using nested if else statement. The condition 1 will be true if the user
has typed „a‟as username. Then the control moves to the nested if statement to check
for password. If it is true, print “login successful” else it will print “Password is incorrect,
Try again”. If condition 1 is false execute the else statement “Username is incorrect,
Try again”.

3. Write a program which to find the grace marks for a student using switch.
The user should enter the class obtained by the student and the number of
subjects he has failed in.

 If the student gets first class and the number of subjects, he failed in is
greater than 3, then he does not get any grace. If the number of
subjects he failed in is less than or equal to 3 then the grace is of 5 marks
over subject.

 If the student gets second class and the number of subjects, he failed in
is greater than 2, then he does not get any grace. If the number of subjects
he failed in is less than or equal to 2 then the grace is of 4 marks per subject.

 If the student gets third class and the number of subjects, he failed in is
greater than 1, then he does not get any grace. If the number of subjects
he failed in is equal to 1, then the grace is of 5 marks per subject

Copyright © Department of Electrical Engineering – Usman Institute of Technology

Вам также может понравиться