Thursday, September 24, 2009

CONDITIONAL STATEMENTS

Conditional statements controls the sequence of statements, depending on the condition


Relational operators:

Relational operators allow comparing two values.

==   is equal to

!=    not equal to

<     less than

>    greater than

<= less than or equal to

>= greater than or equal to

Complex logical operators:

It can combine expressions to get complex logical expressions

&&      and

||          or


1) Simple If statement

2) If-else statement

3) if-else if statement

4) Nested if statement

SIMPLE IF STATEMENT:

It execute if condition is TRUE

Syntax:

if(condition)

{

Statement1;

.....

Statement n;

}





Example:


main()

{

int a,b;

printf(“Enter a,b values:”);

scanf(“%d %d”,&a,&b);

if(a>b)

printf(“\n a is greater than b”);

}

OUTPUT:

Enter a,b values:20

10

a is greater than b

IF-ELSE STATEMENT:

It execute IF condition is TRUE.IF condition is FLASE it execute ELSE part

Syntax:

if(condition)

{

Statement1;

.....

Statement n;

}

else

{

Statement1;

.....

Statement n;

}




Example:

main()

{

int a,b;

printf(“Enter a,b values:”);

scanf(“%d %d”,&a,&b);

if(a>b)

printf(“\n a is greater than b”);

else

printf(“\nb is greater than b”);

}

OUTPUT:

Enter a,b values:10

20

b is greater than a

IF-ELSE IF STATEMENT:

It execute IF condition is TRUE.IF condition is FLASE it checks ELSE IF part .ELSE IF is true then execute ELSE IF PART. This is also false it goes to ELSE part.

Syntax:

if(condition)

{

Statement1;

.....

Statementn;

}

else if

{

Statement1;

.....

Statementn;

}

else

{

Statement 1;

.....

Statement n;

}

Example:

main()

{

int a,b;

printf(“Enter a,b values:”);

scanf(“%d %d”,&a,&b);

if(a>b)

printf(“\n a is greater than b”);

else if(b>a)

printf(“\nb is greater than b”);

else

printf(“\n a is equal to b”);

}

OUTPUT:

Enter a,b values:10

10

a is equal to b

NESTED IF STATEMENT:

To check one conditoin within another.

Take care of brace brackets within the conditions.

Synatax:

if(condition)

{

if(condition)

{

Statement 1;

...

Statement n;

}

}

else

{

Statement 1;

....

Statement n;

}

Example:

main()

{

int a,b;

printf(“\n Enter a and b values:”);

scanf(“%d %d ”,&a,&b);

if(a>b)

if((a!=0) && (b!=0))

printf(“\na and b both are positive and a is greater than b);

else

printf(“\n a is greater than b only”)

else

printf(“ \na is less than b”);

}

Output:

Enter a and b values:30

20

a and b both are positive and a is greater than b





No comments:

Post a Comment