Title: Special Topics 2
1 - Special Topics 2
- C
- Summer 2009
- Luai M. Malhis, PH.D
2Introduction
- The course notes will be taken from many sources
on the internet - Other universities
- From past courses at An-najah
- From special sites dedicated to C
- The complete set is not available
- Course notes will be posted on the OCC
3Introduction Continue
- Course administration
- Grading policy 20 First exam,
- 20 Second exam, , 20 Assignments , 40 Final
exam. - Text Book F. Scott Barker
- Visual C 2005
4C Library .NET Framework
- Introduced by Microsoft (June 2000)
- Vision for embracing the Internet in software
development - Language- and platform- independence
- Visual Basic .NET, Visual C .NET, C and more
- Includes Framework Class Library (FCL) for reuse
- Executes programs by Common Language Runtime
(CLR) - Programs compiled to Microsoft Intermediate
Language (MSIL) - MSIL code translated into machine code
- (Unlike Java) .NET is mostly Windows (MS) centric
- There is a Linux port (e.g., the Mono project)
5C the Language
- Developed at Microsoft by Anders Hejlsberg et al.
- Based on Java
- event-driven, object-oriented, network-aware,
visual programming language - Incorporated into .NET platform
- Web based applications can be distributed
- Programs that can be accessed by anyone through
any device - Allows communicating with different computer
languages - Integrated Design Environment (IDE)
- Makes programming and debugging fast and easy
- Rapid Application Development (RAD)
6 C Continue
- It is related to Java and C
- Picking up Java after C should be easy.
- It is simpler than other object-oriented
languages C - It is safe and robust --- no core dump or dead
console - It has good library and development support
- good graphics package
- good client-server and network support
- It is good for your summer course
- However, it is not easy to learn, with many
features
7C Translation and Execution
- The C compiler translates C source code (.cs
files) into a special representation called
Microsoft Intermediate Language (MSIL) - MSIL is not the machine language for any
traditional CPU, but a virtual machine - The Common Language Runtime (CLR) then interprets
the MSIL file - It uses a just-in-time compiler to translate from
MSIL format to machine code on the fly
8C Compilation and Execution
C source code
9The .NET Framework
- Source code ? MSIL? machine language using
JIT - Common Language Runtime (CLR) Programs are
compiled into machine-specific instructions in
two steps - First, the program is compiled into Microsoft
Intermediate Language (MSIL) which is placed into
the application's executable file. -
- Using JIT (Just-in-time ) compiler which converts
MSIL to machine language, (JIT compile assemblies
into native binary that targets a specific
platform )
10Setting the Path Environment
- Assuming that windows and VS.NET2005 is
installed on the C drive on your computer, add
the following to the Environment Path - C\WINDOWS\Microsoft.NET\Framework\v2.0.50727
- C\Program Files\Microsoft Visual Studio
8\SDK\v2.0\Bin - C\Program Files\Microsoft Visual Studio
8\VC\bin - C\Program Files\Common Files\MicrosoftShared\VS
A\8.0\VsaEnv
11Compiling
- The .NET Framework can be thought of as a VM
(virtual machine) - Save any C program in a text file
example1.cs, and set the environment variable
PATH to point to csc.exe compiler in the .NET
framework directory. - Go to the System Properties by right clicking
you? My Computer ? properties? Environment
variables? click on new? type path?C\WINDOWS\Micr
osoft.NET\Framework\v2.0.50727. - Now open the command console cmd and type
csc example1.cs.
12A Simple C Program
- //
- //
- //
- // Classes HelloWorld
- // --------------------
- // This program prints a string called "Hello
World! - //
- //
- using System
- class HelloWorld
-
- static void Main(string args)
-
- Console.WriteLine(Hello World!)
-
13White Space and Comments
- White Space
- Includes spaces, newline characters, tabs,
blanklines - C programs should be formatted to enhance
readability, using consistent indentation! - Comments
- Comments are ignored by the compiler used only
for human readers (i.e., inline documentation) - Two types of comments
- Single-line comments use //
- // this comment runs to the end of the line
- Multi-lines comments use / /
- / this comment runs to the terminating
- symbol, even across line breaks
/
14Identifiers
- Identifiers are the words that a programmer uses
in a program - An identifier can be made up of letters, digits,
and the underscore character - They cannot begin with a digit
- C is case sensitive, therefore args and Args are
different identifiers - Sometimes we choose identifiers ourselves when
writing a program (such as HelloWorld) - Sometimes we are using another programmer's
code, so we use the identifiers that they chose
(such as WriteLine)
using System class HelloWorld static void
Main(string args)
Console.WriteLine(Hello World!)
15Identifiers Keywords
- Often we use special identifiers called keywords
that already have a predefined meaning in the
language - Example class
- A keyword cannot be used in any other way
All C keywords are lowercase!
16Namespaces
- Partition the name space to avoid name conflict!
- All .NET library code are organized using
namespaces! - By default, C code is contained in the global
namespace - To refer to code within a namespace, must use
qualified name (as in System.Console) or import
explicitly (as in using System )
using System class HelloWorld static void
Main(string args) Console.WriteLine(He
llo World!)
class HelloWorld static void Main(string
args) System.Console.WriteLine(Hello
World!)
17C Program Structure
- In the C programming language
- A program is made up of one or more classes
- A class contains one or more methods
- A method contains program statements
- These terms will be explored in detail throughout
the course
18C Program Structure Class
// comments about the class
class HelloWorld
class header
class body
Comments can be added almost anywhere
19C Classes
- Each class name is an identifier
- Can contain letters, digits, and underscores (_)
- Cannot start with digits
- Can start with the at symbol (_at_)
- Convention Class names are capitalized, with
each additional English word capitalized as well
(e.g., MyFirstProgram ) - Class bodies start with a left brace ()
- Class bodies end with a right brace ()
20C Program Structure Method
// comments about the class
class HelloWorld
Console.Write(Hello World!) Console.WriteLine(
This is from CS112!)
21C Method and Statements
- Methods
- Building blocks of a program
- The Main method
- Each console or windows application must have
main method defined as static - All programs start by executing the Main method
- Braces are used to start () and end () a method
- Statements
- Every statement must end in a semicolon
22Console Application vs. Window Application
- Console Application
- No visual component
- Only text input and output
- Run under Command Prompt or DOS Prompt
- Window Application
- Forms with many different input and output types
- Contains Graphical User Interfaces (GUI)
- GUIs make the input and output more user
friendly! - Message boxes
- Within the System.Windows.Forms namespace
- Used to prompt or display information to the user
23Syntax and Semantics
- The syntax rules of a language define how we can
put symbols, reserved words, and identifiers
together to make a valid program - The 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
necessarily logically (semantically) correct - A program will always do what we tell it to do,
not what we meant to tell it to do
24Errors
- A program can have three types of errors
- The compiler will find problems with syntax and
other basic issues (compile-time errors) - If compile-time errors exist, an executable
version of the program is not created - A problem can occur during program execution,
such as trying to divide by zero, which causes a
program to terminate abnormally (run-time errors) - A program may run, but produce incorrect results
(logical errors)
25Constants
- A constant is similar to a variable except that
it holds one value for its entire existence - The compiler will issue an error if you try to
change a constant - In C, we use the constant modifier to declare a
constant - constant int numberOfStudents 42
- Why constants?
- give names to otherwise unclear literal values
- facilitate changes to the code
- prevent inadvertent errors
26C 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
27Numeric 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 - 32767 0 -
65537 -2,147,483,648 2,147,483,647 0
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
Type byte sbyte short ushort int uint long ulong
decimal float double
Storage 8 bits 8 bits 16 bits 16 bits 32 bits 32
bits 64 bits 64 bits 128 bits 32 bits 64 bits
Question you need a variable to represent world
population. Which type do you use?
28Examples of Numeric Variables
- int x 1
- short y 10
- float pi 3.14
- float f2 9.81f
- float f3 7E-02 // 0.07
- double d1 7E-100
- decimal microsoftStockPrice 28.38m
29Boolean
- A bool value represents a true or false 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 - bool doAgain true
30Characters
- A char is a single character from the a character
set - A character set is an ordered list of characters
each character is given a unique number - C uses the Unicode 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, e.g., - 'a 'X '7' ' ',
- char response Y
31Common Escape Sequences
32string
- A string represents a sequence of characters,
e.g., - string message Hello World
- string filepath C\\ProCSharp\\First.cs
- Strings can be created with verbatim string
literals by starting with _at_, e.g., - No escape sequence
- string a2 _at_\server\fileshare\Hello.cs
- string filepath _at_C\ProCSharp\First.cs
33Types
All types are compatible with object -can be
assigned to variables of type object -all
operations of type object are applicable to them
34Value Types versus Reference Types
35Data Input
- Console.Read()
- Reads a single character from the user
input - Example char c Console.Read()
- Console.ReadLine()
- Used to get a value from the user input
- Example string myString Console.ReadLine()
- Convert from string to the correct data type
- Int.Parse(), Int16.Parse() 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(), Single.Parse()
36Output
- Console.Write(exp) prints the exp no end of line
- close to 20 overlaods
- Console.WriteLine(exp) prints the exp append end
of line - close to 20 overloads
- You can use the values of some variables at some
positions of a stringSystem.Console.WriteLine(
0 1., iAmVar0, iAmVar1) - You can control the output format by using the
format specifiersfloat price 2.5f - System.Console.WriteLine(Price 0C.,
price) - output ------------------ Price 2.50.
- For a complete list of format specifiers,
seehttp//msdn.microsoft.com/library/en-us/csref/
html/vclrfFormattingNumericResultsTable.asp
Example TaxAndTotal.cs
37Example
- // This program gets 10 grades from the user and
computes their - // average. This is Fig. 4.7 of the textbook.
- //
- //
- using System
- class Average1
-
- static void Main(string args)
-
- int total, // sum of grades
- gradeCounter, // number of grades
entered - gradeValue, // grade value
- average // average of all
grades - // initialization phase
- total 0 // clear total
- gradeCounter 1 // prepare to loop
- // next slide processing phase
38Example continue
- while (gradeCounter lt 10) // loop 10 times
-
- // prompt for input and read grade
from user - Console.Write("Enter integer grade
") - // read input and convert to integer
- gradeValue Int32.Parse(Console.ReadL
ine()) - // add gradeValue to total
- total total gradeValue
- // add 1 to gradeCounter
- gradeCounter gradeCounter 1
- // end of while
- // termination phase
- average total / 10 // integer
division - // display average of exam grades
- Console.WriteLine("\nClass average is
0", average) - // end of method Main
- // end of class
39Arithemtic Operators
- Just as in C/Java
- Operators can be combined into complex
expressions - result total count / max - offset
- Operators have a well-defined precedence which
determines the order in which they are evaluated - Precedence rules
- Parenthesis are done first
- Division, multiplication and modulus are done
second - Left to right if same precedence (this is called
associativity) - Addition and subtraction are done last
- Left to right if same precedence
40Precedence of Arithmetic Operations
41Code to test arithmetic operations
// define variables string firstNumber,
secondNumber int number1,
number2 // read two numbers from
the input. Console.Write( "Please enter
the first integer " ) firstNumber
Console.ReadLine() Console.Write(
"\nPlease enter the second integer " )
secondNumber Console.ReadLine() //
convert numbers from type string to type int
number1 Int32.Parse( firstNumber )
number2 Int32.Parse( secondNumber )
// do operations int sum number1
number2 int diff number1 - number2
int mul number1 number2 int div
number1 / number2 int mod number1
number2 Console.WriteLine( "\n0 1
2.", number1, number2, sum )
Console.WriteLine( "\n0 - 1 2.", number1,
number2, diff ) Console.WriteLine(
"\n0 1 2.", number1, number2, mul )
Console.WriteLine( "\n0 / 2 2.",
number1, number2, div )
Console.WriteLine( "\n0 1 2.", number1,
number2, mod )
42Data 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 conversions
- Widening 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 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)
43Data Conversions
- In C, data conversions can occur in three ways
- Assignment 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 promotion
- happens automatically when operators in
expressions convert their operands - Example aFloatVar / anIntVar
- Casting
44Data Conversions Casting
- Casting is the most powerful, and dangerous,
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
45Compatibility Between Simple Types
46Assignment Revisited
- You can consider assignment as another operator,
with a lower precedence than the arithmetic
operators
First the expression on the right hand side of
the operator is evaluated
answer sum / 4 MAX lowest
1
4
3
2
Then the result is stored in the variable on the
left hand side
47Assignment Operators
48Increment and Decrement Operators
49 Equality and Relationa Operators
Note the difference between the equality operator
() and the assignment operator ()
Question if (grade 100)
Console.WriteLine( Great! )
50More Complex (Compound) Boolean Expressions
Logical Operators
- Boolean expressions can also use the following
logical and conditional operators - ! Logical NOT
- Logical AND
- Logical OR
- Logical exclusive OR (XOR)
- Conditional AND
Conditional OR - They all take boolean operands and produce
boolean results
51Comparison Logical and Conditional Operators
- Logical AND () and Logical OR ()
- Always evaluate both conditions
- Conditional AND () and Conditional OR ()
- Would not evaluate the second condition if the
result of the first condition would already
decide the final outcome. - Ex 1 false (x gt 10) --- no need to
evaluate the 2nd condition - Ex 2 if (count ! 0 total /count)
-
52Operations on Enumerations
Console.WriteLine(1 4) // bitwise OR
5 Console.WriteLine(1 4) // bitwise AND 0
Console.WriteLine(71) // Error
Console.WriteLine(6 9)// Error
Console.WriteLine(truefalse) // True
Console.WriteLine(true false) // False
Console.WriteLine(!true) // False
53Precedence and Associativity
high
low
54Declaration of Local Variables
55Additional points on local variables
- int foo 1
- if (foo) Console.WriteLine("yes")
- ERROR No implicit conversion between int and
bool - Variables must be assigned before their value is
used - int x,y
- if (x gt 5) y x
- ERROR x must be assigned before used
56Conditional Statements
- A conditional statement lets us choose which
statement will be executed next - Conditional statements give us the power to make
basic decisions - C's conditional statements
- the if statement
- the if-else statement
- Conitional operator exp1? Va1 val2
- the switch statement
- All just as in c/Java
- (close look at conditional operator and
switch)
57The Conditional Operator
- The conditional operator is similar to an if-else
statement, except that it is an expression that
returns a value - For example
- larger (num1 gt num2) ? num1 num2
- If num1 is greater that num2, then num1 is
assigned to larger otherwise, num2 is assigned
to larger - The conditional operator is ternary, meaning that
it requires three operands
58The Conditional Operator
- Another example
-
- If count 1, then Quarter" is stored in result
Otherwise, Quarters" is stored
string result int count result (count
lt1 ) ? Quarter Quarters // beginning of
the next statement
59if Statement Example
- char ch // char c Console.Read()
- int val
- if('0' lt ch ch lt '9')
- val ch -'0'
- else if('A' lt ch ch lt 'Z')
- val 10 ch -'A'
- else
- val 0
- Console.WriteLine("invalid character 0", ch)
-
60The switch Statement
- The switch statement provides another means to
decide which statement to execute next - The switch statement evaluates an expression,
then attempts to match the result to one of
several possible cases - Each case contains a value and a list of
statements - The flow of control transfers to statement list
associated with the first value that matches
61The switch Statement Syntax
- The general syntax of a switch statement is
switch ( expression ) case value1
statement-list1 case value2
statement-list2 case value3
statement-list3 case ...
62The switch Statement
- The expression of a switch statement must result
in an integral data type, like an integer or
character or a string - Note that the implicit boolean condition in a
switch statement is equality - it tries to match
the expression with a value
63The switch Statement
- A switch statement can have an optional default
case as the last case executed in the statement - The default case has no associated value and
simply uses the reserved word default - If the default case is present, control will
transfer to it if no other case value matches - If there is no default case, and no other value
matches the expression, control falls through to
the statement after the switch - A break statement is used as the last statement
in each case's statement list - A break statement causes control to transfer to
the end of the switch statement
64switch Statement
- Type of switch expressionnumeric, char, enum or
string(null ok as a case label).
Type of switch expression numeric, char, enum
or string (null ok as a case label).
65switch with goto
66Loops
67foreach Statement
68Jumps
cc int z
int x 7 if(xlt7) goto cc
// error no jump into block Also no
jump out of a class
69Enumerations
- List of named constants
- Declaration (directly in a namespace)
- How to use
- enum Color red, blue, green // values 0, 1, 2
- enum Access personal1, group2, all4 1,2,4
- enum Access1 byte personal2, group, all //
values 2, 3, 4 -
- The last definition (Access1) is used to save
memory
Color c Color.blue // enumeration constants
must be qualified Console.WriteLine(c) // writes
out blue Console.WriteLine((int)c) //Writes out 1
70Operations on Enumerations
Color c Color. blue
71Enumerations, example
- enum Season Spring, Summer, Fall, Winter
-
- class Example
- public void Method (Season a)
- Season b // local variable
-
- private Season c
-
- Season s Season.Fall
- Console.WriteLine(s) // writes out 'Fall'
- string name s.ToString()
- Console.WriteLine(name) // also
writes out 'Fall' - Season y Season.Fall
- Console.WriteLine((int) y) // writes out '2'
72Enumerations, example
- using System
- public enum Volume byte Low 1, Medium, High
- class EnumBaseAndMembers
- public static void Main()
- Volume myVolume Volume.Low
- switch (myVolume)
- case Volume.Low
- Console.WriteLine("The volume has
been turned Down.") - break
- case Volume.Medium
- Console.WriteLine("The volume is
in the middle.") - break
- case Volume.High
- Console.WriteLine("The volume has
been turned up.") - break
-
- Console.ReadLine()
-
73Arrays One-dimensional Array
- int a new int3
- int b new int 3, 4, 5
- int c 3, 4, 5
- SomeClass d new SomeClass10// Array of
references - SomeStruct e new SomeStruct10// Array of
values - int len a.Length // number of elements in a
74Multidimensional Arrays
- Jagged (like in Java)
- nt a new int2
- a0 new int3
- a1 new int4
- int x a01
- int len a.Length// 2
- len a0.Length// 3
- int c new int 2 5 // error
- Rectangular (more compact, more efficient access)
- int, a new int2, 3
- int x a0, 1
- int len a.Length // 6
- len a.GetLength(0) // 2 return the number
of rows - len a.GetLength(1) // 3 return the number
of columns
75 Arrays Continue
- int , b 1, 2 , 3, 4
- int , b
- b new int 3, 4
- string names"Bob", "Ted", "Alice"
76using System class Array public
static void Main() int myInts 5, 10,
15 bool myBools new bool2 myBools
0 new bool2 myBools1 new
bool1 double, myDoubles new double2,
2 string myStrings new string3 Conso
le.WriteLine ("myInts0 0, myInts1 1,
myInts2 2", myInts0, myInts1,
myInts2) myBools00 true myBools0
1 false myBools10 true Console.WriteL
ine ("myBools00 0, myBools10 1",
myBools00, myBools10)
77 - myDoubles0,0 3.17
- myDoubles0,1 7.157
- myDoubles1,1 2.117
- myDoubles1,0 556.00138917
- Console.WriteLine ("myDoubles0,0 0,
myDoubles1,0 1", myDoubles0,0,
myDoubles1,0) - myStrings0 "Joe"
- myStrings1 "Matt"
- myStrings2 "Robert"
- Console.WriteLine ("myStrings0 0,
myStrings1 1, myStrings2 2",
myStrings0, myStrings1, myStrings2)
78strings
- string s1 "orange"
- string s2 "red"
- s1 s2
- System.Console.WriteLine(s1) // outputs
"orangered" - s1 s1.Substring(2, 5) // 2 is start
index 5 is length - System.Console.WriteLine(s1) // outputs
"anger - int year 1999
- string msg "ahmad was born in "
year.ToString() - System.Console.WriteLine(msg) // outputs
"ahmad was born in 1999"
79String 2
- string s3 "Visual C Express"
- System.Console.WriteLine(s3.Substring(7, 2))
// outputs "C" - System.Console.WriteLine(s3.Replace("C",
"Basic")) //outputs "Visual Basic Express - string s4 "Hello, World"
- char arr s4.ToCharArray(0, s4.Length) //
be carefull to range, else exception - foreach (char c in arr)
- System.Console.Write(c) // outputs
"Hello, World" -
- string s6 "hi to all"
- System.Console.WriteLine(s6.ToUpper()) //
outputs "HI TO ALL" - System.Console.WriteLine(s6.ToLower()) //
outputs "hi to all"
80Strings 3
- string color1 "red"
- string color2 "green"
- string color3 "red"
- if (color1 color3)
-
- System.Console.WriteLine("Equal")
-
- if (color1 ! color2)
-
- System.Console.WriteLine("Not
equal") -
81Strings 4
- When comparing strings, the Unicode value is
used, and lower case has a smaller value than
upper case. - string s7 "ABC"
- string s8 "abc"
- if (s7.CompareTo(s8) gt 0)
-
- System.Console.WriteLine("Greater-than
")//Greater-than -
- else
-
- System.Console.WriteLine("Less-than")
-
- Will print Greater-than
82Strings 5
- To search for a string inside another string, use
IndexOf(). IndexOf() returns -1 if the search
string is not found otherwise, it returns the
zero-based index of the first location at which
it occurs. - string s9 "Battle of Hastings, 1066"
- System.Console.WriteLine(s9.IndexOf("Hastings"))
// outputs 10 - System.Console.WriteLine(s9.IndexOf("1967"))
// outputs -1 - System.Console.WriteLine(s9.IndexOf('o') //
outputs 7 - 9 overloads to ndexof may take strat index
length and others
83String 6
- char delimit new char ' '
- string s10 "The cat sat on the mat."
- foreach (string substr in
s10.Split(delimit) ) -
- System.Console.WriteLine(substr)
-
- //------------------------------------------------
------- - //char delimit new char ' '
- char cf ''
- string s10 "The cat sat on the mat."
- foreach (string substr in s10.Split(cf))
- System.Console.WriteLine(substr)
-
84Strings 7
- string t "Once,UponA/Time\\In\'America"
- char sep2 new char ' ', ',', '',
'/', '\\', '\'' - foreach (string ss in t.Split(sep2))
- Console.WriteLine(ss)
-
85Program Example
- This program keeps reading int from the keyboard
until -1 is entered. Prints the sum of all entred
numbers. It demonstrate the use of Split and
goto -
- static void Main(string args)
-
- int x -1
- int sum 0
- char ar ' '
- L1 string inp Console.ReadLine()
- foreach (string s in inp.Split(ar))
-
- x int.Parse(s)
- sum x
- Console.WriteLine(x)
-
-
- if (x ! -1)
- goto L1
- Console.WriteLine("the sum is 0",
sum) -
86Example 2 Tax Example
- static void Main( string args )
- // First get amount
- Console.Write( "Please enter amount " )
- string amountString
- amountString Console.ReadLine() // get
the amount from user - // convert from amount string to floating
point number - float amount Single.Parse( amountString
) - // Next get tax rate
- Console.Write( "Please enter tax rate "
) - string taxRateString
- taxRateString Console.ReadLine() //
get the tax rate from user - // convert from string to floating point
number - float taxRate Single.Parse(
taxRateString ) - // Now compute total
- float total amount (1 taxRate)
87Constructing output strings
- int x 12 double y 13.4 float z
12f char c 'a' - string s1 "The sum of " x " and " y "
is " (xy) Console.WriteLine(s1) -
- s1 "The diff between " x2 " and "
y/2 " is " (x2 - y/2) - Console.WriteLine(s1)
- s1 (x y).ToString()
Console.WriteLine(s1) - s1 12.ToString() s1 13
Console.WriteLine(s1) - s1 "" s1 s1 z
cConsole.WriteLine(s1) - s1 "" s1 s1 (z c)
Console.WriteLine(s1) - s1 "" s1 s1 z / c
Console.WriteLine(s1)
88Numeric Formatting
- The full syntax for the format string is
N,MFormatString, - where N is the parameter number, M is the field
width and justification, and FormatString
specifies how numeric data should be displayed. - Item Meaning
- C Display the number as currency, using the
local currency symbol and conventions. - D Display the number as a decimal integer.
- E Display the number by using exponential
(scientific) notation. - F Display the number as a fixed-point value.
- G Display the number as either fixed point or
integer, depending on which format is the most
compact. - N Display the number with embedded commas.
- X Display the number by using hexadecimal
notation
89Format Specifiers Example1
- using System
- public class FormatSpecApp
- public static void Main(string args)
- int i 123456
- Console.WriteLine("0C", i) // 123,456.00
currency - Console.WriteLine("0D", i) // 123456
decimal - Console.WriteLine("0E", i) // 1.234560E005
exponential - Console.WriteLine("0F", i) // 123456.00
float - Console.WriteLine("0G", i) // 123456 general
- Console.WriteLine("0N", i) // 123,456.00
number - Console.WriteLine("0P", i) // 12,345,600.00
percent - Console.WriteLine("0X", i) // 1E240
hexadeciaml -
90Format Specifier Example 2
- Console.WriteLine("Currency formatting - 0C
1C4", 88.8,888.8) - Console.WriteLine("Integer formatting - 0D5",
88) - Console.WriteLine("Exponential formatting -
0E", 888.8) - Console.WriteLine("Fixed-point formatting -
0F3",888.8888) - Console.WriteLine("General formatting - 0G",
888.8888) - Console.WriteLine("Number formatting - 0N",
8888888.8) - Console.WriteLine("Hexadecimal formatting -
0X4", 88)
91Format Specifiers
92Numeric String Parsing
- All the numeric types have a Parse method, which
takes the string representation of a number and
returns you its equivalent numeric value. -
- string t " -1,234,567.890 "
- //double g double.Parse(t) // Same thing
- double g double.Parse(t, NumberStyles.Any)
- Console.WriteLine("g 0F", g)
- The NumberStyles is in System.Globalization
93(No Transcript)
94Numeric String Parsing
- If you also want to accommodate a currency
symbol, you need the third Parse overload, which
takes a NumberFormatInfo object as a parameter - using System
- using System.Globalization
- public class FormatSpecApp
- public static void Main(string args)
- string u " -1,234,567.890 "
- NumberFormatInfo ni new NumberFormatInfo()
- ni.CurrencySymbol ""
- double h double.Parse(u, NumberStyles.Any,
ni) - Console.WriteLine("h 0F", h) // h
-1234567.89 -
-
95Strings and DateTime
- A DateTime object stores the date and time
using System public class DatesApp public
static void Main(string args) DateTime
dt DateTime.Now //now is property
Console.WriteLine(dt) Console.WriteLine("
date 0, time 1\n", dt.Date,
dt.TimeOfDay)
96Boxing and Unboxing
- When you change from value type ? reference type
there is a boxing operation, and when you change
from a reference type ? value type there is an
unboxing operation. - Example int f 42 // Value type.
- object b f // f is boxed to b.
- int x (int)b // Unboxed back to int.
- Note
- Can Unbox only previously boxed value types.
- Can not unbox reference types
97Example
- using System
- namespace box
- enum colorred,green
- struct student
- public int id // must be public in order
to accessable - public char gender
-
- class Program
- static void Main(string args)
- color c color.green
- int f 42 // Value type.
- student s
- s.id 11
- s.gender 'f'
-
98Example Continue
- object b f // f is boxed to b.
- object cc c
- object dd s
- Console.WriteLine(cc.ToString())
//green - cc b
- Console.WriteLine(cc.ToString())//42
- int x (int)b // Unboxed back to
int. - color co (color)cc
- Console.WriteLine(co.ToString())
//42 - student ss (student)dd //Unboxed
back to student - Console.WriteLine(ss.id) //11
- Console.WriteLine(ss.gender) //'f'
-
-
99Boxing and Unboxing
100Boxing and Unboxing
This Queue can then be used for reference types
and value types