Conditional Statements

If you want to perform any calculations or operations based on certain condition then we need to make use of conditional statement. Conditional statements are used to check the conditions. Another name for conditional statements is Decision making statements.
There are 5 types.

1. if statement


This statement is used to perform conditional operations. If the condition is true it produce the result otherwise no result.
syntax1:
if(condition)
statement1;
If the condition is true then statement1 will be executed.
If the condition is false then it will not execute the statement1.

To check the given number is valid number or not. 










Output




















syntax 2:
if(condition)
{
statement1;
statement2;
}
If the condition is true then statement1 and statement2 will be executed.
If the statement is a single statement {} are not required.
If the statements are more than one {} are mandatory.
/*read cost of all the items, if it is more than 1000 provide 10% discount and print it.*/


#include<stdio.h>
main()
{
float cai,bill,dis;
clrscr();
printf("Enter cost of all the items");
scanf("%f",&cai);
if(cai>=1000.0f)
{
dis=cai*10/100;
bill=cai-dis;
printf("\nThe Bill = %.2f",bill);
}
getch();
}
Syntax for both types:-
1:- if(<condition>)
statement1;
statement n;
 
If the condition is true or fail statement n will be executed.
/*to check the given number is valid number or not print messages. */
#include<stdio.h>
main()
{
float n;
clrscr();
printf("Enter a number");
scanf("%f",&n);
if(n)
printf("Within If\n");
printf("Outof If");
getch();
}
2:- if(<condition>)
{
statement1;
statement2;
}
statement n;
 
If the condition is true or fail statement n will be executed.
/*read cost of all the items, if it is more than 1000 provide 10% discount and print it. otherwise print the bill without discount.*/
#include<stdio.h>
main()
{
float cai,bill,dis;
clrscr();
printf("Enter cost of all the items");
scanf("%f",&cai);
bill=cai;
if(cai>=1000.0f)
{
dis=cai*10/100;
bill=cai-dis;
}
printf("\nThe Bill = %.2f",bill);
getch();
}

No comments:

Post a Comment