Data Types and Expressions

Slides:



Advertisements
Similar presentations
Data Types and Expressions
Advertisements

C# Programming: From Problem Analysis to Program Design1 3 Data Types and Expressions C# Programming: From Problem Analysis to Program Design 2 nd Edition.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
C# Programming: From Problem Analysis to Program Design1 Data Types and Expressions C# Programming: From Problem Analysis to Program Design 3rd Edition.
JavaScript, Fourth Edition
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
JavaScript, Third Edition
String Escape Sequences
Basic Elements of C++ Chapter 2.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
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.
Chapter 2: Using Data.
CPS120: Introduction to Computer Science
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Chapter 2 Variables.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Microsoft Visual C#.NET: From Problem Analysis to Program Design1 Chapter 3 Data Types and Expressions Microsoft Visual C#.NET: From Problem Analysis to.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Data Types and Expressions
Chapter 2: Basic Elements of C++
Chapter 2 Variables.
Chapter Topics The Basics of a C++ Program Data Types
BASIC ELEMENTS OF A COMPUTER PROGRAM
Documentation Need to have documentation in all programs
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
ITEC113 Algorithms and Programming Techniques
Basic Elements of C++.
Multiple variables can be created in one declaration
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
C# Programming: From Problem Analysis to Program Design
IDENTIFIERS CSC 111.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Data Types and Expressions
Beginning C Lecture 2 Lecturer: Dr. Zhao Qinpei
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
C++ Data Types Data Type
Data Types and Expressions
Data Types and Expressions
Chapter 2: Introduction to C++.
Data Types and Expressions
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Primitive Types and Expressions
Chap 2. Identifiers, Keywords, and Types
Module 2 Variables, Data Types and Arithmetic
Chapter 2 Variables.
Data Types and Expressions
Presentation transcript:

Data Types and Expressions 2 C# Programming: From Problem Analysis to Program Design 4th Edition C# Programming: From Problem Analysis to Program Design

Chapter Objectives Examine how computers represent data Declare memory locations for data Explore the relationship between classes, objects, and types Use predefined data types Use integral data types C# Programming: From Problem Analysis to Program Design

Chapter Objectives (continued) Use floating-point types Learn about the decimal data type Declare Boolean variables Declare and manipulate strings Work with constants C# Programming: From Problem Analysis to Program Design

Chapter Objectives (continued) Write assignment statements using arithmetic operators Learn about the order of operations Learn special formatting rules for currency Work through a programming example that illustrates the chapter’s concepts C# Programming: From Problem Analysis to Program Design

Data Representation Bits Bytes Bit – "Binary digIT" Binary digit can hold 0 or 1 1 and 0 correspond to on and off, respectively Bytes Combination of 8 bits Represent one character, such as the letter A To represent data, computers use the base-2 number system, or binary number system 0/1 1 2 3 4 5 6 7 C# Programming: From Problem Analysis to Program Design

Bits and Bytes Nibble - 4 bits (half a byte) Byte - 8 bits A group of 8 bits is called a byte. Other groupings include: Nibble - 4 bits (half a byte) Byte - 8 bits Kilobyte (KB) - 1024 bytes (or 1024 x 8 bits) Megabyte (MB) - 1024 kilobytes (or 1048576 bytes) Gigabyte (GB) - 1024 megabytes Terabyte (TB) - 1024 gigabytes Most computers can process millions of bits every second. A hard drive's storage capacity is measured in gigabytes or terabytes. RAM is often measured in megabytes or gigabytes.

Decimal Number System Figure 2-1 Base-10 positional notation of 1326

Decimal Number System 6 5 4 3 2 1 106 105 104 103 102 101 100 1M 100K 10K 1000 10 200,000 + 3000 + 400 + 60 + 5 = 203,465 Figure 2-1 Base-10 positional notation of 203,465

Data Representation (continued) Table 2-1 Binary equivalent of selected decimal values C# Programming: From Problem Analysis to Program Design

Binary Number System (continued) Figure 2-2 Decimal equivalent of 01101001

Binary Number System 27 26 25 24 23 22 21 20 7 6 5 4 3 2 1 32 + 4 = 36 27 26 25 24 23 22 21 20 128 64 32 16 8 32 + 4 = 36 Figure 2-1 Base-10 positional notation of 36

