Computers Windows Internet

If else syntax. Conditional operators. Greeting script depending on the time of day

Some sources say that the select statement if else is independent operator... But it is not, if else is just a notation of the if selection statement. The if else statement allows the programmer to define an action when a condition is true and an alternative action when a condition is false. Whereas if allowed to define an action under a true condition.

The syntax for writing the select statement if else is:

If (/ * checked condition * /) (/ * body of the selection operator 1 * /;) else (/ * body of the selection operator 2 * /;)

It reads like this: “If the checked condition is true, then select statement body 1, otherwise (that is, the checked condition is false) select statement body 2". Notice how the if else statement is written. The else word is deliberately shifted to the right to program code was understandable and easy to read.

Let's look at the problem from the previous topic using if else. Let me remind you the condition of the problem: "You are given two numbers, you need to compare them."

// if_else.cpp: defines the entry point for the console application. #include "stdafx.h" #include using namespace std; int main (int argc, char * argv) (int a, b; cout<< "Vvedite pervoe chislo: "; cin >> a; cout<< "Vvedite vtoroe chislo: "; cin >> b; if (a> = b) // if a is greater than or equal to b, then (cout<< a << " >= " << b << endl; } else // иначе { cout << a << " <= " << b << endl; } system("pause"); return 0; }

In this code, we are interested inlines 14-20... These lines are read like this: if a (first number) greater than or equal b (second number), then execute the output statement inline 16

Cout<< a << " >= " << b << endl;

otherwise execute the output statement in line 19

Cout<< a << " <= " << b << endl;

In this ife, we use relation operations> = and<= . Условие перехода не совсем правильно, так как условие будет ложно только в том случае, если первое число будет меньше второго, во всех остальных случаях условие истинно. Значит, line 19 should be written like this

Cout<< a << " < " << b << endl; // в кавычках записать не меньше или равно, а просто меньше.

And this is how the program worked (see Figure 1).

Vvedite pervoe chislo: 15 Vvedite vtoroe chislo: -4 15> = -4 Press any key to continue. ... ...

Figure 1 - Operator of choice if else

Let me show you another example of using the if else selection statements (the so-called nested if else statements for multiple selection).

The task:
Create an algorithm that finds the value of y, if y = x, for x<0; у=0, при 0<=х<30; у=х 2 , при х>=30;

// inif_else.cpp: defines the entry point for the console application. #include "stdafx.h" #include using namespace std; int main (int argc, char * argv) (int x, y; cout<< "Vvedite x: "; cin >> x; if (x< 0) { y = x; // выполняется, если х меньше нуля } else { if ((x >= 0) && (x< 30)) { y = 0; // выполняется, если х больше либо равно нуля и меньше 30 } else { if (x >= 30) (y = x * x; // executed if x is greater than or equal to 30))) cout<< "y=" << y << endl; system("pause"); return 0; }

In this problem, three cases are possible:
1st case: x< 0 ;
2nd case: x lies in the range from 0 (including 0) to 30;
3rd case: x is greater than or equal to 30.

Notice the innovation !! V 17 line notation like this: if ((x> = 0) && (x< 30)) , i used symbols && - this. Boolean operation AND&& is needed to combine several simple conditions into one compound. In our case, it is necessary to check the truth of two conditions: the first - x> = 0, the second - x< 30 . Все проверяемое условие будет истинно, если истинны два простых условия. В математике правильной записью считается такая запись: 0 <= x < 30 , а в С++ правильной записью считается вот такая запись: (x >= 0) && (x< 30) или такая 0 <= x && x < 30 . Кстати круглые скобочки () && () не обязательны, так как условия простые, но для уверенности, я прописываю, всегда, данные скобочки и вам советую.

Analysis of a particular case:

Let's say the user entered the number 31. Starting from line 12, the conditions are checked. It reads like this: “If x (31 in our case)< 0, то выполнить оператор в line 14". But since 31> 0 the condition is false, we go to the word else (otherwise) line 15... Next, we check if the number 31 is in the specified interval. It reads like this: if x> = 0 and x<30then execute the statement on line 19 ... But since the number 31 is not included in the specified interval, the condition is false. In detail line 17: the program will first check the first simple condition x> = 0 - it is true, and if the first is true, then the program will go on to check the second simple condition x< 30 – оно ложно. Следовательно всё составное условие ложно, ведь в составном условии у нас используется логическая операция && , а это значит, что все составное условие истинно только в том случае, когда истинны оба простых условия. Переходим к else (иначе), здесь у нас последний if , (line 22). Checking x> = 30 is performed. It reads like this: If x> = 30 then execute the operator on line 24 ... Finally, the condition is true, so the statement in line 24... AND line 28 prints the resulting value. Well, everyone, examined the program in the smallest detail. The result of the program, if the user entered the number 31 (see Figure 2)

Please suspend AdBlock on this site.

Now that we have figured out the conditional expressions, we can move on to the main topic of the lesson - conditional operator.

If - else statement template

There are two main options here:

Listing 1.

// first option if (conditional_expression) operator_1; // second option if (conditional_expression) operator_1; else operator_2;

And the pictures, of course. Where can we go without pictures?

Fig.1 Block diagrams of the operator if-else.

This operator works like this. The value of the conditional expression is evaluated. If true, then statement_1 from the main branch is executed, and if false, then either nothing happens (in the first version), or statement_2 from the side branch is executed (in the second version).

I propose to immediately understand the examples. For example, what do you think the following code will display? Check your guess.

Listing 2.

#include int main (void) (if (1) printf ("TRUE! \ n"); else printf ("FALSE! \ n"); return 0;)

Well yes, that's right, it will output TRUE! ... The condition is true. Have you forgotten that one is the truth? I'll tell you something terrible now. Any nonzero number is considered true. Check it out for yourself.

Okay, now here's an example. What do you think this program will display?

Listing 3.

#include int main (void) (if (0) printf ("FALSE! \ n"); return 0;)

I hope you gave the correct answer and you were not confused by the line with the FALSE output! which I added on purpose to confuse you. Yes, this program will not output anything. The condition in parentheses is false, which means that the statement will not be executed. Everything is according to the rules.

Let's take another example to solidify. Be extremely careful, I have prepared everyone there for you. So what will this code output?

Listing 4.

#include int main (void) (int x = 12; if (! (! (x% 3 == 0) &&! (x% 2 == 0))) printf ("kratno \ n"); else printf ("ne kratno \ n "); return 0;)

I believe that you have succeeded! If it didn't work out, don't worry - there will still be time to practice.

Well, now let's talk about the nuances - they, as usual, are available.

Each branch of a conditional operator can contain only ONE operator.

Here's an example.

Listing 5.

#include < 0) printf("x = %d\n", x); x = (-1)*x; printf("%d\n", x); return 0; }

It seems that the program should work like this. The user enters an integer. If the number is less than zero, then we change its sign to the opposite. Otherwise, we do nothing. After that, we display the number on the console screen.

Now pay attention to the screen.


Fig. 2 The result of the program Listing 11

But there is a solution! And this solution is - compound operator ()... If we enclose multiple statements in curly braces, they will be treated as one single statement. Therefore, in order for the program to work correctly, we add a compound operator to it:

Listing 6.

#include int main (void) (int x = 0; scanf ("% d", & x); if (x< 0){ printf("x = %d\n", x); x = (-1)*x; } printf("%d\n", x); return 0; }

Well, now everything is as it should be. Check it yourself. By the way, from experience. I strongly advise you to always use curly braces, even if there is one operator inside them. Very often, this avoids stupid mistakes.

Any language construct can be used inside the if-else control construct, including one more if-else construct.

For example:

Listing 7.

#include int main (void) (int x = 0; scanf ("% d", & x); if (x< 0) { printf("Negative!\n"); } else { if (x == 0){ printf("Zero!\n"); } else { printf("Positive!\n"); } } return 0; }

I think it is clear that using nested conditional statements, you can make a construction similar to the switch selection statement.

The use of nested conditionals introduces another quirk.

else always refers to the closest if that does not have its else

For example:

Listing 8.

If (n> 0) if (a> b) z = a; else z = b;

According to our rule, else refers to the inner (second) if. If we want else to refer to the outer (first) if, then we can use the compound operator.

Listing 9.

If (n> 0) (if (a> b) z = a;) else z = b;

