C if statement
Normally a conditional statement is used in programming for decision making. In this chapter, if you learn how to make decisions using conditional statements.
In C programming, there are three types of if conditional statements:
If-if
If ... Els-if ... else
If ... Elsief ... Els - if ... elseif ... else
C if statement
if (testExpression)
{
// This code will be executed.
}
Here if we evaluate testExpression first.
If testExpression is true (not zero) then statement / statements in if block will be edited.
If testExpression is False, then the statement / statements in the if block will be avoided.
When the value of testExpression is true and when it is false, it is discussed in our relational and logical operators page.
if statement flowcharts
Flowchart of if statement
For example: C if statement
// Program for displaying user positive number on screen.
// The user will not be shown on the screen when negative number inputs.
#include <stdio.h>
int main ()
{
int testNumber;
printf ("Enter an unsigned integer:");
scanf ("% d", & testNumber);
// testNumber's value is greater than 0 if test expression is true.
if (testNumber> 0)
{
printf ("You entered% d. \ n", testNumber);
}
printf ("If the statement is easy in C programming.");
return 0;
}
Output 1
Enter an unsigned integer: 5
You entered 5
The if statement is easy in C programming
The test expression (testNumber> 0) is true when the user enters 5. So your entered 5 appears.
Output 2
Enter a integer: -6
The if statement is easy in C programming
When the user enters the -6, the test expression (F. TestNumber <0) is false. So the compiler avoids the inside statement.
To give a better understanding of the if statement, there is another example
#include <stdio.h>
int main ()
{
int i;
/ * It's always true * /
if (1) {
printf ("This should be printed. \ n");
}
/ * It is never true * /
if (0) {
printf ("This should not be printed. \ n");
}
/ * We can use "else" * /
if (0) {
printf ("This should not be printed. \ n");
}
else {
printf ("This 'else' part should be printed \ n");
}
i = 1;
/ * When there is only one statement, if someone wishes, and may not use it. * /
if (i == 1) {
printf ("This is a branch without the braces {and}. \ n");
}
/ * Be careful about the equal (=) sign? * /
if (i = 100) {
printf ("Beware of equals sign in if statements. \ n");
}
return 0;
}
Output
This should be printed
This 'else' part should be printed
This is a branch without the braces {and}
Beware of equals sign in if statements


0 Comments