+ All Categories
Home > Documents > Lecture #2: Variables, data types, basic IO M E arithmetic...

Lecture #2: Variables, data types, basic IO M E arithmetic...

Date post: 11-Mar-2020
Category:
Upload: others
View: 4 times
Download: 0 times
Share this document with a friend
63
M M E E K K I I Massive Information & Knowledge Engineering Massive Information & Massive Information & Massive Information & Knowledge Engineering Knowledge Engineering Knowledge Engineering Lecture #2: Lecture #2: Variables, data types, basic IO Variables, data types, basic IO arithmetic and assignment arithmetic and assignment operations operations 204111 Computer & Programming Dr.Arnon Rungsawang Dept. of computer engineering Kasetsart University http://mikelab.net/204111
Transcript
Page 1: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

MM EEKK

II

Massive Information &Knowledge EngineeringMassive Information &Massive Information &Massive Information &Knowledge EngineeringKnowledge EngineeringKnowledge Engineering

Lecture #2:Lecture #2:Variables, data types, basic IO Variables, data types, basic IO arithmetic and assignment arithmetic and assignment operationsoperations

204111 Computer & ProgrammingDr.Arnon RungsawangDept. of computer engineeringKasetsart Universityhttp://mikelab.net/204111

Page 2: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture2

Version 2008/1MM EEKKII

Outline of the 1Outline of the 1stst halfhalf

Review

Computer hardware/software

Variables and C# data types

Input and output

Page 3: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture3

Version 2008/1MM EEKKII

Review 01Review 01• Different programming language levels

–– Machine codeMachine code, , assembly codeassembly code, , intermediate languageintermediate language, , high level high level languagelanguage.

– A compilercompiler translates a program from a higher level language to a lower level language.

• C# compiler compiles a C# program to MSIL.MSIL.

•• IdentifiersIdentifiers– Begin with letter or underscore, compose only of letter, digit,

underscore– Reserved words:- classclass, , publicpublic, , static, if, then, static, if, then, ……– Standard Identifier:- ReadLineReadLine, WriteLineWriteLine, …– Use for class, method, namespace and variable names

Page 4: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture4

Version 2008/1MM EEKKII

Review 02Review 02• Structure of a C# program

– at least oneone or more classes•• classclass keyword• class’s name• class body within {…}

• A class consists of one or more methods.– at least one Main()Main() method

• A method consists of one or more statements.– method signature: public static voidpublic static void Main (stringstring[ ] args)– method name– method body within {…}

-> List of statements separated by ;;

Page 5: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture5

Version 2008/1MM EEKKII

C# Program Structure (Console)C# Program Structure (Console)• Program specifications (optional)

//==========================================================// // File: HelloWorld.cs 204111 Demo// // Author: Kun Toto Email: [email protected]// // Classes: HelloWorld// --------------------// This program prints the string "Hello World!”////==========================================================

• Library imports (optional)using System;

• Class definitionsclass HelloWorld{

static void Main(string[] args) {

Console.WriteLine(“Hello World!”);}

}

Page 6: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture6

Version 2008/1MM EEKKII

C# Program Structure (Window)C# Program Structure (Window)• Program specifications (optional)

//==========================================================// // File: HelloWorld.cs 204111 Demo // // Author: Kun Toto Email: [email protected]// // Classes: HelloWorld// --------------------// This program shows a message box.////==========================================================

• Library imports (optional)using System;using System.Windows.Forms;

• Class definitions

class HelloWorld{

static void Main(string[] args) {

MessageBox.Show(“Hello World!”);}

}

Page 7: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture7

Version 2008/1MM EEKKII

Review 03Review 03• The syntax rulessyntax rules of a language define how we

can put symbols, reserved words, and identifiers together to make a valid program.

• The semantics semantics of a program statement define what that statement means (its purpose or role in a program).

• A program that is syntactically correct is not is not necessarilynecessarily logically (semantically) correct.

• A program can have threethree types of errorserrors:– compile-time error– run-time error– logical error

Page 8: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture8

Version 2008/1MM EEKKII

OutlineOutline

Review

Computer hardware/software

Variables and C# data types

Input and output

Page 9: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture9

