C# Programming: Expressions, conditions, and repetitions 01204111 Computer and Programming.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Computer and Programming
3 Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. Conditions can be formed using the.
Selection Statement – Selection Statement Modified from Aj. Thanachat Thanomkulabut’s slide 1 st semester, 2012.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Thanachat Thanomkulabut
Introduction to C# Programming ณภัทร สักทอง Application Program Development.
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Input, Output, and Processing
1 Conditional statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Chapter 2: Using Data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
CHAPTER 4: CONTROL STRUCTURES - SEQUENCING 10/14/2014 PROBLEM SOLVING & ALGORITHM (DCT 1123)
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Fundamental Programming: Fundamental Programming Introduction to C++
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
C# Basic Concept Thanachat Thanomkulabut. Naming Rules  Letters, digits and underscores(_)  First character  letter or _  Up to 63 characters long.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
Input & Output Statement
Selection Statement – Selection Statement Modified from Aj. Thanachat Thanomkulabut’s slide 1 st semester, 2012.
Selection Statement Thanachat Thanomkulabut. Outline 2  Boolean expression  if  if statement  nested if  nested if statement  switch case  switch.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 – Introduction to C# Programming Outline 3.1 Introduction 3.2 Simple Program: Printing a Line.
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
C# Programming: Basic Concept Part 2 Computer and Programming (204111)
1 nd Semester Module2 C# Basic Concept Thanawin Rakthanmanon Computer Engineering Department Kasetsart University, Bangkok.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Lecture 2 Review of 1301 and C# Richard Gesick. Common data types int, long, double, float, char, bool, string.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
C Building Block Chapter 2. Variables A variable is a space in the computer’s memory set aside for a certain kind of data and given a name for easy reference.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Input/Output Statement Thanachat Thanomkulabut. Input Statement  Console.ReadLine()  Return string  Use to get the input from user  Convert string.
1 nd Semester Module6 Review Thanawin Rakthanmanon Create by: Aphirak Jansang Computer Engineering Department Kasetsart.
Basic concepts of C++ Presented by Prof. Satyajit De
Repetition (While-Loop) version]
Thanachat Thanomkulabut
C# Programming.
Chapter 3 – Introduction to C# Programming
Conditional and iterative statements
Chapter 2 Programming Basics.
Primitive Types and Expressions
Variables in C Topics Naming Variables Declaring Variables
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

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.