0% found this document useful (0 votes)
24 views12 pages

C# Math & Random Class, Operators, If & Switch

Uploaded by

Loraine Pagayona
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views12 pages

C# Math & Random Class, Operators, If & Switch

Uploaded by

Loraine Pagayona
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

C# Math Class

- The Math class is a built-in class in C# (inside the System namespace). - It


provides many mathematical methods and constants that we can use without
creating our own functions.
Commonly Used Math Methods:
Method Description Example Result

Math.Abs(x) Returns the Math.Abs(-10) 10


absolute value
(positive
number).

Math.Round(x) Rounds to the Math.Round(4.678)


nearest whole 5
number. Math.Round(4.678, 2)
4.68

Math.Ceiling(x) Rounds up to the Math.Ceiling(4.2) 5


next whole
number.

Math.Floor(x) Rounds down to Math.Floor(4.8) 4


the nearest whole
number.

Math.Sqrt(x) Returns the Math.Sqrt(25) 5


square root.

Math.Pow(x, y) Returns x raised Math.Pow(2, 3) 8


to the power of y.

Math.Max(a, b) Returns the Math.Max(7, 10) 10


larger value.

Math.Min(a, b) Returns the Math.Min(7, 10) 7


smaller value.

Math.PI Constant for π Math.PI 3.14159…


(3.14159…).

C# Random Class
- The Random class in C# is used to generate random numbers.
- It is found in the System namespace.
- To use it, we first create an object from the Random class.
Random rand = new Random();
Method Description Example Result
rand.Next() Returns a rand.Next() 0, 1, 2, …
non-negative
random integer.

rand.Next(max) Returns a rand.Next(10) 0 - 9


random integer
from 0 up to max.

rand.Next(min, max) Returns a rand.Next(5, 20) 5 - 19


random integer
from min up to
max.

rand.Double() Returns a random rand.Double() 0.1, 0.123…


number between
0.0 and 1.0.

Example Program

static void Main()


{
// An object of random class
Random rand = new Random();

Console.WriteLine("Random integer: " + rand.Next() );


Console.WriteLine("Random 0–9: " + rand.Next(10) );
Console.WriteLine("Random 5–14: " + rand.Next(5, 15) );
Console.WriteLine("Random double: " + rand.NextDouble() );
}

Possible Output:
Random integer: 2348562
Random 0–9: 7
Random 5–14: 12
Random double: 0.3435436
C# Assignment Operators

- Assignment operators are used to assign values to variables.


- In the example below, we use the assignment operator (=) to assign
the value 10 to a variable called x:
Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable: Example

int x = 10;

x += 5;

A list of all assignment operators:


Operator Example Same As

= X = 10 X = 10

+= X += 3 X = X+3

-= X -= 3 X = X-3

*= X *= 3 X = X*3

/= X /= 3 X = X/3

%= X %= 3 X = X%3

C# Comparison Operators

Comparison operators are used to compare two values:


Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than X > Y

< Less than X < Y

>= Greater than or equal to X>=Y

<= Less than or equal to X<=Y

C# Logical Operators

Logical operators are used to determine the logic between variables or


values:
Operator Name Description Example

&& Logical and Returns true if both


x > 1 && x < 10
statements are true

|| Logical or Returns true if one of the


x < 5 || x > 10
statements is true

! Logical not Reverse the result, returns


!(x < 5 && x < 10)
false if the result is true

Operator Statements Result

&& true && true true


(logical and operator)
false && frue false

true && false false

false && false false

|| true || true true


(logical or operator)
false || frue true

true || false true

false || false false

! !false true
(logical not operator)
!true false

C# Conditional Statements

C# supports the usual logical conditions from mathematics:

− Less than: a < b

− Less than or equal to: a <= b

− Greater than: a > b

− Greater than or equal to: a >= b

− Equal to a == b
− Not Equal to: a != b

∙ You can use these conditions to perform different actions for different
decisions.
C# has the following conditional statements:

− Use if to specify a block of code to be executed, if a


specified condition is true
− Use else to specify a block of code to be executed, if the same condition is
false
− Use else if to specify a new condition to test, if the first condition is
false
− Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of C# code to be executed if a