Version 2008/1MM EEKKII

• Hardware– the physical, tangible parts of a computer– E.g., CPU, storage, keyboard, monitor

Computer Environment: HardwareComputer Environment: Hardware

Monitor

Keyboard

MainMemory

CentralProcessing

Unit

CD ROM

Hard Disk

chip that executes chip that executes program commandsprogram commandse.g., e.g., Intel Pentium IVIntel Pentium IVSun Sun SparcSparcTransmetaTransmeta

primary storage area primary storage area for programs and datafor programs and data

also called RAMalso called RAM

Page 10: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture10

Version 2008/1MM EEKKII

Storing InformationStoring Information

• Computers store all information digitally:– E.g. numbers, program instructions, text, audio, and

video

• C# uses UnicodeUnicode character ranging from U+0000 to U+FFFF.– ‘A’(0041), ‘a’(0061), ‘1’(0031), ‘ก’(0E01), ‘๑’(0E51)

H i , H e a t h e r .H i , H e a t h e r .

72 105 44 32 72 101 97 116 104 101 114 4672 105 44 32 72 101 97 116 104 101 114 46

Page 11: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture11

Version 2008/1MM EEKKII

Bit Byte and Word, WhatBit Byte and Word, What’’s difference?s difference?

• Information is stored in binary numbersbinary numbers– A single binary digit (0 or 1) is called a bitbit.– A single bit can represent two possible statestwo possible states, like a

light bulb that is either on (1) or off (0).

–– CombinationsCombinations of bits are used to store values.

• 8 bits = 1 byte– Commonly used as a unit of storage in computers– RAM 512 Mb, Hard disk 80 Gb

• Word– The number of bits that a computer processor can

process at a time.– 16 bits word, 32 bits word, 64 bits word processors

Page 12: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture12

Version 2008/1MM EEKKII

Binary Bit CombinationsBinary Bit Combinations

1 bit1 bit0011

2 bits2 bits0000010110101111

3 bits3 bits000000001001010010011011100100101101110110111111

4 bits4 bits0000000000010001001000100011001101000100010101010110011001110111

1000100010011001101010101011101111001100110111011110111011111111

Each additional bit doubles the number of possible combinations.Each additional bit doubles the number of possible combinations.

Page 13: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture13

Version 2008/1MM EEKKII

Information is Stored in MemoryInformation is Stored in Memory

927892789279927992809280928192819282928292839283928492849285928592869286

Large values areLarge values arestored in consecutivestored in consecutivememory locations.memory locations.

1001101010011010Each memory cell stores a Each memory cell stores a set number of bits (usually set number of bits (usually 8 bits, or one 8 bits, or one bytebyte).).

Each memory cell has a Each memory cell has a numeric numeric addressaddress, which , which uniquely identifies it.uniquely identifies it.

Page 14: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture14

Version 2008/1MM EEKKII

Computer Environment: SoftwareComputer Environment: Software

•• Operating SystemOperating System– E.g., Linux, Mac OS X, Windows 2000, Windows XP– manages resources such as CPU, memory, and disk– controls all machine activities

•• Application ProgramsApplication Programs– generic term for any other kind of software– compiler, word processor, missile control, weather

forecast, media player, game, …

Page 15: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture15

Version 2008/1MM EEKKII

Operating SystemOperating System• What does an OS do?

– hides low level details of bare machine– arbitrates competing resource demands

• Useful attributes– multi-user– multi-tasking

OperatingSystem

UserProgram

CPU

Disk

Network

Page 16: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture16

Version 2008/1MM EEKKII

File SystemFile System

• Hierarchical (directories and files)• Filename: sequence of directory names

ending with a file name

WINDOWS

C:

Documents and Settings…

zs9

My Documents

… …

Page 17: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture17

Version 2008/1MM EEKKII

Some Useful CommandsSome Useful Commands• File system

– mkdir as0 // creates a directory named as0– cd as0 // changes current directory to as0– cd .. // changes current directory one level up– dir // list the files of current directory– del <filename> // delete the file– Note 1: you can always do the above using Windows GUI– Note 2: you can even access the directory remotely by typing

