Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Review Materials
- Lesson 5-6. Conditional Instruction IF.
- Lesson Objective
- The goal of the lesson is to present the IF conditional instruction.
- Conditional instructions allow for executing specific parts of a program depending on the conditions met. The IF instruction appears in almost every programming language, although its syntax may vary slightly.
- This instruction has several variants. In C#, the simplest syntax looks like this:
- ```csharp
- if (logical expression)
- {
- //code block that executes if the logical expression is true;
- }
- ```
- A more advanced version, assuming the existence of several possible variants:
- ```csharp
- if (condition_1)
- {
- //if the condition is met, this piece of code will execute;
- }
- else if (condition_2)
- {
- //executes if condition_1 is not met, but condition_2 is;
- }
- else // in all other cases, this piece of code will execute
- {
- //code block;
- }
- ```
- Example 1:
- ```csharp
- int age = Console.Readline();
- if (age == 17)
- {
- Console.WriteLine("You will reach adulthood this year");
- }
- ```
- Example 2:
- ```csharp
- int number1 = 4;
- int number2 = 5;
- if (number1 > number2)
- {
- Console.WriteLine($"{number1} is greater than {number2}");
- }
- else if (number2 > number1)
- {
- Console.WriteLine($"{number2} is greater than {number1}");
- }
- else
- {
- Console.WriteLine("The numbers are equal");
- }
- Console.WriteLine(number1);
- ```
- Nesting instructions allows for adding conditional instructions inside another instruction.
- Example task - A presidential candidate must be at least 35 years old and have collected 100,000 votes. Check if you can run for president.
- ```csharp
- if( are you 35 years old? )
- {
- if( Have you collected 100,000 votes? )
- {
- You can run for president!
- }
- else
- {
- You cannot run for president
- }
- }
- else
- {
- You cannot run for president
- }
- ```
- Try to convert the above pseudocode into a working program 😉
- Watch out for these mistakes!
- - Never place a semicolon after the parentheses in if.
- ```csharp
- if(condition); <- WRONG!
- {
- }
- ```
- - Remember that a variable declared inside a block is not accessible outside it.
- ```csharp
- if(condition)
- {
- int x = 1;
- }
- x++; <- Error! The variable x is not accessible here!
- ```
- Additional Programmer's Mission:
- Create a program that draws 2 numbers from the range of 0 to 100, then check (using the If conditional instruction) if their sum is greater than 50. The program should display a message indicating whether the condition is met or not.
- Hint - the draw can be implemented as follows:
- ```csharp
- Random randomMachine = new Random();
- int drawnValue = randomMachine.Next(1, 101);
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement