Thursday, 23 July 2015

If else statements:Is your decision really yours?

First, you make your decisions, then your decisions make you who you are...
-Nikhil Sardana

The if else statements allow our program to make decisions. For instance,

int a=10;
if(a<100)
cout<<"The number is less than 100";
cout<<"Program ends";

The above code is self-explanatory. The statement just after the if statement gets executed if the condition is true. Since the value of a in our case is less than 100, the line "The number is less than 100" is displayed on screen. Let us say that the value of a is 200. Now, the line will NOT be displayed on the output screen.

But, the statement:
cout<<"Program ends";

Will be executed, irrespective of the value of a. So, "Program ends" will be displayed in both the cases.

You can use multiple if statements in your program. Ex:

char ch='a';
if(ch=='a')
cout<<"You entered a";
if(ch=='e')
cout<<"You entered e";

Homework: Create a working calculator to perform basic arithmetic operations. Input two numbers and a character from user . Check the value of the character i.e. whether it is +,-,%,* or %. Perform the required calculation based on the value of character entered.
Hint: Use multiple if statements and == operator.

Another statement used with if is the else statement. The else clause has no condition, and the statement after else is executed if the condition in preceding if statement is FALSE. For ex:

int a=4;
if(a>10)
cout<<"Greater than 10";
else
cout<<"Smaller than 10";

The above code will output:
Smaller than 10

If you want more than one statement to be a part of if or else, you can use braces {}. It is considered a good practice to use braces, even if there's a single statement because it enhances the readability of the program. For instance,

char ch='a';

if(ch=='a')
{
cout<<"The character is a\n";
cout<<"a is a vowel";
}
else
{
cout<<"The character is not a\n";
}

Here, the output will be:
The character is a
a is a vowel

To check whether the value of a variable is zero or not, you can use:
int a=10;
if(a)
cout<<"The value of a is non-zero";

Remember, every non-zero value is considered to be true.

You can check multiple conditions in the same if statement by using the AND (&&), OR(||) operators. For example:

int a=15,b=10,c=2;

if( (a>b)&&(b>c) )
{
cout<<"a is the greatest";
}

if( (b>a)||(b>c) )
{
cout<<"b is greater than either a or c or both";
}

Both these statements will execute in our case.

In next segment, we will talk about other if-else constructs and their usage. Keep reading!

No comments:

Post a Comment