\\dotnet.cpe.ku.ac.th\zs9$\MyDocsin the Address field of your browser (replace zs9 with your net id)

• Editing– notepad <filename> // edit a file using notepad

• Note: notepad insists on adding .txt after the file name. If you do not want the .txt suffix, choose “All Files” as “Save as type”

– textpad <filename> // edit file using textpad, a code editor

Page 18: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture18

Version 2008/1MM EEKKII

Outline of the 1Outline of the 1stst halfhalf

ReviewComputer hardware/softwareVariables and C# data typesInput and output

Page 19: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture19

Version 2008/1MM EEKKII

VariablesVariables• A variablevariable is a typed name for a location in memory. • A variable must be declareddeclared, specifying the variable's

namename and the typetype of information that will be held in it.

int numberOfStudents;…

int average, max;

data typedata type variable namevariable name

int total;…

Which ones are valid variable namesmyBigVar VAR1 _test @test C# .net99bottles namespace It’s-all-over KunToto Hi!

920092009204920492089208921292129216921692209220922492249228922892329232

numberOfStudents:

average:max:

total:

Page 20: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture20

Version 2008/1MM EEKKII

Assignment OperatorAssignment Operator• An assignment statementassignment statement changeschanges the value of a variable.• The assignment operator is the == sign

• You can only assign a value to a variable that is consistent with the variable's declared type (more later).

• You can declare and assign initial value to a variable at the same time, e.g.,

int total = 55;

• The value on the right is storedstored in the variable on the left.– The value that was in total is overwritten.

total = 55;

int total;…

Page 21: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture21

Version 2008/1MM EEKKII

static void Main(string[] args){

int total;

total = 15;System.Console.Write(“total = ”);System.Console.WriteLine(total);

total = 55 + 5;System.Console.Write(“total = ”);System.Console.WriteLine(total);

}

ExampleExample

Page 22: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture22

Version 2008/1MM EEKKII

ConstantsConstants• A constantconstant is similar to a variable exceptexcept that it holds one holds one

valuevalue for its entire existence.

• The compiler will issue an error if you try to change a constant.

• In C#, we use the const modifier to declare a constant.const int numberOfStudents = 49;

• Why constants?– give names to otherwise unclear literal values– facilitate changes to the code– prevent inadvertent errors

Page 23: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture23

Version 2008/1MM EEKKII

C# Primitive Data TypesC# Primitive Data Types• There are 15 data types in C#• Eight of them represent integers:

– byte, sbyte, short, ushort, int, uint, long, ulong• Two of them represent floating point numbers:

– float, double• One of them represents decimals:

– decimal• One of them represents boolean values:

– bool• One of them represents characters:

– char• One of them represents strings:

– string• One of them represents objects:

– object

Page 24: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture24

Version 2008/1MM EEKKII

Numeric Data TypesNumeric Data Types• The difference between the various numeric types is

their size, and therefore the values they can store:Range

0 - 255-128 - 127

-32,768 - 327670 - 65537

-2,147,483,648 – 2,147,483,6470 – 4,294,967,295-9×1018 to 9×1018

0 – 1.8×1019

±1.0×10-28; ±7.9×1028 with 28-29 significant digits

±1.5×10-45; ±3.4×1038 with 7 significant digits±5.0×10-324; ±1.7×10308 with 15-16 significant digits

Question: you need a variable to represent world population. Which type do you use?

Type

bytesbyteshortushortintuintlongulong

decimal

floatdouble

Storage

8 bits8 bits16 bits16 bits32 bits32 bits64 bits64 bits

128 bits

32 bits64 bits

Page 25: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture25

Version 2008/1MM EEKKII

Examples of Numeric VariablesExamples of Numeric Variables

int x = 1;short y = 10;float pi = 3.14f; // f denotes floatfloat f3 = 7E-02f; // 0.07double d1 = 7E-100;// use m to denote a decimaldecimal microsoftStockPrice = 28.38m;

Page 26: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture26

Version 2008/1MM EEKKII

