Control Statements in C
Control Statements in C
If-Else:
The if-else statement is used to express decisions. Formally the syntax is
if (expression)
statement1
else
statement2
#include<stdio.h>
int main() {
int a = 10, b = 5;
if(a > b)
printf("a is greater than b\n");
else
printf("b is greater than a\n");
return 0;
}
If-Else Ladder:
The if-else ladder statement is used to express multiple decisions. Formally the syntax is
if(expression)
statement1
else if(expression)
statement2
else if(expression)
statement3
else
statement4
#include<stdio.h>
int main() {
int a = 10, b = 25, c = 20;
if (a > b)
printf("a is greater than b\n");
else if (c > b)
printf("c is greater than b\n");
else
printf("b is greater than a, c\n");
return 0;
}
Switch:
The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly. Formally the syntax is
switch (expression) {
case 'exp':
statements
case 'exp':
statements
default:
statements
}
#include<stdio.h>
int main() {
int a = 2;
switch(a) {
case 1:
printf("this is date\n");
break;
case 2:
printf("this is month\n");
break;
case 3:
printf("this is year\n");
break;
default:
printf("This is default case\n");
}
return 0;
}
For Loop:
The For loop first is value initialization, second is a Condition and the third is variable will b increment or decrement. If the condition is true execute the statements and increments the value. Formally syntax is
for (initilization; condition; increment)
statement
#include<stdio.h>
int main() {
int i, a=0;
for(i = 0; i < 5; i++) {
a = a+i;
}
printf("%d\n", a);
return 0;
}
While loop:
In the While loop, the first expression evaluates. If it is non-zero, the statement executes and the expression re-evaluates. This cycle continues until expression becomes zero, at which point execution resumes after statement. Formally The syntax is
while (expression)
statement
#include<stdio.h>
int main(){
int a = 0,i = 0;
while( i < 5) {
a = a+i;
i++;
}
printf("%d \n", a);
return 0;
}
Do While:
In The do-while, the first statement executes, then conditions evaluate. If it is true, the statement evaluates again, and so on. When the expression becomes false, the loop terminates. Formally syntax is
do
statement
while(condition)
#include<stdio.h>
int main() {
int a =0, i =0;
do {
a = a+i;
i++;
} while(i<5);
printf("%d \n", a);
return 0;
}
Break and Continue:
Control Statements in C, The break statement provides an early exit from for, while, and do-while, just as from switch. The continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do-while loop to begin.
#include<stdio.h>
int main() {
int a =0, i =0;
do {
if (i == 3)
break;
a = a+i;
i++;
} while(i<5);
printf("%d \n", a);
return 0;
}
#include<stdio.h>
int main() {
int a =0, i =0;
do {
i++;
if (i == 3)
continue;
a = a+i;
} while(i<5);
printf("%d \n", a);
return 0;
}
Recent Comments