c# programming: expressions, conditions, and repetitions 01204111 computer and programming
TRANSCRIPT
![Page 1: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/1.jpg)
C# Programming:Expressions, conditions,
and repetitions01204111 Computer and
Programming
![Page 2: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/2.jpg)
Agenda
• Expressions• Input / Output• Program flow control
– Boolean expressions– Conditions– Repetitions
![Page 3: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/3.jpg)
Overview
BasicsVariables, expressions, input and output
BasicsVariables, expressions, input and output
Type conversion, math methodsType conversion, math methods
Flow control: Boolean expressionsFlow control: Boolean expressions
RepetitionsRepetitions ConditionsConditions
![Page 4: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/4.jpg)
Warnings
• There are far too many topics covered in this single lecture as compared to previous ones.
• However, what we would like to reflect on is that the general ideas of programming are mostly the same no matter what language you are using.
• However, the changes are– Syntactic changes– Various language dependent features
![Page 5: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/5.jpg)
C# Program: review
• A program starts at Main• A program is organized into a set of namespaces, classes,
and methods.• You may skip the namespace part.
using System;
namespace Sample{ class Program { static void Main() { Console.WriteLine("Hello, world"); } }}
![Page 6: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/6.jpg)
Inside method Main
• Variable declarations• Other statements
static void Main(string[] args) { const double pi = 3.1416;
int radius; double area;
radius = int.Parse(Console.ReadLine()); area = pi*radius*radius; Console.WriteLine(area); }
![Page 7: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/7.jpg)
Note#1: Terminating a statement
• In C#, almost every statement must end with ;
• Except compound statements, grouped by { } pairs.
int x; int y = 10;
x = int.Parse(Console.ReadLine());if(x > y) Console.WriteLine("Good");
int x; int y = 10;
x = int.Parse(Console.ReadLine());if(x > y) Console.WriteLine("Good");
if(x <= y){ Console.WriteLine("Ummm"); Console.WriteLine("Try harder.");}
if(x <= y){ Console.WriteLine("Ummm"); Console.WriteLine("Try harder.");}
![Page 8: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/8.jpg)
Variables: review
• If we want to store any value to be used later, we shall need a variable.
• In C#, before you can use a variable, you must– Declare it– Specify its type, which specifies a set of possible
values that the variable can keep.
![Page 9: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/9.jpg)
Standard data types in C#: Review
Type Size Description Rangebool 1 byte Store truth value true / false char 1 byte Store one character character code 0 – 255byte 1 byte Store positive integer 0 – 255short 2 byte Store integer -32,768 -- 32,767int 4 byte Store integer -2.1 x 109 -- 2.1 x 109 long 8 byte Store integer -9.2 x 1018 -- 9.2 x 1018
double 16 byte Store real number ± 5.0x10-324 -- ± 1.7x10308
string N/A Store sequence of characters
N/A
![Page 10: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/10.jpg)
Important types
• Boolean: bool– There are two possible values, which are true and false.
• Integer: int– Stores integers with in range 2.1 x 109 -- 2.1 x 109
• Real numbers: double– Stores floating point numbers in range ± 5.0x10-324 --
± 1.7x10308
![Page 11: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/11.jpg)
Important types
• String: string– Written only in double quotes, e.g., "Hello"– If you want double quote itself, put backslash in front of it.
• Character: char– Represents a single character, written with a single
quote.
s = "He says \"I love you.\"";Console.WriteLine(s);s = "He says \"I love you.\"";Console.WriteLine(s);
He says "I love you."He says "I love you."
![Page 12: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/12.jpg)
Variable naming rules
• Each variable must have a name, which must satisfy the following rules:– consists of digits, English alphabets, and underlines.– first character must be English alphabets (either in upper caps or
in lower caps) or an underline.– must not be the same as reserved words
• Not that upper case and lower case alphabets are different.
Example nam
eName
_data
9point
class class_A
class_”A”
point9
![Page 13: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/13.jpg)
Variable declaration: review
• Types must be specified.
• Can initialize the values at the same time
int radius;string firstName;double GPA;
int radius;string firstName;double GPA;
int radius = 5;string firstName = "john";double GPA = 2.4;
int radius = 5;string firstName = "john";double GPA = 2.4;
![Page 14: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/14.jpg)
Expressions
• Computations in C# take place in expressions.
![Page 15: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/15.jpg)
Operators
• Most arithmetic operators work as in Python, except division.– Operators: + - * /– Operators: % (modulo)
• Operators are evaluated according to their precedence, as in Python.
![Page 16: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/16.jpg)
Divisions with/by reals, the result are realsDivisions with/by reals, the result are reals
Integer division, the results are integerInteger division, the results are integer
Operators
• What are the values– 11 + 5 – 39 / 5 – 39.0/5 – 39 % 5 – 5.0 % 2.2
167
4
0.6
7.8
![Page 17: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/17.jpg)
Input statement
• A common method for reading a string from the user is:
Console.ReadLine()
string name = Console.ReadLine();Console.WriteLine("Your name is {0}", name);string name = Console.ReadLine();Console.WriteLine("Your name is {0}", name);
![Page 18: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/18.jpg)
Conversion from strings
• However, if we want to perform arithmetic computation with them, we have to convert strings to appropriate types.– Mathod int.Parse turns a string to an int.– Method double.Parse turns string to a double.
string sc = Console.ReadLine();int count = int.Parse(Console.ReadLine());
int age = int.Parse(Console.ReadLine());double time = double.Parse(Console.ReadLine());
string sc = Console.ReadLine();int count = int.Parse(Console.ReadLine());
int age = int.Parse(Console.ReadLine());double time = double.Parse(Console.ReadLine());
![Page 19: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/19.jpg)
Output statements
• Method Console.Write and Console.WriteLine are common methods for showing results to console.– Method Console.Write is similar to method Console.WriteLine, but it does not put in a new line.
• We can format the output pretty easily.
![Page 20: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/20.jpg)
Examples usage of Console.WriteLine
• Basic usage:
• Specifying printing templates:
• Specifying extra formatting:
Console.WriteLine(”Size {0}x{1}”, width, height);Console.WriteLine(”Size {0}x{1}”, width, height);
double salary=12000;double salary=12000;Console.WriteLine("My salary is {0:f2}.", salary);Console.WriteLine("My salary is {0:f2}.", salary);
Console.WriteLine("Hello");Console.WriteLine("Hello");Console.WriteLine(area);Console.WriteLine(area);
20
![Page 21: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/21.jpg)
Thinking Corner
• Write a program to read the height (in meters) and weight (in kg) and compute the BMI as in the following formula.
BMI =Weight in KilogramsWeight in Kilograms
(Height in Meters) X (Height in Meters)(Height in Meters) X (Height in Meters)
Enter weight (in kg): 83Enter height (in m): 1.7Your BMI is 28.72.
Enter weight (in kg): 83Enter height (in m): 1.7Your BMI is 28.72.
![Page 22: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/22.jpg)
The solution
Enter weight (in kg): 83Enter height (in m): 1.7Your BMI is 28.719723183391.
Enter weight (in kg): 83Enter height (in m): 1.7Your BMI is 28.719723183391.
public static void Main(string[] args) { Console.Write("Enter weight (in kg): "); double w = double.Parse(Console.ReadLine()); Console.Write("Enter height (in m): "); double h = double.Parse(Console.ReadLine()); Console.WriteLine("Your BMI is {0}.", w / (h*h)); Console.ReadLine(); }
public static void Main(string[] args) { Console.Write("Enter weight (in kg): "); double w = double.Parse(Console.ReadLine()); Console.Write("Enter height (in m): "); double h = double.Parse(Console.ReadLine()); Console.WriteLine("Your BMI is {0}.", w / (h*h)); Console.ReadLine(); }
quite an ugly formatting
(click to show)
![Page 23: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/23.jpg)
Basic output formatting
• When displaying floating point numbers, WriteLine may show too many digits. Console.WriteLine("Your BMI is {0:f2}.", w / (h*h)); Console.WriteLine("Your BMI is {0:f2}.", w / (h*h));
We can add formatting :f2 in to the printing template.f is for floating points, and 2 is the number of digits.We can add formatting :f2 in to the printing template.f is for floating points, and 2 is the number of digits.
Enter weight (in kg): 83Enter height (in m): 1.7Your BMI is 28.72.
Enter weight (in kg): 83Enter height (in m): 1.7Your BMI is 28.72.
![Page 24: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/24.jpg)
Thinking Corner: Ants
• An ant starts walking on a bright whose length is m meters. The ant walks with velocity v meters/second. After arriving at one end of the bridge, it walks back with the same speed. It keeps walking for t minutes. How many rounds that the ant completely crosses the bridge and gets back to the starting point?Write a program that takes
m, v, and t , as double, and compute how many rounds that the ant walks over the
bridge.
![Page 25: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/25.jpg)
Ideas
• From the duration and speed, we can calculate the total distance the ant walks.
• From the distance and the length of the bridge, we can calculate the number of rounds– The problem we have to solve is that how we manage
to removes all the fractions in the result by the division.
– We will start with a program that compute the number of rounds, in real, and we will fix this problem later.
![Page 26: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/26.jpg)
Partial solution
• method Mainstatic void Main() { Console.Write("Enter m (m): "); double m = double.Parse(Console.ReadLine()); Console.Write("Enter v (m/s): "); double v = double.Parse(Console.ReadLine()); Console.Write("Enter t (min): "); double t = double.Parse(Console.ReadLine());
double dist = v * t * 60; double walk = dist / (2*m); Console.WriteLine("Number of times = {0}", walk); Console.ReadLine();}
static void Main() { Console.Write("Enter m (m): "); double m = double.Parse(Console.ReadLine()); Console.Write("Enter v (m/s): "); double v = double.Parse(Console.ReadLine()); Console.Write("Enter t (min): "); double t = double.Parse(Console.ReadLine());
double dist = v * t * 60; double walk = dist / (2*m); Console.WriteLine("Number of times = {0}", walk); Console.ReadLine();}
(click to show)
![Page 27: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/27.jpg)
Type conversion
• Values can be converted in to different types.• C# usually converts values in smaller types to
values in bigger types automatically.
short int long
int double
![Page 28: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/28.jpg)
Casting
• However, for other conversions, we have to explicitly specify that we really need conversion.
• The syntax for that is:
(type) value• For example, if we want to convert 2.75 to an
integer we will write (int) 2.75
• Sometimes, we will have to putparentheses on the values to be converted.
get 2, convertinga double to an int in this way always rounds everything down
get 2, convertinga double to an int in this way always rounds everything down
![Page 29: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/29.jpg)
Solution for Thinking Corner
• Shows only method Mainstatic void Main() { Console.Write("Enter m (m): "); double m = double.Parse(Console.ReadLine()); Console.Write("Enter v (m/s): "); double v = double.Parse(Console.ReadLine()); Console.Write("Enter t (min): "); double t = double.Parse(Console.ReadLine());
double dist = v * t * 60;
int walk = (int)(dist / (2*m));
Console.WriteLine("Number of times = {0}", walk); Console.ReadLine();}
static void Main() { Console.Write("Enter m (m): "); double m = double.Parse(Console.ReadLine()); Console.Write("Enter v (m/s): "); double v = double.Parse(Console.ReadLine()); Console.Write("Enter t (min): "); double t = double.Parse(Console.ReadLine());
double dist = v * t * 60;
int walk = (int)(dist / (2*m));
Console.WriteLine("Number of times = {0}", walk); Console.ReadLine();}
(click to show)
![Page 30: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/30.jpg)
Additional operators
• C# also provides additional useful operators related to variable updates– Operators for increasing and decreasing by one– Operators for updating values
![Page 31: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/31.jpg)
Operators for variable updates
• As in Python, C# provides data update operators
x = x + 10 x += 10
y = y * 7 y *= 7
z = z / 7 z /= 7
![Page 32: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/32.jpg)
Operators ++, --
• We usually increase or decrease a variable by one. In C#, it is very easy to do.
x = x + 1 x += 1 x++x++
x = x - 1 x -= 1 x--x--
![Page 33: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/33.jpg)
Examples: printing numbers
int a = 1;while(a <= 10){ Console.WriteLine(a);
a = a + 1;}
int a = 1;while(a <= 10){ Console.WriteLine(a);
a = a + 1;}
int a = 1;while(a <= 10){ Console.WriteLine(a);
a += 1;}
int a = 1;while(a <= 10){ Console.WriteLine(a);
a++;}
int a = 1;while(a <= 10){ Console.WriteLine(a);
a++;}
![Page 34: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/34.jpg)
Methods for computing mathematical functions
• C# provides methods for computing math functions in standard class Math.
![Page 35: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/35.jpg)
A list of common math methodsMethod/Constant
Value returned Example Call Result
PI Value of Math.PI 3.1415927
Max(x,y) Larger of the two Math.Max(1,2) 2
Abs(x) Absolute value of x Math.Abs(-1.3) 1.3
Sqrt(x) Square-root of x Math.Sqrt(4.0) 2.0
Round(x) Nearest integer to x Math.Round(0.8) 1
Pow(x,y) xy Math.Pow(3,2) 9.0
Log(x) Natural log of x Math.Log(10) 2.302585
Ceiling(x) Smallest integer greater than or equal to x
Math.Ceiling(4.1) 5
Cos(x) Cosine of x radians Math.Cos(Math.PI) -1
![Page 36: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/36.jpg)
Thinking corner
Write a program that reads the radius and computer the area of the circle.
Write a program that reads the radius and computer the area of the circle.Enter radius: 6The area is 113.0973Enter radius: 6The area is 113.0973
Hint: Math.PIHint: Math.PI
![Page 37: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/37.jpg)
Program flow control
• Condition or Boolean expressions• Types of program control:
– Conditional: if, if-else– Repetition: while, do-while, for
x == 0
x > 0
x < 0
x > 0 TrueTrue
False
False
TrueTrue
False
False
x < 0
height <= 140TrueTrue
FalseFalse
![Page 38: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/38.jpg)
Condition: Boolean expressions
• How to build an expression?– Comparison– Combining smaller expressions
Comparison operators
Comparison operators
Boolean operatorsBoolean
operators
![Page 39: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/39.jpg)
Data type: bool
• Type bool represents logical values, with only two possible values:– True : true– False : false As in Python
C# is case sensitive.Therefore "True" is not the same as "true".
As in PythonC# is case sensitive.Therefore "True" is not the same as "true".
![Page 40: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/40.jpg)
Comparison operators
Operators Meanings Examples== Equal a == 5!= Not equal done != False< Less than data < 10
<= Less than or equal
count <= 15
> Greater than money > 0>= Greater than
or equalinterest >= 0.02
![Page 41: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/41.jpg)
Boolean operators
AND
OR
NOT
&&
||
!
![Page 42: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/42.jpg)
Examplesx is not
equal to 0 or y is
equal to 10
(x!=0) || (y==10)
i is less than n
and x is not equal to y
(i<n) && (x!=y)
a is between b
to c
(a >= b) && (a <= c)
![Page 43: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/43.jpg)
if statements
• if statements controls whether some statement will be executed.
if( condition ) statement
![Page 44: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/44.jpg)
คำ��สั่��ง if-else
• if-else statements are used when you have two choices.
if( condition) statementelse statement
![Page 45: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/45.jpg)
Examples
The sky train has 50% price reduction for children not over 10 years old. The original ticket price is 50 baht. Write a program that reads the age and shows the ticket price.
The sky train has 50% price reduction for children not over 10 years old. The original ticket price is 50 baht. Write a program that reads the age and shows the ticket price.
static void Main(){ int age = int.Parse(Console.ReadLine()); if(age <= 10) Console.WriteLine("Price = 25"); else Console.WriteLine("Price = 50");}
static void Main(){ int age = int.Parse(Console.ReadLine()); if(age <= 10) Console.WriteLine("Price = 25"); else Console.WriteLine("Price = 50");}
![Page 46: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/46.jpg)
Be carefule
• In Python, the condition in the if-statement may not be in the parentheses.
• But in C#, the parentheses after the if-statement is part of the syntax, and cannot be removed.
if age <= 10: print("Hello!")if age <= 10: print("Hello!")
if(age <= 10) Console.WriteLine("Hello");if(age <= 10) Console.WriteLine("Hello");
![Page 47: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/47.jpg)
Empty statements
• As in Python, C# has an empty statement that does not do anything, which is
;• Usage example:
if(x > 15) ;else Console.WriteLine("hello");
if(x > 15) ;else Console.WriteLine("hello");
![Page 48: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/48.jpg)
Controlling many statements
• The if- and if-else- statements only control single statements following it.
• More over, indentation does not mean anything in C#.
if age <= 10: print("Hello, kid") print("Your price is 25 baht")
if age <= 10: print("Hello, kid") print("Your price is 25 baht")
if(age <= 10) Console.WriteLine("Hello, kid"); Console.WriteLine("Your price is 25 baht");
if(age <= 10) Console.WriteLine("Hello, kid"); Console.WriteLine("Your price is 25 baht");
Converted to C#
![Page 49: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/49.jpg)
Block
• We can combine many statements into a single one by embracing them with the curly brackets { }. This is call a block.
• A block behaves like a single statement.
if age <= 10: print("Hello, kid") print("Your price is 25 baht")
if age <= 10: print("Hello, kid") print("Your price is 25 baht")
if(age <= 10){ Console.WriteLine("Hello, kid"); Console.WriteLine("Your price is 25 baht");}
if(age <= 10){ Console.WriteLine("Hello, kid"); Console.WriteLine("Your price is 25 baht");}
converted to C#
Block
![Page 50: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/50.jpg)
Be careful
• In C#, only curly brackets define blocks. Indentation only serves as readability enhancement.
if(x > 0) total += x; count++;
if(x > 0) total += x; count++;
if(x > 0) total += x;count++;
if(x > 0) total += x;count++;
if(x > 0){ total += x; count++;}
if(x > 0){ total += x; count++;}
is the same as
is not thesame as
![Page 51: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/51.jpg)
Thinking corner
• From the previous example on computing the BMI, add a status message to the user according to the table below.
BMI Status
less than 18.5 Underweight
greater than or equal to 18.5 but less than 25
Normal
greater than or equal to 25.0 but less than 30
Overweight
greater than or equal to 30 Obese (Extremely
Fat)
Only write the part that prints the status. You can assume that the BMI has be computed and stored in variable bmi
![Page 52: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/52.jpg)
Solution 1: if statements
if(bmi < 18.5) Console.WriteLine("Underweight");if((bmi >= 18.5) && (bmi < 25)) Console.WriteLine("Normal");if((bmi >= 25) && (bmi < 30)) Console.WriteLine("Overweight");if(bmi >= 30) Console.WriteLine("Extremely fat");
if(bmi < 18.5) Console.WriteLine("Underweight");if((bmi >= 18.5) && (bmi < 25)) Console.WriteLine("Normal");if((bmi >= 25) && (bmi < 30)) Console.WriteLine("Overweight");if(bmi >= 30) Console.WriteLine("Extremely fat");
(click to show)
![Page 53: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/53.jpg)
Solution 2: nested if
if(bmi < 18.5) Console.WriteLine("Underweight");else if(bmi < 25) Console.WriteLine("Normal"); else if(bmi < 30) Console.WriteLine("Overweight"); else Console.WriteLine("Extremely fat");
if(bmi < 18.5) Console.WriteLine("Underweight");else if(bmi < 25) Console.WriteLine("Normal"); else if(bmi < 30) Console.WriteLine("Overweight"); else Console.WriteLine("Extremely fat");
(click to show)
![Page 54: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/54.jpg)
Be careful when using nested if
if(a > 5) if(b < 10) Console.WriteLine("Hello"); else Console.WriteLine("Good-bye");
if(a > 5) if(b < 10) Console.WriteLine("Hello"); else Console.WriteLine("Good-bye");
if(a > 5) if(b < 10) Console.WriteLine("Hello");else Console.WriteLine("Good-bye");
if(a > 5) if(b < 10) Console.WriteLine("Hello");else Console.WriteLine("Good-bye");
Both programs are the same, because in C#
indentation does not change the meaning of the
program.
Which "if" that the only "else" in the program is referring to?
Which "if" that the only "else" in the program is referring to?
![Page 55: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/55.jpg)
Matching else and if
if(a > 5) if(b < 10) Console.WriteLine("Hello"); else Console.WriteLine("Good-bye");
if(a > 5) if(b < 10) Console.WriteLine("Hello"); else Console.WriteLine("Good-bye");
if(a > 5) if(b < 10) Console.WriteLine("Hello");else Console.WriteLine("Good-bye");
if(a > 5) if(b < 10) Console.WriteLine("Hello");else Console.WriteLine("Good-bye");
The "else" is always paired up with the closed first if-statementThe "else" is always paired up
with the closed first if-statement
![Page 56: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/56.jpg)
Using blocks
• If we want "else" to pair up with other "if", we have to explicitly put them into a single block.
if a > 5: if b < 10: print("Hello")else: print("Good-bye")
if a > 5: if b < 10: print("Hello")else: print("Good-bye")
if(a > 5){ if(b < 10) Console.WriteLine("Hello");}else Console.WriteLine("Good-bye");
if(a > 5){ if(b < 10) Console.WriteLine("Hello");}else Console.WriteLine("Good-bye");
![Page 57: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/57.jpg)
Example: Tax deduction
• When calculate tax deduction, if you have children, you can deduct 15,000 baht per children. You can use that deduction for at most 3 children.
• We would like to write a program as below.
Do you have any children (Y/N)? NYour deduction is 0 baht.Do you have any children (Y/N)? NYour deduction is 0 baht.
Do you have any children (Y/N)? YHow many children do you have? 2Your deduction is 30000 baht
Do you have any children (Y/N)? YHow many children do you have? 2Your deduction is 30000 baht
Do you have any children (Y/N)? YHow many children do you have? 5Your deduction is 45000 baht
Do you have any children (Y/N)? YHow many children do you have? 5Your deduction is 45000 baht
![Page 58: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/58.jpg)
Deduction: plans
• Keep the deduction in variable deduction.• Write the first part where the program asks if the
user has any children.• Then, add more details later.
![Page 59: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/59.jpg)
Deduction: first steppublic static void Main(string[] args){ Console.Write("Do you have any children (Y/N)? "); string ans = Console.ReadLine(); int deduction = 0; if(ans == "Y") { // dealing with the case where the user has children } else deduction = 0; Console.WriteLine("Your deduction is {0} baht.", deduction); Console.ReadLine();}
public static void Main(string[] args){ Console.Write("Do you have any children (Y/N)? "); string ans = Console.ReadLine(); int deduction = 0; if(ans == "Y") { // dealing with the case where the user has children } else deduction = 0; Console.WriteLine("Your deduction is {0} baht.", deduction); Console.ReadLine();}
![Page 60: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/60.jpg)
Y or y
• If we would like to allow the user to answer with either Y or y, how should we change the program?
if((ans == "Y") || (ans == "y")) { // ……… }
if((ans == "Y") || (ans == "y")) { // ……… }
Use "or" ( || )
if(ans == "Y") if(ans == "Y")
![Page 61: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/61.jpg)
Deduction: final steppublic static void Main(string[] args){ Console.Write("Do you have any children (Y/N)? "); string ans = Console.ReadLine(); int deduction = 0; if((ans == "Y") || (ans == "y")) { Console.Write("How many children do you have? "); int ccount = int.Parse(Console.ReadLine()); if(ccount > 3) ccount = 3; deduction = ccount * 15000; } else deduction = 0; Console.WriteLine("Your deduction is {0} baht.", deduction); Console.ReadLine();}
public static void Main(string[] args){ Console.Write("Do you have any children (Y/N)? "); string ans = Console.ReadLine(); int deduction = 0; if((ans == "Y") || (ans == "y")) { Console.Write("How many children do you have? "); int ccount = int.Parse(Console.ReadLine()); if(ccount > 3) ccount = 3; deduction = ccount * 15000; } else deduction = 0; Console.WriteLine("Your deduction is {0} baht.", deduction); Console.ReadLine();}
![Page 62: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/62.jpg)
Iteration
• We will look at two closely-related statements for iteration
while-statementchecks the condition before start or continue
do-while-statementdoes the loop first, then checks the condition
do-while-statementdoes the loop first, then checks the condition
![Page 63: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/63.jpg)
while-statement
• Works as in Python.
while( condition) statement
63
condition
statement 1
true
statement 2:
statement n
false
![Page 64: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/64.jpg)
do-while-statement
• Python does not have the do-while statement
do statementwhile( condition );
64
condition
true
statement 1statement 2:
statement n
false
![Page 65: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/65.jpg)
Examples
• Reads the password, until the user enters "hellocsharp"
string pwd;
pwd = Console.ReadLine();while(pwd != "hellocsharp") pwd = Console.ReadLine();
string pwd;
pwd = Console.ReadLine();while(pwd != "hellocsharp") pwd = Console.ReadLine();
written with while
string pwd;
do pwd = Console.ReadLine();while(pwd != "hellocsharp");
string pwd;
do pwd = Console.ReadLine();while(pwd != "hellocsharp");
written with
do-while
Which one looks easier?
![Page 66: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/66.jpg)
Examples
• Reads an integer n, print numbers from 1 to n, one per line.
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.WriteLine(i); i++;}
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.WriteLine(i); i++;}
written with while
int n = int.Parse( Console.ReadLine());int i = 1;do{ Console.WriteLine(i); i++;}while(i <= n);
int n = int.Parse( Console.ReadLine());int i = 1;do{ Console.WriteLine(i); i++;}while(i <= n);
written withdo-while
![Page 67: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/67.jpg)
Be careful
• The while-statement and the do-while-statement are very similar. The only differences is that the do-while-statement does not check the condition on the first run of the loop.
int n = int.Parse( Console.ReadLine());int i = 1;do{ Console.WriteLine(i); i++;}while(i <= n);
int n = int.Parse( Console.ReadLine());int i = 1;do{ Console.WriteLine(i); i++;}while(i <= n);
In previous example if n is 0, the program still prints 1.
In previous example if n is 0, the program still prints 1.
![Page 68: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/68.jpg)
Thinking corner
• Reads an integer n, the prints numbers from 1 to n. Prints at most 8 numbers per line; separate each pair of numbers with a space.
![Page 69: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/69.jpg)
Printing numbers: plans
• Write a program that prints all number in a single line.
• Add some code that prints new lines at appropriate place.
![Page 70: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/70.jpg)
Printing numbers: 1
• Start with a program that prints every in a single line.– Next step: add more spaces.
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.Write(i); i++;}
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.Write(i); i++;}
201234567891011121314151617181920
201234567891011121314151617181920
![Page 71: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/71.jpg)
Printing numbers: 2
• Change the template to "{0} "– Next step: add new lines
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.Write("{0} ", i); i++;}
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.Write("{0} ", i); i++;}
201 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
201 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
![Page 72: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/72.jpg)
Printing numbers: 3
• We shall add statements that print new lines.• Note that we print new lines after printing 8 numbers,
i.e., when i is 8, 16, 24, …
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.Write("{0} ", i); i++;}
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.Write("{0} ", i); i++;}
201 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
201 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
if(___________________) Console.WriteLine();
![Page 73: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/73.jpg)
Printing numbers: Final
• Question: if we add the code after statement i++ what would the output be like?
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.Write("{0} ", i); if(i % 8 == 0) Console.WriteLine(); i++;}
int n = int.Parse( Console.ReadLine());int i = 1;while(i <= n){ Console.Write("{0} ", i); if(i % 8 == 0) Console.WriteLine(); i++;}
201 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
201 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
![Page 74: C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming](https://reader036.vdocuments.mx/reader036/viewer/2022062518/56649ea05503460f94ba26fc/html5/thumbnails/74.jpg)
Conclusion
• This lecture presents the syntax of C# related to basic control flows.
• Note that even though the programming language changes, many of the concepts carry through the new language.