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
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
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,
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
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.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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
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
Topics Designing a Program Input, Processing, and Output
Computer Programming BCT 1113
BASIC ELEMENTS OF A COMPUTER PROGRAM
Basic Elements of C++.
Data Types, Identifiers, and Expressions
Java Programming: From Problem Analysis to Program Design, 4e
Data Types and Expressions
Chapter 2: Introduction to C++
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.
2.1 Parts of a C++ Program.
Chapter 2 Edited by JJ Shepherd
Data Types and Expressions
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
C++ Data Types Data Type
Chapter 2: Java Fundamentals
Data Types and Expressions
Chapter 2: Introduction to C++.
Topics Designing a Program Input, Processing, and Output
Data Types and Expressions
Topics Designing a Program Input, Processing, and Output
An Introduction to Programming with C++ Fifth Edition
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 3 C# Programming: From Problem Analysis to Program Design 2nd Edition C# Programming: From Problem Analysis to Program Design

Chapter Objectives Declare memory locations for data Explore the relationship between classes, objects, and types Use predefined data types Use integral data types Use floating-point types Learn about the decimal data type Declare Boolean variables C# Programming: From Problem Analysis to Program Design

Chapter Objectives (continued) Declare and manipulate strings Work with constants 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

Memory Locations for Data Identifier Name 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 C# Programming: From Problem Analysis to Program Design

Reserved Words in C# C# Programming: From Problem Analysis to Program Design

Reserved Words in C# (continued) Contextual keywords New with C# 2.0 standards – November 2005 As powerful as regular keywords Contextual keywords have special meaning only when used in a specific context; other times they can be used as identifiers C# Programming: From Problem Analysis to Program Design

Naming Conventions Pascal case Camel case First letter of each word capitalized Class, method, namespace, and properties identifiers Camel case Hungarian notation First letter of identifier lowercase; first letter of subsequent concatenated words capitalized Variables and objects C# Programming: From Problem Analysis to Program Design

Naming Conventions (continued) Uppercase Every character is uppercase Constant literals and for identifiers that consist of two or fewer letters C# Programming: From Problem Analysis to Program Design

Examples of Valid Names (Identifiers) C# Programming: From Problem Analysis to Program Design

Examples of Invalid Names (Identifiers) C# Programming: From Problem Analysis to Program Design

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; C# Programming: From Problem Analysis to Program Design

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, implemented as a class C# Programming: From Problem Analysis to Program Design

Types, Classes, and Objects Instance of a class → object A class includes more than just data Encapsulation → packaging of data and behaviors into a single or unit→class C# Programming: From Problem Analysis to Program Design

Type, Class, and Object Examples C# Programming: From Problem Analysis to Program Design

Predefined Data Types Common Type System (CTS) Divided into two major categories Figure 3-1 .NET common types C# Programming: From Problem Analysis to Program Design

Value and Reference Types Figure 3-2 Memory representation for value and reference types C# Programming: From Problem Analysis to Program Design

Value Types Fundamental or primitive data types Figure 3-3 Value type hierarchy C# Programming: From Problem Analysis to Program Design

Value Types (continued) C# Programming: From Problem Analysis to Program Design

Integral Data Types Primary difference How much storage is needed Whether a negative value can be stored C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

Floating-point Types May be in scientific notation with an exponent 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 C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

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’ Examples decimal endowmentAmount = 33897698.26M; decimal deficit; C# Programming: From Problem Analysis to Program Design

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 bool undergraduateStudent; bool moreData = true; C# Programming: From Problem Analysis to Program Design

Strings Reference type Represents a string of Unicode characters string studentName; string courseName = “Programming I”; string twoLines = “Line1\nLine2”; C# Programming: From Problem Analysis to Program Design

Making Data Constant Add the keyword const to a declaration Value cannot be changed Standard naming convention Syntax const type identifier = expression; const double TAX_RATE = 0.0675; const int SPEED = 70; const char HIGHEST_GRADE = ‘A’; C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

Examples of Assignment Statements int numberOfMinutes, count, minIntValue; char firstInitial, yearInSchool, punctuation; numberOfMinutes = 45; count = 0; minIntValue = -2147483648; firstInitial = ‘B’; yearInSchool = ‘1’; enterKey = ‘\n’; // newline escape character C# Programming: From Problem Analysis to Program Design

Examples of Assignment Statements (continued) double accountBalance, weight; decimal amountOwed, deficitValue; bool isFinished; accountBalance = 4783.68; weight = 1.7E-3; //scientific notation may be used amountOwed = 3000.50m; // m or M must be suffixed to // decimal deficitValue = -322888672.50M; C# Programming: From Problem Analysis to Program Design

