C# Programming: Expressions, conditions, and repetitions Computer and Programming
Agenda Expressions Input / Output Program flow control –Boolean expressions –Conditions –Repetitions
Overview Basics Variables, expressions, input and output Basics Variables, expressions, input and output Type conversion, math methods Flow control: Boolean expressions Repetitions Conditions
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
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"); }
Inside method Main Variable declarations Other statements static void Main(string[] args) { const double pi = ; int radius; double area; radius = int.Parse(Console.ReadLine()); area = pi*radius*radius; Console.WriteLine(area); }
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."); }
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.
Standard data types in C#: Review TypeSizeDescriptionRange bool1 byteStore truth valuetrue / false char1 byteStore one charactercharacter code 0 – 255 byte1 byteStore positive integer0 – 255 short2 byteStore integer-32, ,767 int4 byteStore integer-2.1 x x 10 9 long8 byteStore integer-9.2 x x double16 byteStore real number± 5.0x ± 1.7x stringN/AStore sequence of characters N/A
Important types Boolean: bool –There are two possible values, which are true and false. Integer: int –Stores integers with in range 2.1 x x 10 9 Real numbers: double –Stores floating point numbers in range ± 5.0x ± 1.7x10 308
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."
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 nameName _data 9point class class_A class_”A” point9
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;
Expressions Computations in C# take place in expressions. Expressions Arithmetic Expressions Boolean Expressions
Operators Most arithmetic operators work as in Python, except division. –Operators: + - * / –Operators: % (modulo) Operators are evaluated according to their precedence, as in Python.
Divisions with/by reals, the result are reals Integer division, the results are integer Operators What are the values – –39 / 5 –39.0/5 –39 % 5 –5.0 % 2.2
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);
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());
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.
Examples usage of Console.WriteLine Basic usage: Specifying printing templates: Specifying extra formatting: Console.WriteLine(”Size {0}x{1}”, width, height); double salary=12000; Console.WriteLine("My salary is {0:f2}.", salary); Console.WriteLine("Hello");Console.WriteLine(area); 20
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 Kilograms (Height in Meters) X (Height in Meters) Enter weight (in kg): 83 Enter height (in m): 1.7 Your BMI is Enter weight (in kg): 83 Enter height (in m): 1.7 Your BMI is
The solution Enter weight (in kg): 83 Enter height (in m): 1.7 Your BMI is Enter weight (in kg): 83 Enter height (in m): 1.7 Your BMI is 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)
Basic output formatting When displaying floating point numbers, WriteLine may show too many digits. 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): 83 Enter height (in m): 1.7 Your BMI is Enter weight (in kg): 83 Enter height (in m): 1.7 Your BMI is
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.
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.
Partial solution method Main 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(); } 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)
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
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 put parentheses on the values to be converted. get 2, converting a double to an int in this way always rounds everything down get 2, converting a double to an int in this way always rounds everything down
Solution for Thinking Corner Shows only method Main 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(); } 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)
Additional operators C# also provides additional useful operators related to variable updates –Operators for increasing and decreasing by one –Operators for updating values
Operators for variable updates As in Python, C# provides data update operators x = x + 10x += 10 y = y * 7y *= 7 z = z / 7z /= 7
Operators ++, -- We usually increase or decrease a variable by one. In C#, it is very easy to do. x = x + 1x += 1 x++ x = x - 1x -= 1 x--
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++; }
Methods for computing mathematical functions C# provides methods for computing math functions in standard class Math.
A list of common math methods Method/ Constant Value returnedExample CallResult PI Value of Math.PI Max(x,y)Larger of the twoMath.Max(1,2)2 Abs(x)Absolute value of xMath.Abs(-1.3)1.3 Sqrt(x)Square-root of xMath.Sqrt(4.0)2.0 Round(x)Nearest integer to xMath.Round(0.8)1 Pow(x,y)xyxy Math.Pow(3,2)9.0 Log(x)Natural log of xMath.Log(10) Ceiling(x)Smallest integer greater than or equal to x Math.Ceiling(4.1)5 Cos(x)Cosine of x radiansMath.Cos(Math.PI)
Thinking corner Write a program that reads the radius and computer the area of the circle. Enter radius: 6 The area is Enter radius: 6 The area is Hint: Math.PI
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 True FalseFalse FalseFalse FalseFalse FalseFalse x < 0 height <= 140 True Fal se
Condition: Boolean expressions How to build an expression? –Comparison –Combining smaller expressions Comparison operators Boolean operators
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 Python C# is case sensitive. Therefore "True" is not the same as "true".
Comparison operators OperatorsMeaningsExamples ==Equala == 5 !=Not equaldone != False <Less thandata < 10 <=Less than or equal count <= 15 >Greater thanmoney > 0 >=Greater than or equal interest >= 0.02
Boolean operators AND OR NOT && || !
Examples x 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)
if statements if statements controls whether some statement will be executed. if( condition ) statement
คำสั่ง if-else if-else statements are used when you have two choices. if( condition) statement else statement
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. 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"); }
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");
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");
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#
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
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 the same as
Thinking corner From the previous example on computing the BMI, add a status message to the user according to the table below. BMIStatus less than 18.5Underweight 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 30Obese (Extremely Fat) Only write the part that prints the status. You can assume that the BMI has be computed and stored in variable bmi
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)
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)
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?
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-statement
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");
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)? N Your deduction is 0 baht. Do you have any children (Y/N)? N Your deduction is 0 baht. Do you have any children (Y/N)? Y How many children do you have? 2 Your deduction is baht Do you have any children (Y/N)? Y How many children do you have? 2 Your deduction is baht Do you have any children (Y/N)? Y How many children do you have? 5 Your deduction is baht Do you have any children (Y/N)? Y How many children do you have? 5 Your deduction is baht
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.
Deduction: first step 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(); }
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")
Deduction: final step 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(); }
Iteration We will look at two closely-related statements for iteration while-statement checks the condition before start or continue do-while-statement does the loop first, then checks the condition do-while-statement does the loop first, then checks the condition
while-statement Works as in Python. while( condition) statement 63 condit ion stateme nt 1 tru e stateme nt 2 : stateme nt n false
do-while-statement Python does not have the do-while statement do statement while( condition ); 64 condit ion tru e stateme nt 1 stateme nt 2 : stateme nt n false
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?
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 with do-while
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.
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.
Printing numbers: plans Write a program that prints all number in a single line. Add some code that prints new lines at appropriate place.
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++; }
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++; }
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++; } if(___________________) Console.WriteLine();
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++; }
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.