Binary Number System 7 6 5 4 3 2 1 27 26 25 24 23 22 21 20 128 64 32 16 8 128 + 16 + 4 + 2 + 1 = 161 Figure 2-1 Base-10 positional notation of 161

Data Representation (continued) Character sets With only 8 bits, can represent 28, or 256, different decimal values ranging from 0 to 255; this is 256 different characters Unicode – character set used by C#.NET Uses 16 bits to represent characters 216, or 65,536 unique characters, can be represented Example: Euro '€' is '\u20AC' Visit http://unicode.org /charts American Standard Code for Information Interchange (ASCII) – subset of Unicode First 128 characters are the same

Data Representation (continued) ASCII Table

Data Representation (continued) List of Unicode characters From Wikipedia, the free encyclopedia "This article contains special characters. Without proper rendering support, you may see question marks, boxes, or other symbols. This is a list of Unicode characters. As of version 10.0, Unicode contains a repertoire of over 136,000 characters covering 139 modern and historic scripts, as well as multiple symbol sets. As it is not technically possible to list all of these characters in a single Wikipedia page …" Link: https://en.wikipedia.org/wiki/List_of_Unicode_characters

Data Representation (continued) List of Unicode characters Link: https://en.wikipedia.org/wiki/List_of_Unicode_characters Console.WriteLine('\u00D1');

Data Representation (continued) Table 2-2 Common abbreviations for data representations

Memory Locations for Data Identifier Name (camel notation) Rules for creating an identifier Combination of alphabetic characters (a-z and A-Z), numeric digits (0-9), and the underscore First character in the name may not be numeric No embedded spaces – concatenate (append) words together Keywords cannot be used Use the case of the character to your advantage Be descriptive with meaningful names Examples: customerName, productCode, addressLine1, savingAccountBalance

Reserved Words in C# Table 2-3 C# keywords & reserved words

Contextual Keywords Table 2-4 C# contextual keywords Never use these words as variable names – It is a very bad idea!!!

Naming Conventions Pascal case Camel case First letter of each word capitalized Class, method, namespace, and properties identifiers Eg: FirstName, LastName Camel case Hungarian notation First letter of identifier lowercase; first letter of subsequent concatenated words capitalized Variables and objects Eg: firstName, lastName, savingAccountBalance

Examples of Valid Names (Identifiers) Table 2-5 Valid identifiers

Examples of Invalid Names (Identifiers) Table 2-6 Invalid identifier

Variables Area in computer memory where a value of a particular data type can be stored Declare a variable Allocate memory Syntax type identifier; Compile-time initialization Initialize a variable when it is declared type identifier = expression;

Types, Classes, and Objects C# has more than one type of number int type is a whole number Floating-point types can have a fractional portion Types are actually implemented through classes One-to-one correspondence between a class and a type Simple data type such as int, string, … implemented as classes C# Programming: From Problem Analysis to Program Design

Type, Class, and Object Examples Table 2-7 Sample data types C# Programming: From Problem Analysis to Program Design

Predefined Data Types Common Type System (CTS) Divided into two major categories Figure 2-3 .NET common types

Value and Reference Types Figure 2-4 Memory representation for value and reference types

Value Types Fundamental or primitive data types Figure 2-5 Value type hierarchy

Value Types Figure 2-5 Type Examples Integral: 123 Floating point: 1.57e+3 (same as 1570) Decimal: 1.23 Boolean true / false Struct class Person…{name, age, sex…} Enumerated enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; Figure 2-5 Type Examples

Value Types (continued) Table 2-8 C# value data types with .NET alias

Integral Data Types Includes number of types Primary difference How much storage is needed Whether a negative value can be stored Includes number of types byte & sbyte char int & uint long & ulong short & ushort

Data Types Table 2-9 Values and sizes for integral types

Examples of Integral Variable Declarations int studentCount; // number of students in the class int ageOfStudent = 20; // age-originally initialized to 20 int numberOfExams; // number of exams int coursesEnrolled; // number of courses enrolled

