Control structure or control statement hold the execution of a program by any condition or decision. Control structure specifies the order in which the various instructions in a program are to be executed by the computer. Control structure determines the flow of control in a program.
There are 3 types of control structures or control statements:
Decision Control Structure allows the computer to take a decision as which statement is to be executed next. Types of Decision control structure:
if (condition) { statement 1; statement 2; . . statement n; }
Example 1: Input user's age and check it is eligible for vote or not.
#include<stdio.h> int main() { int n; printf("Enter Age: "); scanf("%d",&n); if(n>=18) { printf("User is eligible for vote"); } return 0; }
In Output 1, user entered value 20 which is greater than 18, so the condition is true, the message will print 'User is eligible for vote'. In Output 2, user entered value 15, makes the condition false, no message will be printed. If you want to print a message when the condition is false, than use if-else condition.
if (condition) { //execute if condition is true statement 1; statement 2; . . statement n; } else { //execute if condition is false statement 1; statement 2; . . statement n; }
Example 2: Re-write the example 1 using if-else condition.
#include<stdio.h> int main() { int n; printf("Enter Age:"); scanf("%d",&n); if(n>=18) { printf("User is eligible for vote"); } else { printf("User is not eligible for vote"); } return 0; }
if (condition 1) { statement 1; } else { if (condition 2) { statement 2; } else { statement 3; } }
In the above example, if condition 1 is true first block of statements will be executed, rest of the condition will not executed nor checked. If condition 1 is false and condition 2 is true, than 2nd block of Statements will be executed, 3rd block will not be checked. If the condition 1 and condition 2 is false than 3rd block of statements will execute.
Example 3: Input 3 numbers and find greater number.
#include<stdio.h> int main() { int a, b, c; printf("Enter 3 numbers:"); scanf("%d%d%d",&a,&b,&c); if(a>b && a>c) { printf("A is greater"); } else { if(b>a && b>c) { printf("B is greater"); } else { printf("C is greater"); } } return 0; }