Implementation of If , If-else and Switch Statement
If statement : If statement allows the compiler to test the condition first, and then, depending upon the result, it will execute the statements. If the test condition is true, then only statements within the if statement performed by the C compiler.
Syntax :
if (test condition)
{
Statement 1;
Statement 2;
Statement 3;
………….
Statement n;
}
|
Example :
#include<stdio.h>
#include<conio.h>
void main(){
int i=10;
if(i<=10){
printf(“value of i is less than or equal to 10”);
}
}
|
Output : value of i is less than or equal to 10
If-else statement :
If the test expression is evaluated to true,
- statements inside the body of if are executed.
- statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
- statements inside the body of else are executed
- statements inside the body of if are skipped from execution
Syntax :
if (condition) {
// execute if the test expression is true
}
else {
// execute if the test expression is false
}
|
Example :
#include<stdio.h>
#include<conio.h>
void main() {
int i;
printf("Enter value : ");
scanf("%d", &i);
if (i%2 == 0) {
printf("%d is even .",i);
}
else {
printf("%d is odd .",i);
}
}
|
Output :
Enter value : 5
5 is odd .
Switch statement : switch statement is used when you have multiple possibilities for the if statement. Switch case will allow you to choose from multiple options.the switch case allows you to set the necessary statements for the user.At the end of each block it is necessary to insert a break statement because if the programmers do not use the break statement, all consecutive blocks of codes will get executed from every case onwards after matching the case block.
Syntax :
switch(variable)
{
case 1:
//execute code
break;
case n:
//execute code
break;
default:
//execute code
break;
}
|
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Please enter a no numbers from 1 to 7 : ");
scanf("%d",&a);
switch(a)
{
case 1:
printf("Its Sunday");
break;
case 2:
printf("Its Monday");
break;
case 3:
printf("Its Tuesday");
break;
case 4:
printf("its Wednesday");
break;
case 5:
printf("Its thursday");
break;
case 6:
printf("Its Friday");
break;
case 7:
printf("Its Saturday");
break;
default :
printf("YOU HAVE ENTERED WRONG NUMBER");
break;
}
}
|
Output :
Please enter a no numbers from 1 to 7 : 8
YOU HAVE ENTERED WRONG NUMBER
For more JECRC University II Sem Computer Programming Lab Experiments CLICK HERE