condition is True.

Syntax

if (condition)

{
// block of code to be executed if the condition is True

In the example below, we test two values to find out if 20 is greater than 18. If the
condition is True, print some text:

Example

int x = 20;

int y = 18;

if (x > y) {

Console.WriteLine("x is greater than y");


}

Example explained

In the example above we use two variables, x and y, to test whether x is greater
than y (using the > operator). As x is 20, and y is 18, and we know that 20 is
greater than 18, we print to the screen that "x is greater than y".

Another Example

int x;
int max = 0;

x = Convert.ToInt32(Console.ReadLine());

if (x > max)

max = x;
}

Example explained

In the example above we use two variables, x and max. This program asks for a
user to enter a value for variable x then this program checks if the user input x is
greater than the value of max variable. If true then the program will replace the
value of max variable to the value of x.
The else Statement

∙ Use the else statement to specify a block of code to be executed if the


condition is False.

Syntax

if (condition)

{
// block of code to be executed if the condition is True

else {
// block of code to be executed if the condition is False

Example 1

int time = 20;


if (time < 18) {
Console.WriteLine("Good day.");
}
else {

Console.WriteLine("Good evening.");
}

// Outputs "Good evening."


Example 1 explained

In the example above, time (20) is greater than 18, so the condition is
False.Because of this, we move on to the else condition and print to the screen
"Good evening". If the time was less than 18, the program would print "Good day".

Example 2: How to check if a number is even or odd int x;

x = Convert.ToInt32(Console.ReadLine());

if(x%2==0) {

Console.WriteLine("Even");
}

else {
Console.WriteLine("Odd");
}

Example 3: How to check if a number is positive or negative

int x;
x = Convert.ToInt32(Console.ReadLine());

if (x<0) {

Console.WriteLine("Negative");
}
else {
Console.WriteLine("Positive");
}
Example 4: How to calculate the profit and loss of a company

int profit, loss;


int income = Convert.ToInt32(Console.ReadLine());

int cost = Convert.ToInt32(Console.ReadLine());

if(income>=cost) {

profit = income - cost;


Console.WriteLine("Profit = " + profit); }
else {
loss = cost - income;
Console.WriteLine("Loss = " + loss);
}

The else if Statement

∙ Use the else if statement to specify a new condition if the first condition is
False.
Syntax

if (condition a) {
// block of code to be executed if condition1 is True

else if (condition b) {
// block of code to be executed if the condition1 is false and condition2 is
// True
}
else {
// block of code to be executed if the condition1 is false and condition 2 is
// False
}

Example

int time = 22;


if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}

// Outputs "Good evening."


Example explained

In the example above, time (22) is greater than 10, so the first condition is False. The
next condition, in the else if statement, is also False, so we move on to the else
condition since condition1 and condition2 are both False and print to the screen "Good
evening". However, if the time was 14, our program would print "Good day."

C# Switch Statements

∙ Use the switch statement to select one of many code blocks to be


executed. Syntax

switch(expression)
{
case x:
// code block 1
break;
case y:
// code block 2
break;
default:
// code block 3
break;
}

This is how it works:

∙ The switch expression is evaluated once


∙ The value of the expression is compared with the values of each case
∙ If there is a match, the associated block of code is executed
The
example below uses the weekday number to calculate the weekday
name:
Example

int day = 4;
switch (day) {
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4: Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6: Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}

// Outputs "Thursday" (day 4)


The break Keyword

∙ When C# reaches a break keyword, it breaks out of the switch block. ∙ This
will stop the execution of more code and case testing inside the block. ∙ When
a match is found, and the job is done, it's time for a break. There is no need
for more testing.

∙ A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.

The default Keyword

∙ The default keyword is optional and specifies some code to run if there is no
case match:

Example

int day = 4;
switch (day)

{
case 6:
Console.WriteLine("Today is Saturday."); break;
case 7:
Console.WriteLine("Today is Sunday.");
break;
default:
Console.WriteLine("Looking forward to the Weekend.");
break;
}
// Outputs "Looking forward to the Weekend."

You might also like