TestNumericTestNumericusing System;class TestNumeric {

static void Main( string[] args ) {int myInt = 10;Console.Write( "myInt = " );Console.WriteLine( myInt );myInt = 10 + 45;Console.Write( "myInt = " );Console.WriteLine( myInt );float myFloat = 1.234f;Console.Write( "myFloat = " );Console.WriteLine( myFloat );decimal myDecimal = 28.24m;Console.Write( "myDeciaml = " );Console.WriteLine( myDecimal );myFloat = 1.2345678901234567890f;Console.Write( "myFloat = " );Console.WriteLine( myFloat );myDecimal = 1.2345678901234567890m;Console.Write( "myDeciaml = " );Console.WriteLine( myDecimal );

}}

1234567891011121314151617181920212223 Example: TestNumeric.cs

Page 27: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture27

Version 2008/1MM EEKKII

BooleanBoolean• A boolbool value (storage size is 8 bits)

represents a truetrue or falsefalse condition.

• A boolean can also be used to represent any two states, such as a light bulb being on or off.

• The reserved words true and false are the only valid values for a boolean type.

boolbool doAgain = true;

Page 28: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture28

Version 2008/1MM EEKKII

CharactersCharacters• A charchar is a single character from the a character seta character set.

• A character setcharacter set is an ordered list of characters; each character is given a unique number.

• C# uses the UnicodeUnicode character set, a superset of ASCII. – Uses sixteen bits per character, allowing for 65,536 unique

characters– It is an international character set, containing symbols and

characters from many languages.– Code chart can be found at: http://www.unicode.org/charts/

• Character literals are represented in a program by delimiting with single quotes.– ‘A’(0041), ‘a’(0061), ‘1’(0031), ‘ก’(0E01), ‘๑’(0E51)

Page 29: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture29

Version 2008/1MM EEKKII

Escape SequencesEscape SequencesEscape sequence Description \n Newline. Position the screen cursor to the beginning of the

next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning

of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the previous characters output on that line.

