Decision making with if statement and else..if
Decision making
what is decision making?
hello! everyone today we are go in the order of execution of statement based on certain condition,or a repeat a group of a statement until certain specified condition are met this involves a kind ofdecision making to see weather a particular condition has occured or not and then direct the computer to execute certain statement accordingly.
c language possess such decision making capabilities by supporting the following statements:g to study if statement and else...if statement.
we have seen that a C program is a set of a statement whicsituationh are normally executed sequentially in a order in which they appear.
we have a number of situation where we may have to change
1.if statement
2. switch statement (will study in next tutorial)
3. conditional operator statement
4. go to statement
1. if statement
syntax- if (test expression)
if statement consist of a condition and a test statement when this test condition
is true then next statement will run.
Some example of decision
making.using if statement :
1.if (bank balance is zero)
Borrow money
2.if (room is dark)
Put on lights
3.if (code is 1)
Person is male
4.if (age is more than 50)
Person is retired
If statement may be implemented
in different forms the different forms are:
1.simple if statement
2.if…..else statement
3.nested if…..else statement
4.else if ladder
1.Simple if statement
The general form of simple if
statement is
if(test expression)
{
Statement-block;
}
Statement-x;
2.if….else statement
The if…else statement is an
extension of the simple if statement.the general forms is….
If(test expression)
{
True-block statement(s)
}
Else
{
False-block statement(S)
}
Statement-x
First we check 1st
condition if this condition is false then compiler moves to else part to
procced.
Example:-
// odd even by if else.......
#include<stdio.h>
main()
{
int a;
printf("enter the number u want to check:");
scanf("%d",&a);
if(a%2==0){
printf("given number is
even:");
}
else printf("number is odd:");
return 0;
}
3.Nesting of if…else statement
When a series of decision are
involved we may have to use to more than one if…else statements
In nesting as shown here:
if(test conditon-1)
{
if(test-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-x;
4. The else…if ladder
There is another way of putting ifs toegther
when multipath decision are involved.a multiipath decision is a chian of ifs in
which the each else is an if.it take following general form.
if (condition 1)
Statement-1;
else if( condition 2)
Statement-2;
else if(condition 3)
Statement-3;
else
Default-statement;
Statement-x;
MCQs based on if ans else..if statement
void main()
{
int x = 0;
if (x == 0)
printf("hiii");
else
printf("how are you");
printf("hellooo");
}
b) how are you
c) hellooo
d) hihellooob) Run time error
c) Helloo
d) Varies
Comments
Post a Comment