As I mentioned, it is best to always use curly braces to avoid misinterpretation of the notation. It is very difficult to search for such errors in programs. Pay attention also to the indentation. I use them to make it immediately clear from the code which branch belongs to which if.

The lesson will cover php conditional statements: the if statement and the switch statement

The php conditional statements are represented by three main constructs:

  • condition operator if,
  • switch operator switch
  • and ternary operator.

Let's take a closer look at each of them.

PHP if statement

Fig 3.1. Conditional IF statement, shortened version


Rice. 3.2. IF ELSE conditional statement syntax


Rice. 3.3. Complete syntax for IF elseif conditional statement

Let's summarize:

The complete syntax is:

if (condition) (// if the condition is true operator1; operator2;) elseif (condition) (operator1; ...) else (// if the condition is false operator1; operator2;)

  • The shortened syntax can do not contain part of the construction with else and do not contain an additional condition elseif
  • Instead of the function word elseif, you can write else if (separately)
  • There can be several elseifs in one if statement. The first encountered elseif expression equal to TRUE will be executed.
  • If there is an alternative condition elseif, the else clause must come last in the syntax.

A colon: can be used in a conditional statement instead of curly braces. In this case, the operator ends with the service word endif

Rice. 3.4. If and Endif conditional statement in php

Example:

if ($ x> $ y): echo $ x. "greater than". $ y; elseif ($ x == $ y): // when using ":" you cannot write separately else if echo $ x. "is equal to". $ y; else: echo $ x. "not> and not =". $ y; endif;

Important: When using a colon instead of curly braces elseif, you cannot write in two words!

Logical operations in a condition

The following operations can be present in the if clause in parentheses:

Example: check the value of a numeric variable: if it is less than or equal to 10, display a message "Number less than or equal to 10", in the opposite case, issue a message "Number is greater than 10"


Solution:

$ number = 15; if ($ number<=10) { echo "число меньше или равно 10"; } else { echo "число больше 10"; }

Blocks of php code can be broken, consider an example:

Example: Display html code "A is equal to 4" if the variable $ a is indeed 4


1 Solution:
1 2 3 4

2 Solution:

1 2 3 A equals 4

A equals 4

Php job 3_1: Display translation of colors from in English into Russian, checking the value of the variable (in which the color is assigned: $ a = "blue")


Php job 3_2: Find the maximum of three numbers

Comparison operations and the rule of lies

In the if statement, there must be a logical expression or a variable in parentheses that is considered from the point of view of logic algebra, returning values ​​either true or false

Those. a single variable can be used as a condition. Let's consider an example:

1 2 3 4 $ a = 1; if ($ a) (echo $ a;)

$ a = 1; if ($ a) (echo $ a;)

In the example, the translator php language will consider the variable in parentheses for the rule of lies:

The rule of LIE or what is considered to be false:

  • logical False
  • integer zero ( 0 )
  • valid zero ( 0.0 )
  • empty line and the line «0»
  • array without elements
  • object without variables
  • special type NULL

Thus, in the considered example, the variable $ a is equal to one, respectively, the condition will be true and the operator echo $ a; will display the value of the variable.

Php job 3_3: given a variable a with a string value. If a is equal to the name, then output "Hello name!", if a is equal to an empty value, then output "Hi stranger!"

Logical constructs AND OR and NOT in a conditional operator

  1. Sometimes it is necessary to provide for the fulfillment of several conditions at the same time. Then the conditions combine logical operator AND — && :
  2. $ a = 1; if ($ a> 0 || $ a> 1) (echo "a> 0 or a> 1";)

  3. To indicate that the condition is false, use logical NOT operator — ! :
  4. 1 2 3 4 $ a = 1; if (! ($ a< 0 ) ) { echo "a не < 0" ; }

    $ a = 1; if (! ($ a<0)) { echo "a не < 0"; }

Switch PHP statement

The switch statement or "switch" replaces several consecutive if statements. In doing so, it compares one variable with a set of values. Thus, it is the most convenient remedy. for organizing multi-branching.

Syntax:

1 2 3 4 5 6 7 8 9 10 switch ($ variable) (case "value1": statement1; break; case "value2": statement2; break; case "value3": statement3; break; [default: statement4; break;])

switch ($ variable) (case "value1": statement1; break; case "value2": statement2; break; case "value3": statement3; break;)

  • The operator can check both string values ​​(in which case they are indicated in quotes) and numeric (without quotes).
  • The break statement in the construction is required. It exits the construction if the condition is true and the operator corresponding to the condition is executed. Without break, all case statements will be executed regardless of their truth.

Rice. 3.5. Conditional Switch statement


Example: an array with full masculine names is given. Check the first element of the array and, depending on the name, issue a greeting with a short name.


Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 $ names = array ("Ivan", "Peter", "Semyon"); switch ($ names [0]) (case "Peter": echo "Hello, Petya!"; break; case "Ivan": echo "Hello, Vanya!"; break; case "Semyon": echo "Hello, Vanya! "; break; default: echo" Hello, $ names! "; break; )

$ names = array ("Ivan", "Peter", "Semyon"); switch ($ names) (case "Peter": echo "Hello, Petya!"; break; case "Ivan": echo "Hello, Vanya!"; break; case "Semyon": echo "Hello, Vanya!"; break ; default: echo "Hello, $ names!"; break;)

Php job 3_4:

  • Create a variable $ day and assign it an arbitrary numeric value
  • Use the switch statement to output the phrase "This is a working day" if the value of the variable $ day falls within the range of numbers from 1 to 5 (inclusive)
  • Output the phrase "It's a day off" if the value of the variable $ day is 6 or 7
  • Output the phrase "Unknown day" if the value of the variable $ day is not in the range of numbers from 1 to 7 (inclusive)

Complete the code:

1 2 3 4 5 6 7 8 9 10 11 12 ... switch (...) (case 1: case 2: ... echo "This is a working day"; break; case 6: ... default: ...)

Switch (...) (case 1: case 2: ... echo "This is a working day"; break; case 6: ... default: ...)

PHP ternary operator

Ternary operator, i.e. with three operands, has a fairly simple syntax, in which to the left of the? the condition is written, and on the right - two operators separated by the sign:, to the left of the sign the operator is executed if the condition is true, and to the right of the sign: the operator is executed if the condition is false.

condition? operator1: operator2;

12.09.2017

Not yet


Hello everyone!
Continuing to learn PHP basics from scratch!
In this tutorial, I will tell you about if else condition statement... Literally, if means "if", and else means "otherwise." The if else construction itself helps to check the data and display the result (display messages, execute some command, redirect the user to a secret page or let him into the admin panel). To learn how to write the conditions correctly and understand the if else construction, I will give you a real life example that is very similar to the if else construction.
You give your brain a command: as soon as the alarm sounds (6:00), I have to get up, wash my face, brush my teeth, get dressed and gallop to work. If the alarm does not ring at 6:00, then you can sleep, since you do not need to run to work.
Did you notice the if else statement? The precondition will be the set alarm time "6:00". If the alarm clock rings, then we get up and run to work, if it doesn't ring (otherwise, they still say a lie), then we sleep on.
You can create a lot of such examples of life, for example: if it rains, then I sit at home, if there is no rain, then I take the ball and go to play football.
So how can you write the if else construction? Very simple.
Let's go step by step and start with a simple condition - the if statement.

For a better understanding, I have drawn the diagram of the if statement in the form of a picture:

Now let's try to transform the life example I gave above into php code.

If you save a php file with this code and open it through a local server (see), the result will be:

⇒ Explanation of the code:
In the condition, I compared the variable $ weather with the value "rain" (line # 3). In human terms, this code sounds like this: if the variable $ weather is equal to the value "rain", then you need to display the text " I am sitting at home". By the way, let me remind you (if you forgot a little) that the equal sign is denoted by a double equal sign, like this (==). If you write another value to the $ weather variable (line number 2), for example, snow, then the browser will blank page as conditions were not met.

→ PATTERN CODE "CONSTRUCTION if":

→ Cheat sheet:

Equality: ==
Example: if ($ a == $ b)

Not equality:! =
Example: if ($ a! = $ B)

More:>
Example: if ($ a> $ b)

Less:<
Example: if ($ a< $b)

Greater than or equal:> =
Example: if ($ a> = $ b)

Less or equal:<=
Example: if ($ a<= $b)

Logical "and": and
Example: if ($ a == $ b and $ c! = $ D)

Logical "or": or, ||
Example: if ($ a == $ b || $ c! = $ D)

Now we will try to display a message if the conditions were not met, namely, if it rains, I sit at home, if it does not rain, I take the ball and go to play football. For a better understanding, let's see the figure below:

Now we will translate the circuit into real code:

Result:

I take the ball and go to play football

⇒ Explanation of the code:
In the condition, I compared the $ weather variable with the value "rain" (line number 3), but since I assigned the value "sun" to the variable $ weather (line number 2), the condition was not met (the values ​​are not the same), which means that the second part of the code (else) will work:

Else (echo "I take the ball and go to play football"; // result if the condition is not true)

→ CODE-PATTERN "CONSTRUCTION if-else":

Double if-else condition

Moving on to a more complex one - double if-else condition.
Let's use an example to create a password and login check.

Target:
Create a condition for checking the login and password. If the password or login do not match, display an error message.

Let's get started.
First, let's create two variables $ logo and $ password with the corresponding values:

Notice that in the statement we have separated the two variables with the "AND" operator. This means that two variables must be correct for the condition to be fulfilled, but since our condition does not match the password (sink # 4), it means that the condition is incorrect and you will see the following message on the screen:

Login or password is not correct

If you change the value of the $ password variable to "123" (line # 3), then the conditions will be fully met (line # 4):

Result:

welcome to admin panel

Nested if-else constructs

Nested construction- this is when there is another structure inside the structure. Explained not quite clearly? It doesn't matter, you will understand everything by example.

Target:
Create a condition for checking the login and password. If the password or login do not match, display an error message, if they match, then check the secret word, if the secret word does not match, display an error message, if it matches, then display the message " welcome to admin panel ".

Let's get started:

First, let's create three variables, $ logo, $ password and $ x with the corresponding values:

Now let's create a double condition to test the $ logo and $ password variables:

Now under the comment " // there will be one more condition with a secret word "(line number 7) write one more if-else construct with the condition of checking the variable $ x:

Since the secret word is incorrect (line number 8), the screen will display a message:

secret word is wrong

If you replace the value of the variable $ x with "BlogGOOD", then the secret word is also true:

Since the login and password are correct, and this means that the condition was met, the first part of the code worked, where it was necessary to check the secret word. Since the secret word is correct with the condition, then on the screen you will see the message:

welcome to admin panel

→ PATTERN CODE "NESTED CONSTRUCTION if-else":

Elseif condition statement

Elseif construct is a combination of if and else statements that will help you check several conditions in a row.

Syntax:

Note, in lines # 6 and # 10, two words are specially written together "elseif", if you separate them with a space "else if", the code will generate an error.

Let's give a working code with a selection of programming tutorials.

Result:

You ordered PHP tutorial

The elseif way can be written the same way nested if else construct:

The result is the same, but it's easier to get confused (I got confused 2 times in my own code).

Addition to the lesson (you don't need to know yet):

There are several more options for how you can write the if else ( alternative syntax).
I will prepare a whole lesson about the alternative syntax, where I will explain and show everything. For now, just go over your eyes.
Code # 1:

The variable "$ a" contains the value 15

Homework:
Try to substitute inequality (! =) Instead of equality (==) in the condition, or try with signs greater than less:

and also replace the "AND" operator with "OR".

Everyone, I'm waiting for you in the next lessons! Subscribe to blog updates!

Previous post
Next post

(PHP 4, PHP 5, PHP 7)

elseif, as its name suggests, is a combination of if and else... Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE... However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE... For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:

if ($ a> $ b) (
echo "a is bigger than b";
) elseif ($ a == $ b) (
echo "a is equal to b";
) else (
echo "a is smaller than b";
}
?>

There may be several elseif s within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write "else if" (in two words) and the behavior would be identical to the one of "elseif" (in a single word). The syntactic meaning is slightly different (if you "re familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

/ * Incorrect Method: * /
if ($ a> $ b):
else if ($ a == $ b): // Will not compile.
echo "The above line causes a parse error.";
endif;

/ * Correct Method: * /
if ($ a> $ b):
echo $ a. "is greater than". $ b;
elseif ($ a == $ b): // Note the combination of the words.
echo $ a. equals. $ b;
else:
echo $ a. "is neither greater than or equal to"... $ b;
endif;