if statement
The if statement evaluates a condition, if the condition is true then a true-block (a statement or set of statements) is executed, otherwise the true-block is skipped.The general syntax of the if statement is:
if (expression)
true-block;
statement-x;
In the above syntax, if is a keyword that should contain expression or condition which is enclosed within parentheses. If the expression is true (nonzero) then the true-block is executed and followed by statement-x are also executed, otherwise, the control passes to statement-x. The true-block may consists of a single statement, a compound statement or empty statement. The control flow of if statement and the corresponding flow chart is shown below.
#include<iostream>
using namespace std;
int main()
{
int qty, dis=0;
float rate, tot;
cout<<"\nEnter the quantity ";
cin>>qty;
cout<<"\nEnter the rate ";
cin>>rate;
if ( qty> 500)
dis=10;
tot = (qty * rate) - ( qty * rate * dis / 100);
cout<<"The total expenses is "<< tot;
return 0;
}
First Run
Enter the quantity 550
Enter the rate 10
The total expenses is 4950
Second Run
Enter the quantity 450
Enter the rate 10
The total expenses is 4500
In the first execution of the program, the test condition evaluates to true, since qty>
Therefore, the variable dis which is initialized to 0 at the time of declaration, now gets a new value 10. The total expenses is calculated using a new dis value.
In the second execution of the program, the test condition evaluates to false, since qty> 500. Thus, the variable dis which is initialized to 0 at the time of declaration, remains 0. Hence, the expression after the minus sign evaluates to 0. So, the total expenses is calculated without discount.
#include <iostream>
using namespace std;
int main()
{
int age;
cout<< "\n Enter your age: ";
cin>> age; if(age>=18)
cout<< "\n You are eligible for voting ....";
cout<< "This statement is always executed.";
return 0;
}
Enter your age: 23
You are eligible for voting….
This statement is always executed.
#include<iostream>
using namespace std;
int main()
{
int bonus,yr_of_ser;
cout<<"\nEnter your year of service ";
cin>>yr_of_ser;
if ( yr_of_ser> 3 )
{
bonus=2000;
cout<<"\n Your bonus is " <<bonus;
}
cout<<"\nCongratulations...";
return 0;
}
Enter your year of service 5
Your bonus is 2000
Congratulations...
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.