Control structures, or control statements, 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 to which statement is to be executed next. Types of decision control structure:
Syntax:
if (condition) { statement 1; statement 2; . . statement n; }
Example 1: Input the user's age and check if it is eligible for a vote or not. x
#include<stdio.h>
int main()
{
int n;
printf("Enter Age: ");
scanf("%d",&n);
if(n>=18)
{
printf("User is eligible to vote.");
}
return 0;
}
In Output 1, the user entered value 20, which is greater than 18, so the condition is true, the message will print 'User is eligible to vote'. In Output 2, the user entered value 15, which makes the condition false, so no message will be printed. If you want to print a message when the condition is false, then use an if-else condition.
Syntax:
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: Rewrite the example 1 using an if-else condition.
#include<stdio.h>
void main()
{
int n;
printf("Enter Age:");
scanf("%d",&n);
if(n>=18)
{
printf("User is eligible to vote");
}
else
{
printf("User is not eligible to vote");
}
}
if (condition 1) { statement 1; } else { if (condition 2) { statement 2; } else { statement 3; } }
In the above example, if condition 1 is true, the first block of statements will be executed, rest of the conditions will not be executed nor checked. If condition 1 is false and condition 2 is true, then the 2nd block of statements will be executed, and the 3rd block will not be checked. If condition 1 and condition 2 are false, then the 3rd block of statements will execute.
Example 3: Input 3 numbers and find the greater number.
#include<stdio.h>
void 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");
}
}
}
C Language Feedback, Questions, Suggestions, Discussion.
Ad: