Items in this page:
if (x == 3) printf("The if condition is fulfilled!\n"); printf("The if condition is not fulfilled!\n");
if (condition) { statement(s); } next_statement;
|
If other than 3 is entered, the output is shown below. The if statement is skipped because x == 3 is false. Take note about the different between = and ==.
By expanding the simplest if statement, theif-else constructs make C/C++ more flexible in selecting options based on several conditions. For example:
#include<stdio.h>
int main(void)
{
int x;
printf("Enter an integer: \n");
scanf_s("%d", &x, 1);
if(x == 3)
{
printf("x = %d\n", x);
printf("The if condition is fulfilled!\n");
}
else
{
printf("x = %d\n", x);
printf("The if condition is not fulfilled!\n");
}
return 0;
}
| |
| |
|
The general form is given below.
if (condition)
{
statement 1;
}
else
{
statement 2;
}
next_statement;
Again, by expanding the if-else statement, we can build a program with any number of conditions and the respective options.
|
|
Program input and output samples are given below.
The general form is shown below.
if (condition1)
{
statement 1;
}
else if (condition2)
{
statement 2;
}
else if(...)
}
statement ...;
}
next_statement;
Another variation is checking several conditions for an option. In this if construct, every if must be matched with the else. For example:
#include<stdio.h>
int main(void)
{
int year, train;
char curr_post;
printf("Are you qualified for a Manager promotion?\n");
printf("Enter the number of year: ");
scanf_s("%d", &year, 1);
printf("Enter the number of training received: ");
scanf_s("%d", &train, 1);
printf("Enter your current post(J - Junior, S - Senior, A - Asst. Manager): ");
// don't forget the space before %c else the execution will stop prematurely...
scanf_s(" %c", &curr_post);
if(year >= 10)
if(train >= 5)
if(curr_post =='A' ||'a')
printf("Qualified to be promoted to Manager!\n");
else
{
printf("Become Assistant Manager first.\n");
printf("Need more training.\n");
printf("Need more experience.\n");
}
else
{
printf("Need more training.\n");
printf("Need more experience.\n");
}
else
printf("Need more experience.\n");
return 0;
}
A sample input and output is shown below.
In this example, to be promoted to a manager post, all the three if statements must be true.
InWin32 Tutorial you will notice that the if statement is very useful for simple C/C++ code troubleshooting. We can test/verify/check by skipping certain line of codes to verify whether the error is generated by the skipped code.