750 likes | 767 Views
C# Programming: Expressions, conditions, and repetitions. 01204111 Computer and Programming. Agenda. Expressions Input / Output Program flow control Boolean expressions Conditions Repetitions. Overview. Flow control: Boolean expressions. Repetitions. Conditions.
E N D
C# Programming:Expressions, conditions, and repetitions 01204111 Computer and Programming
Agenda • Expressions • Input / Output • Program flow control • Boolean expressions • Conditions • Repetitions
Overview Flow control: Boolean expressions Repetitions Conditions Type conversion, math methods Basics Variables, expressions, input and output
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 using System;namespace Sample { class Program { staticvoid Main() { Console.WriteLine("Hello, world"); } } } • A program starts at Main • A program is organized into a set of namespaces, classes, and methods. • You may skip the namespace part.
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); }
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"); 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.
Important types • Boolean:bool • There are two possible values, which aretrueand false. • Integer:int • Stores integers with in range2.1 x 109 -- 2.1 x 109 • Real numbers:double • Stores floating point numbers in range ± 5.0x10-324 -- ± 1.7x10308
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); • 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 name Name point9 9point _data class class_A class_”A”
Variable declaration: review • Types must be specified. • Can initialize the values at the same time int radius; string firstName; double GPA; int radius = 5; string firstName = "john"; double GPA = 2.4;
Expressions • Computations in C# take place in expressions.
Operators • Most arithmetic operators work as in Python, except division. • Operators: + - * / • Operators: % (modulo) • Operators are evaluated according to their precedence, as in Python.
Operators • What are the values • 11 + 5 • 39 / 5 • 39.0/5 • 39 % 5 • 5.0 % 2.2 16 7 Integer division, the results are integer Divisions with/by reals, the result are reals 7.8 4 0.6
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);
Conversion from strings • However, if we want to perform arithmetic computation with them, we have to convert strings to appropriate types. • Mathodint.Parse turns a string to an int. • Methoddouble.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());
Output statements • MethodConsole.Write and Console.WriteLine are common methods for showing results to console. • MethodConsole.Write is similar to methodConsole.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("Hello"); Console.WriteLine(area); Console.WriteLine(”Size {0}x{1}”, width, height); double salary=12000; Console.WriteLine("My salary is {0:f2}.", salary);
Weight in Kilograms BMI = (Height in Meters) X (Height in Meters) Thinking Corner • Write a program to read the height (in meters) and weight(in kg) and compute the BMI as in the following formula. Enter weight (in kg): 83 Enter height (in m): 1.7 Your BMI is 28.72.
The solution (click to show) 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(); } Enter weight (in kg): 83 Enter height (in m): 1.7 Your BMI is 28.719723183391. quite an ugly formatting
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. Enter weight (in kg): 83 Enter height (in m): 1.7 Your BMI is 28.72.
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, andt , 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 • methodMain (click to show) 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(); }
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 putparentheses on the values to be converted. get 2, converting a double to an int in this way always rounds everything down
Solution for Thinking Corner • Shows only methodMain (click to show) 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(); }
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 + 10 x += 10 y = y * 7 y *= 7 z = z / 7 z /= 7
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 - 1 x -= 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 += 1; } 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.
Thinking corner Write a program that reads the radius and computer the area of the circle. Enter radius: 6 The area is 113.0973 Hint: Math.PI
Program flow control x > 0 • Condition or Boolean expressions • Types of program control: • Conditional: if, if-else • Repetition: while, do-while, for x > 0 True False x < 0 x < 0 True False x == 0 height <= 140 True False
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 PythonC# is case sensitive. Therefore"True" is not the same as "true".
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 toy (i<n) && (x!=y) a is between b toc (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 has50% 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"); }
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) 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");
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) Console.WriteLine("Hello, kid"); Console.WriteLine("Your price is 25 baht"); Converted toC#
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) { Console.WriteLine("Hello, kid"); Console.WriteLine("Your price is 25 baht"); } if age <= 10: print("Hello, kid") print("Your price is 25 baht") converted to C# Block
Be careful • In C#, only curly brackets define blocks. Indentation only serves as readability enhancement. is the same as if(x > 0) total += x; count++; if(x > 0) total += x; count++; if(x > 0) { total += x; count++; } is not the same as