Table 2-10 Values and sizes for floating-point types May be in scientific notation with an exponent Format is: n.ne±P 3.2e+5 is equivalent to 320,000 1.76e-3 is equivalent to .00176 OR in standard decimal notation Default type is double Table 2-10 Values and sizes for floating-point types

Examples of Floating-Point Declarations double extraPerson = 3.50; // extraPerson originally set // to 3.50 double averageScore = 70.0; // averageScore originally set // to 70.0 double priceOfTicket; // cost of a movie ticket double gradePointAverage; // grade point average float totalAmount = 23.57f; // note the f must be placed after // the value for float types

Table 2-11 Value and size for decimal data type Decimal Types Monetary data items As with the float, must attach the suffix ‘m’ or ‘M’ onto the end of a number to indicate decimal Float attach ‘f’ or ‘F’ Table 2-11 Value and size for decimal data type Examples decimal endowmentAmount = 33897698.26M; decimal deficit;

Boolean Variables Based on true/false, on/off logic Boolean type in C# → bool Does not accept integer values such as 0, 1, or -1 Default value is: false bool undergraduateStudent; bool moreData = true;

Strings Reference type Represents a string of Unicode characters string studentName; string courseName = "Programming I"; string twoLines = "Line1\nLine2";

Making Data Constant Add the keyword const to a declaration Value cannot be changed ALLCAPS standard naming convention Syntax: const type identifier = expression; const double TAX_RATE = 0.0675; const int SPEED = 70; const char HIGHEST_GRADE = 'A';

Assignment Statements Used to change the value of the variable Assignment operator ( = ) Syntax variable = expression; Expression can be: Another variable Compatible literal value Mathematical equation Call to a method that returns a compatible value Combination of one or more items in this list

Examples of Assignment Statements int numberOfMinutes, count, minIntValue; numberOfMinutes = 45; count = 0; minIntValue = -2147483648; count = count + 1; numberOfMinutes = 10 + Delay(clerkId);

Examples of Assignment Statements char firstInitial, yearInSchool, punctuation, enterKey, lastChar; firstInitial = 'B'; yearInSchool = '1'; punctuation = ';'; enterKey = '\n'; // newline escape character lastChar = '\u005A'; // Unicode character 'Z' euroSymbol= '\u20AC'; // Unicode character '€'

Examples of Assignment Statements (continued) double accountBalance, weight; bool isFinished; accountBalance = 4783.68; weight = 1.7E-3; //scientific notation may be used isFinished = false; //declared previously as a bool //Notice – no quotes used

Examples of Assignment Statements (continued) decimal amountOwed, deficitValue; amountOwed = 3000.50m; // m or M must be suffixed to // decimal data types deficitValue = -322888672.50M;

Examples of Assignment Statements (continued) string aSaying, fileLocation; aSaying = "First day of the rest of your life!\n"; fileLocation = @ "C:\textFiles\newChapter2"; @ placed before a string literal signals that the characters inside the double quotation marks should be interpreted verbatim --- No need to use escape characters with @

Examples of Assignment Statements (continued) Figure 2-7 Impact of assignment statement

Arithmetic Operations Simplest form of an assignment statement resultVariable = operand1 operator operand2; Readability Space before and after every operator Table 2-12 Basic arithmetic operators

Basic Arithmetic Operations Figure 2-8 Result of 67 % 3 Modulus operator with negative values Sign of the dividend determines the result -3 % 5 = -3; 5 % -3 = 2; -5 % -3 = -3;

Basic Arithmetic Operations (continued) Plus (+) with string Identifiers Concatenates operand2 onto end of operand1 string result; string fullName; string firstName = "Daenerys"; string lastName = "Targaryen"; fullName = firstName + " " + lastName; //now fullName is "Daenerys Targaryen"

Concatenation Figure 2-9 String concatenation

Basic Arithmetic Operations (continued) Increment and Decrement Operations Unary operator num++; // num = num + 1; --value1; // value = value – 1; Preincrement/predecrement versus post int num = 100; Console.WriteLine(num++); // Displays 100 Console.WriteLine(num); // Displays 101 Console.WriteLine(++num); // Displays 102

Basic Arithmetic Operations (continued) Figure 2-10 Declaration of value type variables

Basic Arithmetic Operations (continued) Figure 2-11 Change in memory after count++; statement executed

Basic Arithmetic Operations (continued) int num = 100; Console.WriteLine(num++); //prints 100 Console.WriteLine(num); //prints 101 Console.WriteLine(++num); //prints 102 C# Programming: From Problem Analysis to Program Design

Basic Arithmetic Operations (continued) Figure 2-12 Results after statement is executed

Compound Operations Accumulation Variable on left side of equal symbol is used once the entire expression on right is evaluated

Basic Arithmetic Operations (continued) Order of operations Order in which the calculations are performed Example answer = 100; answer += 50 * 3 / 25 – 4; 50 * 3 = 150 150 / 25 = 6 6 – 4 = 2 100 + 2 = 102

Order of Operations Associativity of operators Left Right Table 2-14 Operator precedence Associativity of operators Left Right NOTE. When an operator has right associativity, its expression is evaluated from right to left. For example, the assignment operator is right-associative. Therefore, the expression to its right  is evaluated before the assignment operation is invoked. 

Order of Operations (continued) Figure 2-13 Order of execution of the operators

Mixed Expressions Implicit type coercion Changes int data type into a double No implicit conversion from double to int double answer; answer = 10 / 3; // Does not produce 3.3333333 double answer2; answer2 = 10.0 / 3; // produces 3.3333333 int value1 = 440, anotherNumber = 70; double value2 = 100.60; value2 = value1; // ok, 440.0 stored in value2

Figure 2-14 Syntax error generated for assigning a double to an int Mixed Expressions int value1 = 440; double value2 = 100.60; value1 = value2; // syntax error as shown in Figure 2-14 Figure 2-14 Syntax error generated for assigning a double to an int

Mixed Expressions (continued) Explicit type coercion Cast (type) expression examAverage = (exam1 + exam2 + exam3) / (double) count; int value1 = 0, anotherNumber = 75; double value2 = 100.99, anotherDouble = 100; value1 = (int) value2; // value1 = 100 value2 = (double) anotherNumber; // value2 = 75.0

Mixed Expressions (continued) Explicit Conversion ( Using the Convert class ) int v1 = Convert.ToInt32(1.999); // v1 is 1 long v2 = Convert.ToInt64("5.7777"); // v2 is 5.7777 string v3 = Convert.ToString(1.999); // v3 is "1.999" char v4 = Convert.ToChar(65); // v4 is 'A'

Formatting Output You can format data by adding dollar signs, percent symbols, and/or commas to separate digits You can suppress leading zeros You can pad a value with special characters Place characters to the left or right of the significant digits Use format specifiers

Formatting Output (continued) Table 2-15 Examples using format specifiers

Numeric Format Specifiers Table 2-16 Standard numeric format specifiers

Numeric Format Specifiers (continued) Table 2-16 Standard numeric format specifiers (continued)

Custom Numeric Format Specifiers Table 2-17 Custom numeric format specifiers

Custom Numeric Format Specifiers (continued)

Width Specifier Useful when you want to control the alignment of items on multiple lines Alignment component goes after the index ordinal followed by a comma (before the colon) If alignment number is less than actual size, it is ignored If alignment number is greater, pads with white space Negative alignment component places spaces on right Console.WriteLine("{0,10:F0}{1,8:C}", 9, 14); 9 $14.00 //Right justified values ------------------ 123456789012345678