Examples of Assignment Statements (continued) int count = 0, newValue = 25; string aSaying, fileLocation; aSaying = “First day of the rest of your life!\n "; fileLocation = @”C:\CSharpProjects\Chapter2”; isFinished = false; // declared previously as a bool count = newValue; @ placed before a string literal signals that the characters inside the double quotation marks should be interpreted verbatim C# Programming: From Problem Analysis to Program Design

Examples of Assignment Statements (continued) Figure 3-5 Impact of assignment statement C# Programming: From Problem Analysis to Program Design

Arithmetic Operations Simplest form of an assignment statement resultVariable = operand1 operator operand2; Readability Space before and after every operator C# Programming: From Problem Analysis to Program Design

Basic Arithmetic Operations Figure 3-6 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; C# Programming: From Problem Analysis to Program Design

Basic Arithmetic Operations (continued) Plus (+) with string Identifiers Concatenates operand2 onto end of operand1 string result; string fullName; string firstName = “Rochelle”; string lastName = “Howard”; fullName = firstName + “ “ + lastName; C# Programming: From Problem Analysis to Program Design

Concatenation Figure 3-7 String concatenation C# Programming: From Problem Analysis to Program Design

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; System.Console.WriteLine(num++); // Displays 100 System.Console.WriteLine(num); // Display 101 System.Console.WriteLine(++num); // Displays 102 C# Programming: From Problem Analysis to Program Design

Basic Arithmetic Operations (continued) int num = 100; System.Console.WriteLine(x++ + “ “ + ++x); // Displays 100 102 Figure 3-9 Change in memory after count++; statement executed C# Programming: From Problem Analysis to Program Design

Basic Arithmetic Operations (continued) Figure 3-10 Results after statement is executed C# Programming: From Problem Analysis to Program Design

Compound Operations Accumulation += C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

Order of Operations Associativity of operators Left Right C# Programming: From Problem Analysis to Program Design

Order of Operations (continued) Figure 3-11 Order of execution of the operators C# Programming: From Problem Analysis to Program Design

Mixed Expressions Implicit type coercion Changes int data type into a double No implicit conversion from double to int Figure 3-12 Syntax error generated for assigning a double to an int C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

Numeric Format Specifiers C# Programming: From Problem Analysis to Program Design

Numeric Format Specifiers (continued) C# Programming: From Problem Analysis to Program Design

Custom Numeric Format Specifiers C# Programming: From Problem Analysis to Program Design

Custom Numeric Format Specifiers (continued) C# Programming: From Problem Analysis to Program Design

Formatting Output C# Programming: From Problem Analysis to Program Design

Programming Example – CarpetCalculator Figure 3-13 Problem specification sheet for the CarpetCalculator example C# Programming: From Problem Analysis to Program Design

Data Needs for the CarpetCalculator C# Programming: From Problem Analysis to Program Design

Non-changing Definitions for the CarpetCalculator C# Programming: From Problem Analysis to Program Design

CarpetCalculator Example Figure 3-14 Prototype for the CarpetCalculator example C# Programming: From Problem Analysis to Program Design

Algorithm for CarpetCalculator Example Figure 3-15 CarpetCalculator flowchart C# Programming: From Problem Analysis to Program Design

Algorithm for the CarpetCalculator Example (continued) Figure 3-16 Structured English for the CarpetCalculator example C# Programming: From Problem Analysis to Program Design

CarpetCalculator Example (continued) Figure 3-17 Class diagram for the CarpetCalculator example C# Programming: From Problem Analysis to Program Design

/* 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; C# Programming: From Problem Analysis to Program Design

roomLengthInches / INCHES_PER_FOOT; roomWidthInches / INCHES_PER_FOOT; roomLength = roomLengthFeet + roomLengthInches / INCHES_PER_FOOT; roomWidth = roomWidthFeet + roomWidthInches / INCHES_PER_FOOT; numOfSquareFeet = roomLength * roomWidth; numOfSquareYards = numOfSquareFeet / SQ_FT_PER_SQ_YARD; carpetPrice = 27.95; totalCost = numOfSquareYards * carpetPrice; Console.Out.WriteLine("The cost of " + BEST_CARPET + " is {0:C}", totalCost); Console.Out.WriteLine( ); carpetPrice = 15.95; Console.Out.WriteLine("The cost of " + ECONOMY_CARPET + " is " + "{0:C}", totalCost); Console.Read(); } } } C# Programming: From Problem Analysis to Program Design

CarpetCalculator Example (continued) Figure 3-18 Output from the CarpetCalculator program C# Programming: From Problem Analysis to Program Design

Chapter Summary 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