# Condition determination for C language beginner's basic tutorial

• 2020-05-30 20:50:55
• OfStack

(1) if... else

Write a program first

``````
#include <stdio.h>

int main()
{
int x = -1;
if(x > 0)
{
printf("x is a positive number!\n");
}
else
{
printf("x is not a positive number!\n");
}

return 0;
}

``````

Operation results:

`x is not a positive number!`

Program analysis:

Define an integer x and assign it a value. This value is either greater than 0 or not greater than 0.
If it is greater than 0, print x is a positive number!
If it is not greater than 0, print x is not a positive number!

Instead of using an online compiler, it is recommended to use a native compiler (apple recommends Xcode, PC recommends dev C + +). If you set a breakpoint step on the native compiler, you will find that only one of the printf statements in if and printf statements in else will be executed. This is because if and else are mutually exclusive and cannot both be executed.

(2) if... else if... else

Change the program a little bit

``````
#include <stdio.h>

int main()
{
int x = 0;
if(x > 0)
{
printf("x is a positive number!\n");
}
else if(x == 0)
{
printf("x is zero!\n");
}
else
{
printf("x is a negative number!\n");
}

return 0;
}

``````

Operation results:

`x is zero!`

Program analysis:
If there are more than two conditions, if... else if... else... In the sentence.
The conditions in this program are divided into three categories: greater than 0, equal to 0, or less than 0.
Greater than 0 prints x is a positive number!
If it's equal to 0, it prints x is zero!
Less than 0 prints x is a negative number!

Note that x == 0, where the equals sign is two, not one.
In C, an equal sign means an assignment, such as b = 100;
Two equal signs indicate whether the left and right sides of the equal sign are equal.

(3) the use of multiple else if

``````
#include <stdio.h>

int main()
{
int x = 25;
if(x < 0)
{
printf("x is less than 0\n");
}
if(x >= 0 && x <= 10)
{
printf("x belongs to 0~10\n");
}
else if(x >= 11 && x <= 20)
{
printf("x belongs to 11~20\n");
}
else if(x >= 21 && x <= 30)
{
printf("x belongs to 21~30\n");
}
else if(x >= 31 && x <= 40)
{
printf("x belongs to 31~40\n");
}
else
{
printf("x is greater than 40\n");
}

return 0;
}

``````

Operation results:

`x belongs to 21~30`

Program analysis:
(1)
The value of x is divided into several intervals :(negative infinity, 0), [0, 10], [11, 20], [21, 30], [31, 40], (40, positive infinity).
(negative infinity, 0) is determined by if
[0, 10], [11, 20], [21, 30], [31, 40] are judged by else if
(40, plus infinity) is determined by else

(2)
The symbol" & & "Stands for" and ", meaning" & & "The judgment condition is only true when the conditions on both sides are true.

Related articles: