Difference between revisions of "Selection"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Nesting Statements)
 
(4 intermediate revisions by 2 users not shown)
Line 62: Line 62:
 
==Nesting Statements==
 
==Nesting Statements==
 
Both if and switch statements can be nested, meaning that one statement can be contained within another.
 
Both if and switch statements can be nested, meaning that one statement can be contained within another.
<syntaxhighlight lang="csharp" line>if (a > b)
+
 
 +
<syntaxhighlight lang="csharp" line> if (a > b)
 
   {
 
   {
 
     if (b > 50)
 
     if (b > 50)
Line 69: Line 70:
 
       }
 
       }
 
   }
 
   }
 +
</syntaxhighlight>

Latest revision as of 13:22, 29 June 2018

Selection uses if statements and switch statements. These allow your programs to make decisions or change the course of your program based on an input or a variable.

If / If Else

if statements work by performing an action only if a condition is reached. After the if command, the condition should be within round brackets, the contents of which should equate to true or false.

1 if (a > b)
2   {
3     Console.WriteLine("A is greater than B");
4   }

This can also be paired with else, which will perform an action if the "if" condition is not met.

1 if (a > b)
2   {
3     Console.WriteLine("A is greater than B");
4   }
5   else
6   {
7     Console.WriteLine("A is not Greater Than B");
8   }

Else If

 1 if (a > b)
 2   {
 3     Console.WriteLine("A is greater than B");
 4   }
 5   else if (a > c)
 6           {
 7              Console.WriteLine("A is greater than C");
 8           }
 9   else
10   {
11     Console.WriteLine("A is not Greater Than B or C");
12   }

Switch / Case

Switch is basically a combined if and if else statement, and is used for a lot of different options.

1 switch(x)
2   { 
3     case 1:
4       x++;
5       break;
6     case 2:
7       x--;
8       break;
9   }

Default is an optional part of the switch method, which is used in case none of the other conditions are met.

 1 switch(x)
 2   { 
 3     case 1:
 4       x++;
 5       break;
 6     case 2:
 7       x--;
 8       break;
 9     default:
10       x*= x;
11       break;
12   }

Nesting Statements

Both if and switch statements can be nested, meaning that one statement can be contained within another.

1  if (a > b)
2   {
3     if (b > 50)
4       {
5         Console.WriteLine("b is a very large number!");
6       }
7   }