3 Conditional Structure - If and Switch
3 Conditional Structure - If and Switch
Control Structure
Books
if(condition)
{
// Statements to execute
// if condition is true
}
If statement - Example
if ( num1 == num2 )
{
cout<<"Both Numbers are equal "<<endl;
}
if ( marks >= 40 )
{
cout<<"Student is Pass !"<<endl;
}
else
{
cout<<"Student is Fail !"<<endl;
}
if( expression1)
{
variable = expression2;
}
else
{
variable = expression3; variable = Expression1 ? Expression2 : Expression3
}
Conditional or Ternary Operator (?:)
// C++ program to find largest among two numbers using ternary operator
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
variable = Expression1 ? Expression2 : Expression3
5. int n1 = 5, n2 = 10, max;
6. max = (n1 > n2) ? n1 : n2; If ( n1 > n2 )
7. cout << "Largest number = " << max; {
max = n1;
8. return 1;
} else
9. } {
max = n2;
}
Nested if statement
if (condition1)
{
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Multi-if or if-else-if statement
else
cout<<"Student is Fail !"<<endl;
#include "iostream"
using namespace std;
int main()
{
int marks;
cout<<"Enter Marks of the Student : ";
cin>> marks;
if ( marks >= 64 )
cout<<“A Grade !"<<endl;
else
cout<<"Student is Fail !"<<endl;
AND && Logical Multiplication, Output is true if all inputs are true
else
cout<<“Not a vowel !"<<endl;
}
Home Work
3. Write a C++ program to find whether a given year is a leap year or not.
4. Write a C++ program to read the age of a candidate and determine whether it is eligible for casting
his/her own vote. (18+ age is required to cast vote).
5. Write a C++ program which takes 3 numbers from user and find the largest of three numbers.
6. Write a program in C to read any day number in integer and display day name in the word.
7. Write a program in C to read any Month Number in integer and display the number of days for this
month.