\’ Used to print a single quote \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double quote (") character. \uxxxx Unicode escape sequence for character with hex value xxxx.\xn[n][n][n] Unicode escape sequence for character with hex value nnnn

(variable length version of \uxxxx). \Uxxxxxxxx Unicode escape sequence for character with hex value

xxxxxxxx (for generating surrogates).

Page 30: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture30

Version 2008/1MM EEKKII

StringString• A string represents a sequence of

characters, e.g.,string message = “Hello World”;

Strings can be created with verbatim string literals by starting with @, e.g.,

string a2 = @“\\server\fileshare\Hello.cs”;

Question: how to represent this string: The double quotation mark is “

Question: how to represent this string: \\dotnet.cpe.ku.ac.th\zs9$\MyDocs

Page 31: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture31

Version 2008/1MM EEKKII

String exampleString example

using System;class stringDemo {

public static void Main (string[] args) {string a1 = "\"Hello World!\"";string a2 = "\\\\dotnet.cpe.ku.ac.th\\zs9$\\MyDocs";string a3 = @"\\server\fileshare\Hello.cs";string a4 = a1 + "\n" + a2 + "\n" + a3;

Console.WriteLine(a4);Console.WriteLine("a1.length()=[{0}]", a1.Length);

}}

123456789101112

Page 32: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture32

Version 2008/1MM EEKKII

OutlineOutline

ReviewComputer hardware/softwareVariables and C# data typesInput and output

Page 33: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture33

Version 2008/1MM EEKKII

Data InputData Input• Console.ReadLine()

– Used to get a value from the user input– Examplestring myString = Console.ReadLine();

• Convert from string to the correct data type– Int32.Parse()

• Used to convert a string argument to an integer• Allows math to be preformed once the string is converted• Example:

string myString = “1023”;int myInt = Int32.Parse( myString );

– Double.Parse()

Page 34: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture34

Version 2008/1MM EEKKII

Console.ReadLineConsole.ReadLine()()using System;class ioDemo {

static void Main () {//string myStr = Console.ReadLine();string myStr = "1234";int a = Int32.Parse(myStr);double b = Double.Parse(myStr);Console.WriteLine("[{0}] [{1:F}]", a, b);

}}

Page 35: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture35

Version 2008/1MM EEKKII

Difference betweenDifference between Console.ReadConsole.Read()() && Console.ReadLineConsole.ReadLine()()

• Console.ReadLine() return a stringstring value from the standard input device.double myPI = Double.Parse(Console.ReadLine());

–– RunRun--time errortime error may be occurred if your input is uncorrected.

• Console.Read() return an intint value of the (onlyonly) first character typed at the standard input device.int myAge = Console.Read();

– If you input “A123”, myAge will get integer value 65.– If you input “18”, myAge will get integer value 49.

Page 36: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture36

Version 2008/1MM EEKKII

Console.ReadConsole.Read()()using System;class Console_Read {

static void Main() {int i = Console.Read();string a = Console.ReadLine();Console.WriteLine("[{0}], [{1}]", i, a);

}}

Page 37: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture37

Version 2008/1MM EEKKII

WhatWhat’’s wrong with this?s wrong with this?using System;class ioDemo {public static void Main (string[] args) {Console.Write("Please type your name : ");string myName = Console.ReadLine();Console.Write("Please type your age : ");int myAge = Console.Read();Console.WriteLine("Hello, {0}, how are you?", myName);Console.WriteLine("You are {0} year old, wow!!", myAge);Console.Read();// what wrong with this program???

}}

Page 38: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture38

Version 2008/1MM EEKKII

OutputOutput• Console.WriteLine(variableName);

• You can use the values of some variables at some positions of a string:System.Console.WriteLine(“{0} {1}.”, iAmVar0, iAmVar1);

• You can control the output format by using the format specifiers:float price = 2.5f;System.Console.WriteLine(“Price = {0:C}.”, price);Price = $2.50.

For a complete list of format specifiers, seehttp://msdn.microsoft.com/library/en-us/csref/html/vclrfFormattingNumericResultsTable.asp

Example: TaxAndTotal.cs

Page 39: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture39

Version 2008/1MM EEKKII

Output exampleOutput example

Page 40: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture40

Version 2008/1MM EEKKII

Output formatOutput formatSymbol Meaning Exaple of usage Result

D or d Decimal Console.WriteLine(“ {0:D} ",10}; 10

E or e Exponential Console.WriteLine(“ {0:E} ",10}; 1.000000E+001

F or f Fix Point Console.WriteLine(“ {0:F} ",10}; 10.00

X or x Hexadecimal Console.WriteLine(“ {0:X} ",10}; A

P or p Percent Console.WriteLine(“ {0:P} ",10}; 1,000.00 %

Page 41: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture41

Version 2008/1MM EEKKII

Output Format (2) Output Format (2) using System;class myFormat {static void Main() {int a = 123456;Console.WriteLine("{0:C}", a);Console.WriteLine("{0:D}", a);Console.WriteLine("{0:E}", a);Console.WriteLine("{0:F}", a);Console.WriteLine("{0:N}", a);Console.WriteLine("{0:P}", a);Console.WriteLine("{0:X}", a);Console.WriteLine("{0: dd mm yyyy}", DateTime.Now);

}}

1234567891011121314

Page 42: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture42

Version 2008/1MM EEKKII

Short brakeShort brake

• 5 minutes

Page 43: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture43

Version 2008/1MM EEKKII

22ndnd--Half OutlineHalf Outline

Arithmetic operations

Assignment operations

Page 44: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture44

Version 2008/1MM EEKKII

Arithmetic ExpressionsArithmetic Expressions• An expressionexpression is a combination of operators and

operands.•• Arithmetic expressionsArithmetic expressions (we will see logical

expressions later) compute numeric results and make use of the arithmetic operators:

Addition + Subtraction -Multiplication *Division /Remainder %

There are no exponents

Page 45: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

MM EEKK

II

Massive Information &Knowledge EngineeringMassive Information &Massive Information &Massive Information &Knowledge EngineeringKnowledge EngineeringKnowledge Engineering

1 // Arithmetic.cs2 using System;3 class Arithmetic4 {5 static void Main( string[] args )6 {7 string firstNumber, // first string entered by user8 secondNumber; // second string entered by user9 int number1, // first number to add10 number2; // second number to add11 // prompt for and read first number from user as string12 Console.Write( "Please enter the first integer: " );13 firstNumber = Console.ReadLine();14 // read second number from user as string15 Console.Write( "\nPlease enter the second integer: " );16 secondNumber = Console.ReadLine();17 // convert numbers from type string to type int18 number1 = Int32.Parse( firstNumber );19 number2 = Int32.Parse( secondNumber );20 // do operations21 int sum = number1 + number2;22 int diff = number1 - number2;23 int mul = number1 * number2;24 int div = number1 / number2;25 int mod = number1 % number2;26 // display results27 Console.WriteLine( "\n{0} + {1} = {2}.", number1, number2, sum );28 Console.WriteLine( "\n{0} – {1} = {2}.", number1, number2, diff );29 Console.WriteLine( "\n{0} * {1} = {2}.", number1, number2, mul );30 Console.WriteLine( "\n{0} / {2} = {2}.", number1, number2, div );31 Console.WriteLine( "\n{0} % {1} = {2}.", number1, number2, mod );32 } // end method Main33 } // end class Arithmetic

Page 46: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture46

Version 2008/1MM EEKKII

Division and RemainderDivision and Remainder• If both operands to the division operator (/) are integers,

the result is an integer (the fractional part is discarded).

• The remainder operator (%) returns the remainder after dividing the second operand into the first.

8 / 12 equals?

14 / 3 equals? 4

0

14 % 3 equals?

8 % 12 equals?

2

8

Page 47: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture47

Version 2008/1MM EEKKII

Operator PrecedenceOperator Precedence• Operators can be combined into complex expressions.

result = total + count / max - offset;

• Operators have a well-defined precedenceprecedence which determines the order in which they are evaluated.

•• Precedence rulesPrecedence rules– Parenthesis are done first.– Division, multiplication and modulus are done second.

• Left to right if same precedence (this is called associativeassociative).– Addition and subtraction are done last.

• Left to right if same precedence.

Page 48: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture48

Version 2008/1MM EEKKII

Precedence of Arithmetic Operations Precedence of Arithmetic Operations

Operator(s) Operation Order of evaluation (precedence) ( ) Parentheses Evaluated first. If the parentheses are nested,

the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

*, / or % Multiplication Division Modulus

Evaluated second. If there are several such operators, they are evaluated left to right.

+ or - Addition Subtraction

Evaluated last. If there are several such operators, they are evaluated left to right.

Precedence of arithmetic operators.

Page 49: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture49

Version 2008/1MM EEKKII

Operator Precedence: ExamplesOperator Precedence: Examples

• What is the order of evaluation in the following expressions?

a + b + c + d + e432

a + b * c - d / e3 241

a / (b + c) - d % e2 341

a / (b * (c + (d - e)))4 123

1

Example: TemperatureConverter.cs

Page 50: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture50

Version 2008/1MM EEKKII

Data ConversionsData Conversions• Sometimes it is convenient to convert data from one type

to another.– For example, we may want to treat an integer as a floating point

value during a computation.

• Conversions must be handled carefully to avoid losing information.

•• Two types of conversionsTwo types of conversions–– Widening conversionsWidening conversions are generally safe because they tend to

go from a small data type to a larger one (such as a short to an int).

• Q: how about int to long?–– Narrowing conversionsNarrowing conversions can lose information because they tend

to go from a large data type to a smaller one (such as an int to a short).

Page 51: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture51

Version 2008/1MM EEKKII

Data ConversionsData Conversions• In C#, data conversions can occur in three ways:

–– Assignment conversionAssignment conversion• occurs automatically when a value of one type is assigned to

a variable of another• only widening conversions can happen via assignment• Example: aFloatVar = anIntVar

–– Arithmetic promotionArithmetic promotion• happens automatically when operators in expressions

convert their operands• Example: aFloatVar / anIntVar

–– CastingCasting

Page 52: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture52

Version 2008/1MM EEKKII

Data Conversions: CastingData Conversions: Casting•• CastingCasting is the most powerful, and dangerousdangerous, technique

for conversion.• Both widening and narrowing conversions can be

accomplished by explicitly casting a value.• To cast, the type is put in parentheses in front of the

value being converted.• For example, if total and count are integers, but we

want a floating point result when dividing them, we can cast total:

result = (float) total / count;

Example: DataConversion.cs

Page 53: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture53

Version 2008/1MM EEKKII

Data Conversions: Parse()Data Conversions: Parse()

• Parse() will convert string to other values.– double.Parse()– Int64.Parse()– int.Parse()– Int16.Parse()– char.Parse()– byte.Parse()

using System;class ioDemo {static void Main () {//string myStr = Console.ReadLine();string myStr = "1234";int a = Int32.Parse(myStr);double b = Double.Parse(myStr);Console.WriteLine("[{0}] [{1:F}]", a, b);long c = Int64.Parse(myStr);Console.WriteLine("[{0}] [{1}]", a, c);short d = Int16.Parse(myStr);Console.WriteLine("[{0}] [{1}]", a, d);

}}

Page 54: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture54

Version 2008/1MM EEKKII

OutlineOutline

Admin. and reviewArithmetic operationsAssignment operations

Page 55: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture55

Version 2008/1MM EEKKII

Assignment RevisitedAssignment Revisited• You can consider assignment as another

operator, with a lower precedence than the arithmetic operators.

First the expression on the right handFirst the expression on the right handside of the = operator is evaluatedside of the = operator is evaluated

Then the result is stored in theThen the result is stored in thevariable on the left hand sidevariable on the left hand side

answer = sum / 4 + MAX * lowest;

14 3 2

Page 56: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture56

Version 2008/1MM EEKKII

Assignment RevisitedAssignment Revisited

• The right and left hand sides of an assign-ment statement can contain the same variable.

First, one is added to theFirst, one is added to theoriginal value of original value of countcount

Then the result is stored back into Then the result is stored back into countcount(overwriting the original value)(overwriting the original value)

count = count + 1;

Page 57: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture57

Version 2008/1MM EEKKII

Assignment OperatorsAssignment Operators

Assignment operator Sample expression Explanation += c += 7 c = c + 7 -= d -= 4 d = d - 4 *= e *= 5 e = e * 5 /= f /= 3 f = f / 3 %= g %= 2 g = g % 2

Page 58: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture58

Version 2008/1MM EEKKII

Increment and Decrement OperatorsIncrement and Decrement Operators

Operator Called Sample expression Explanation ++ preincrement ++a Increment a by 1, then use the new value

of a in the expression in which a resides.

++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.

-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.

-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

The increment and decrement operators.

Page 59: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

MM EEKK

II

Massive Information &Knowledge EngineeringMassive Information &Massive Information &Massive Information &Knowledge EngineeringKnowledge EngineeringKnowledge Engineering

1 // Increment.cs2 // Preincrementing and postincrementing3 4 using System;5 6 class Increment7 {8 static void Main(string[] args)9 {10 int c;11 12 c = 5;13 Console.WriteLine( c ); // print 514 Console.WriteLine( c++ ); // print 5 then postincrement15 Console.WriteLine( c ); // print 616 17 Console.WriteLine(); // skip a line18 19 c = 5;20 Console.WriteLine( c ); // print 521 Console.WriteLine( ++c ); // preincrement then print 622 Console.WriteLine( c ); // print 623 24 } // end of method Main25 26 } // end of class Increment

556

566

Page 60: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture60

Version 2008/1MM EEKKII

Operators Associativity Type () ++ --

left to right right to left

parentheses unary postfix

++ -- + - (type) right to left unary prefix

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

?: right to left conditional

= += -= *= /= %= right to left assignment

Precedence and Precedence and AssociativityAssociativity

high

low

Page 61: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

MM EEKK

II

Massive Information &Knowledge EngineeringMassive Information &Massive Information &Massive Information &Knowledge EngineeringKnowledge EngineeringKnowledge Engineering

Additional SlidesAdditional Slides

Page 62: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture62

Version 2008/1MM EEKKII

ASCII TableASCII Table

Page 63: Lecture #2: Variables, data types, basic IO M E arithmetic ...mcs/courses/2007_02/204111/slides/L02.pdf204111 Computer & Programming - 2nd Lecture 4 M II K EE Version 2008/1 Review

204111 Computer & Programming - 2nd Lecture63

Version 2008/1MM EEKKII


Recommended