If-else statement
- It is similar to if statement i.e. It is also used to execute or ignore a set of statements after testing a condition.
- In if-else statement one condition and two blocks of statements are given.
- First blocks contain if statement with condition and its body part.
- Second is else and it contain only body part.
Syntax:
Explanation working of if-else statement
- A condition is a logical or relational expression and it produces either true or false result.
- If the condition is true the first block of if-else statement (which is if-statement) is executed and second is ignored and after executing the first block , the control is transferred to next statement after if -else structure.
- If the condition is false then the first blocks of statement is ignored and the second block of statement is executed. After the executing the second block of statement the control is transferred to next statement after if-else structure.
Possible Errors which can occur using if-else statement
- Else statement cannot be use without if statement
else
{
block of statement
}
compiler will indicate error like misplaced else statement
- Else statement cannot be use alone within the body of if statement
if(condition)
{
else
{
block of statement
}
}
Let take an example to implement if-else statement
Program to find number is Even or Odd using if-else statement
Code
- #include<iostream>
- using namespace std;
- int main()
- {
- int Num;
- cout<<"Enter Number to check it is Even or Odd: ";
- cin>>Num;
- if(Num%2==0)
- {
- cout<<"Number is Even";
- }
- else
- {
- cout<<" Number is Odd";
- }
- }
Categories:
c,
else,
if,
programming,
statement