Interpolated Strings (New in C# 6) The $ special character identifies a string literal as an interpolated string. An interpolated string looks like a template string that contains expressions to be replaced by the string representations of their results. This style offers a readable and convenient way to create formatted strings. string name = "Diana Prince"; DateTime date = DateTime.Now; // Composite formatting: Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date); // String interpolation: Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's " + $"{date:HH:mm} now."); // in both cases the output is // Hello, Diana Prince! Today is Sunday, it's 15:20 now.

Programming Example – CarpetCalculator Figure 2-15 Problem specification sheet for the CarpetCalculator example

Data Needs for the CarpetCalculator Table 2-18 Variables

Nonchanging Definitions for the CarpetCalculator Side Note: 1 yard = 3 feet 1 sqy = 9 sqf Table 2-19 Constants

CarpetCalculator Example Figure 2-16 Prototype for the CarpetCalculator example

Algorithm for CarpetCalculator Example Figure 2-17 CarpetCalculator flowchart

Algorithm for the CarpetCalculator Example (continued) Figure 2-18 Structured English for the CarpetCalculator example

CarpetCalculator Example (continued) Figure 2-19 Class diagram for the CarpetCalculator example

CarpetCalculator Example (continued) Figure 2-20 Revised class diagram without methods

/* CarpetCalculator.cs Author: Doyle */ using System; namespace CarpetExample { class CarpetCalculator static void Main( ) const int SQ_FT_PER_SQ_YARD = 9; const int INCHES_PER_FOOT = 12; const string BEST_CARPET = "Berber"; const string ECONOMY_CARPET = "Pile"; int roomLengthFeet = 12, roomLengthInches = 2, roomWidthFeet = 14, roomWidthInches = 7; double roomLength, roomWidth, carpetPrice, numOfSquareFeet, numOfSquareYards, totalCost;

roomLength = roomLengthFeet + (double) roomLengthInches / INCHES_PER_FOOT; roomWidth = roomWidthFeet + (double) roomWidthInches / INCHES_PER_FOOT; numOfSquareFeet = roomLength * roomWidth; numOfSquareYards = numOfSquareFeet / SQ_FT_PER_SQ_YARD; carpetPrice = 27.95; //per square yard totalCost = numOfSquareYards * carpetPrice; Console.WriteLine("The cost of " + BEST_CARPET + " is {0:C}", totalCost); Console.WriteLine( ); carpetPrice = 15.95; //per square yard Console.WriteLine("The cost of " + ECONOMY_CARPET + " is " + "{0:C}", totalCost); Console.Read(); }

Coding Standards Naming conventions Spacing conventions Identifiers Spacing conventions Declaration conventions C# Programming: From Problem Analysis to Program Design

Resources Naming Guidelines for .NET – http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx Writing Readable Code – http://software.ac.uk/resources/guides/writing-readable-source-code#node-131 C# Video tutorials – http://www.programmingvideotutorials.com/csharp/csharp-introduction Visual Studio 2012 – C# – http://msdn.microsoft.com/en-us/library/kx37x36(V=VS.110).aspx

Chapter Summary Memory representation of data Bits versus bytes Number system Binary number system Character sets Unicode C# Programming: From Problem Analysis to Program Design

Chapter Summary (continued) Memory locations for data Relationship between classes, objects, and types Predefined data types Integral data types Floating-point types Decimal type Boolean variables Strings C# Programming: From Problem Analysis to Program Design

Chapter Summary (continued) Constants Assignment statements Order of operations Formatting output C# Programming: From Problem Analysis to Program Design

Appendix 1 Formatting Numbers using System; using System.Globalization; using System.Resources; using System.Threading; class Sample { public static void Main() Console.WriteLine(String.Format("{0:0.00}", 123.4567)); // 123.46 Console.WriteLine(String.Format("{0:0.00}", 1.2)); // 1.20 Console.WriteLine(String.Format("{0:0.00}", 0.1)); // 0.10 Console.WriteLine(String.Format("{0:0.00}", 123.0)); // 123.00 Console.WriteLine(String.Format("{0:0.00}", 123)); // 123.00 Console.WriteLine(String.Format("{0:00.0}", 123.4567) ); // 123.5 Console.WriteLine(String.Format("{0:00.0}", 1.99) ); // 02.0 Console.WriteLine(String.Format("{0:0,0.0}", 12345.67)); // 12,345.7 Console.WriteLine(String.Format("{0:#.00}", 0.1) ); // .10 Console.WriteLine(String.Format("{0,10:0.0}", 123.4567)); // _____123.5 Console.WriteLine(String.Format("{0,-10:0.0}", 123.4567)); // 123.5____ Console.WriteLine(String.Format("Balance is ${0,-10:0.0}USD", 123.4567)); // Balance is $123.5____USD Console.WriteLine(String.Format("{0:Balance is $0.0 USD}", 123.4567)); // Balance is $123.5____USD Console.WriteLine(String.Format("{0:00000}", 123) ); // 00123 Console.WriteLine(String.Format("{0,5}", 123) ); // __123 Console.WriteLine(String.Format("{0,-5}", 123)); // 123__ Console.WriteLine(String.Format("{0:(###) ###-####}", 2165551234)); // (216) 555-1234 Console.WriteLine(String.Format("{0:(000) 000-0000}", 2165551234)); // (216) 555-1234 double decNum = 1.23; string strUSA = decNum.ToString(CultureInfo.InvariantCulture.NumberFormat); // "1.23" string strEurope = decNum.ToString(CultureInfo.GetCultureInfo("es-ES").NumberFormat); // "1,23" Console.WriteLine(strUSA ); // "1.23" Console.WriteLine(strEurope ); // "1,23" Console.ReadKey(); }

Appendix 2 Formatting Dates using System; using System.Globalization; using System.Resources; using System.Threading; class DemoFormatDates { public static void Main() //using other Culture values. See Link: // https://msdn.microsoft.com/en-US/library/Ee825488(v=CS.20).aspx //Thread.CurrentThread.CurrentCulture = new CultureInfo("es-VE"); //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-UK"); //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); //Thread.CurrentThread.CurrentCulture = new CultureInfo("el-GR"); CultureInfo ci = Thread.CurrentThread.CurrentCulture; Console.WriteLine(ci); // en-US DateTime dt = DateTime.Now; Console.WriteLine(dt); // 8 / 8 / 2015 4:39:58 PM Console.WriteLine(String.Format("{0:y yy yyy yyyy}", dt)); // 15 15 2015 2015 Console.WriteLine(String.Format("{0:M MM MMM MMMM}", dt)); // 8 08 Aug August Console.WriteLine(String.Format("{0:d dd ddd dddd}", dt)); // 8 08 Sat Saturday Console.WriteLine(String.Format("{0:h hh H HH}", dt)); // 4 04 16 16 hour 12/24 Console.WriteLine(String.Format("{0:m mm}", dt)); // 39 39 minutes Console.WriteLine(String.Format("{0:s ss}", dt)); // 58 58 seconds Console.WriteLine(String.Format("{0:t tt}", dt)); // P PM A.M. or P.M. Console.WriteLine(String.Format("{0:z zz zzz}", dt)); // -4 -04 -04:00 time zone Console.ReadKey(); } C# Programming: From Problem Analysis to Program Design

Appendix 3 Formatting Dates using System; using System.Globalization; using System.Resources; using System.Threading; class Sample { public static void Main() DateTime dt = DateTime.Now; Console.WriteLine(dt); // 8 / 8 / 2015 10:22:15 PM Console.WriteLine(String.Format("{0:t}", dt)); // 10:22 PM ShortTime Console.WriteLine(String.Format("{0:T}", dt)); // 10:22:15 PM LongTime Console.WriteLine(String.Format("{0:d}", dt)); // 8 / 8 / 2015 ShortDate Console.WriteLine(String.Format("{0:D}", dt)); // Saturday, August 08, 2015 LongDate Console.WriteLine(String.Format("{0:F}", dt)); // Saturday, August 08, 2015 10:22:15 PM FullDateTime Console.WriteLine(String.Format("{0:r}", dt)); // Sat, 08 Aug 2015 22:22:15 GMT RFC1123 Console.WriteLine(String.Format("{0:u}", dt)); // 2015 - 08 - 08 22:22:15Z UniversalSortableDate Console.ReadKey(); } C# Programming: From Problem Analysis to Program Design

Appendix 4 Formatting Tables using System; using System.Globalization; using System.Resources; using System.Threading; class Sample { public static void Main() Console.WriteLine("First Name| Last Name | Age "); Console.WriteLine("----------+===============+-----"); Console.WriteLine(String.Format("{0,-10}|{1,-15}|{2,5}", "Daenerys", "Targaryen", 19)); Console.WriteLine(String.Format("{0,-10}|{1,-15}|{2,5}", "Drogon", "", 3)); Console.WriteLine(String.Format("{0,-10}|{1,-15}|{2,5}", "Maester", "Aemon", 102)); Console.ReadKey(); }