C if statement
The ‘if’ statement in C is used to control the C program flow based on the if condition. If the condition in the ‘if statement’ is true, then the block of code will be executed, otherwise, it will be skipped.
Syntax
If (condition)
{
…..
Code block;
…..
}
#includemain() { int a = 15; if (a<20) { printf("a is less than 20"); } }
Output
a is less than 20
C if-else statement
#includevoid main() { int a, b; printf("Enter the value for a: "); scanf("%d", &a); printf("\nPlease the value for b: "); scanf("%d", &b); if (a > b) { printf("\n a is greater than b"); } else { printf("\n b is greater than a"); } }
Enter the value for a: 5 Please the value for b: 10 b is greater than a
From the above program, the two numbers are compared and printed which number is greater.
Nested if-else statements
#includemain() { int x=5,y=10; if(x==5) { if(y==10) { printf("value of x is 5, and value of y is 10."); } } else { printf("x and y values are not 5 and 10"); } }
Output:
value of x is 5, and value of y is 10.
C else-if statements
This is an another if statement and used when if statements having multiple decisions.
Syntax
if (condition 1)
{
…..
Code block;
…..
}
else if(condition 2)
{
…..
Code block;
…..
}
else {
…..
Code block;
…..
}
Example Program
#includemain() { int a, b; printf("Enter the value for a: "); scanf("%d", &a); printf("\nEnter the value for b: "); scanf("%d", &b); if (a > b) { printf("\n a is greater than b"); } else if (b > a) { printf("\n b is greater than a"); } else { printf("\n Both are equal"); } }
Output
Enter the value for a: 5 Enter the value for b: 10 b is greater than a
In the above example program, else-if statement checks for another if condition. We can use as many else-if conditions in the code.
C goto Statement
In C, we have special type of Statements which does not execute based on some decisions or conditions. The goto statement in C are not based on any conditions but still it controls the flow. The goto statement is used to branch unconditionally within a program from one point to another. The use of goto statements are not encouraged in C programming but still it is used in some situations where the use of goto statements will be more desirable.
#includevoid main() { const int maxInput = 10; int i; double number, average, sum = 0.0; for (i = 1; i <= maxInput; ++i) { printf("%d. Enter a number: ", i); scanf("%lf", &number); // go to jump if the negative number is given if (number < 0.0) { goto jump; } sum += number; } jump: average = sum / (i - 1); printf("Sum = %.2f\n", sum); printf("Average = %.2f", average); }
Output
1. Enter a number: 10 2. Enter a number: 12 3. Enter a number: 4 4. Enter a number: -3 Sum = 26.00 Average = 8.67
Note: The goto statement in C program should be used very carefully as it may jump to out of the scope. The goto statements are used only when it is needed and useful for your code.