Lecture 2
Lecture 2
Contents
▪ Type Casting
▪ Conditions
If
else
else if
▪ Switch
Type Casting
• Converting one datatype into another is known as type casting.
#include<iostream>
#include<iostream>
using namespace std;
using namespace std;
int main()
int main()
{
{
float a= 3.45; float b= 4.57;
float a= 3.45; float b= 4.57;
int z;
float z = a + b;
z= (int)a + (int) b;
cout<< z; //output 8.02
cout<< z; //output 7
return 0;
return 0;
}
}
Conditions
• C++ has the following conditional statements:
1. Use if to specify a block of code to be executed, if a specified
condition is true
2. Use else to specify a block of code to be executed, if the same
condition is false
3. Use else if to specify a new condition to test, if the first
condition is false
Conditions... (if)
• Use the if statement to specify a block of C++ code to be executed if
a condition is true.
• Syntax--
if (condition)
{
// block of code to be executed if the condition is true
}
Conditions... (if)
#include<iostream>
#include<iostream>
using namespace std;
using namespace std;
int main()
int main()
{
{
int a=15; int b=20;
if(15>10)
if(a<b)
{
{
cout<<"15 is greater than 10";
cout<<"b is greater than a";
}
}
return 0;
return 0;
}
}
Conditions...(else)
• Use the else statement to specify a block of code to be executed if
the condition is false.
• Syntax-
if (condition)
{
// block of code to be executed if the condition is true
} else
{
// block of code to be executed if the condition is false
}
Conditions...(else)
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main() {
int main() {
int number = 90;
int number = 90;
if (number > 80)
if (number < 80) {
{
cout << "Hey I get A+";
cout << "Hey I get A+";
} else {
} else{
cout << "Hey I get A";
cout << "Hey I get A";
}
}
return 0;
return 0;
}
}
Conditions...(else if)
• Use the else if statement to specify a new condition if the first
condition is false.
• Syntax-
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is
true
} else {
// block of code to be executed if the condition1 is false and condition2 is
false
}
Conditions...(else if)
#include <iostream> #include <iostream>
using namespace std; using namespace std;