Fundamental Data Types

Slides:



Advertisements
Similar presentations
1/1/ / faculty of Electrical Engineering eindhoven university of technology Introduction Part 2: Data types and addressing modes dr.ir. A.C. Verschueren.
Advertisements

Software Engineering Fundamental data types. Guidelines - numbers Avoid “magic numbers” (hard- coded values that are not self- explanatory): Changes can.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
22-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Arithmetic Expressions Addition (+) Subtraction (-) Multiplication (*) Division (/) –Integer –Real Number Mod Operator (%) Same as regular Depends on the.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
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.
Lecture 4: Digital Systems & Binary Numbers (4)
Secure Coding Rules for C++ Copyright © 2016 Curt Hill
Expressions and Assignment Statements
Expressions and Assignment Statements
Chapter 2 Variables.
Lec 3: Data Representation
Expressions.
Type Checking Generalizes the concept of operands and operators to include subprograms and assignments Type checking is the activity of ensuring that the.
Expressions.
Expressions and Assignment Statements
Chap. 2. Types, Operators, and Expressions
Chapter 4 – Fundamental Data Types
ECE Application Programming
More important details More fun Part 3
Tokens in C Keywords Identifiers Constants
Multiple variables can be created in one declaration
Primitive Data, Variables, Loops (Maybe)
Modified from Sharon Guffy
Expressions and Assignment Statements
Chapter 6 Floating Point
Type Conversion, Constants, and the String Object
Secure Coding Rules for C++ Copyright © Curt Hill
Data Structures Mohammed Thajeel To the second year students
Java Programming: From Problem Analysis to Program Design, 4e
Expressions and Assignment Statements
Unit 2 Programming.
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.
Expressions Chapter 4 Copyright © 2008 W. W. Norton & Company.
Expressions and Assignment Statements
Fundamentals of Programming I Number Systems
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Chapter-3 Operators.
Lectures on Numerical Methods
Coding Concepts (Data- Types)
Program Breakdown, Variables, Types, Control Flow, and Input/Output
Building Java Programs
Data Types and Expressions
Summary of what we learned yesterday
Introduction to Primitives
Introduction to Primitives
Unit 3: Variables in Java
Module 2 Variables, Data Types and Arithmetic
Chapter 2 Variables.
OPERATORS in C Programming
Operator King Saud University
Assistant Professor Rabia Koser Dept. of Computer Applications
Expressions and Assignment Statements
The IF Revisited A few more things Copyright © Curt Hill.
Programming Fundamental-1
19. General Control Issues
OPERATORS in C Programming
Presentation transcript:

Fundamental Data Types CSC-3004 Introduction to Software Development Spring 2013 Dr. James Skon

Numbers in General Avoid "magic numbers" Magic numbers are literal numbers, such as 100 or 47524, that appear in the middle of a program without explanation If you program in a language that supports named constants, use them instead. If you can't use named constants, use global variables when it's feasible to do so.

Numbers in General Avoiding magic numbers yields three advantages: Changes can be made more reliably. Must change all “100”s to “200”s that deal with some aspect. But which? Changes can be made more easily. Change once! Your code is more readable. for i = 0 to 99 do ... for i = 0 to MAX_ENTRIES-1 do ...

Numbers in General for i = 0 to CONSTANT do ... total = total + 1 Use hard-coded 0s and 1s if you need to. The values 0 and 1 are used to increment, decrement, and start loops at the first element of an array. for i = 0 to CONSTANT do ... total = total + 1

Anticipate divide-by-zero errors Each time you use the division symbol (/ in most languages), think about whether it's possible for the denominator of the expression to be 0. If the possibility exists, write code to prevent a divide-by-zero error.

Make type conversions obvious Make type conversions obviousMake sure that someone reading your code will be aware of it when a conversion between different data types occurs. In C++ you could say: y = x + (float) i

Avoid mixed-type comparisons If x is a floating-point number and i is an integer, the test if ( i = x ) then … is almost guaranteed not to work. By the time the compiler figures out which type it wants to use for the comparison, converts one of the types to the other, does a bunch of rounding, and determines the answer, you'll be lucky if your program runs at all.

Integers Check for integer division Consider: When you're using integers, 7/10 does not equal 0.7. It usually equals 0, or minus infinity, or the nearest integer … What it equals varies from language to language Consider: 10 * (7/10) = (10*7) / 10 = 7

Check for integer overflow Integer Type Range Signed 8-bit −128 through 127 Unsigned 8-bit 0 through 255 Signed 16-bit −32,768 through 32,767 Unsigned 16-bit 0 through 65,535 Signed 32-bit −2,147,483,648 through 2,147,483,647 Unsigned 32-bit 0 through 4,294,967,295 Signed 64-bit −9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 Unsigned 64-bit 0 through 18,446,744,073,709,551,615 Ranges for Different Types of Integers

Check for integer overflow The easiest way to prevent integer overflow is to think through each of the terms in your arithmetic expression and try to imagine the largest value each can assume

Check for overflow in intermediate results The number at the end of the equation isn't the only number you have to worry about Consider: int termA = 1000000; int termB = 1000000; int product = termA * termB / 1000000; System.out.println( "( " + termA + " * " + termB + " ) / 1000000 = " + product ); Output: ( 1000000 * 1000000 ) / 1000000 = -727 WHY?

Floating-Point Numbers floating-point numbers can't represent many fractional decimal numbers accurately a 32-bit floating-point representation of 1/3 equals 0.33333330

Floating-Point Numbers Avoid additions and subtractions on numbers that have greatly different magnitudes With a 32-bit floating-point variable, 1,000,000.00 + 0.1 = 1,000,000.00 Why? because 32 bits don't give you enough significant digits to encompass the range between 1,000,000 and 0.1. Likewise, 5,000,000.02 - 5,000,000.01 = 0.0.

Floating-Point Numbers 1 is equal to 2 for sufficiently large values of 1. —Anonymous

Floating-Point Numbers Avoid equality comparisons Floating-point numbers that should be equal are not always equal. The main problem is that two different paths to the same number don't always lead to the same number. For example, 0.1 added 10 times rarely equals 1.0

Floating-Point Numbers Values of I: 0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999 double nominal = 1.0; double sum = 0.0; for ( int i = 0; i < 10; i++ ) { sum += 0.1; } if ( nominal == sum ) { System.out.println( "Numbers are the same." ); } else { System.out.println( "Numbers are different." ); The variable nominal is a 64-bit real sum is 10*0.1. It should be 1.0.l Here's the bad comparison

Floating-Point Numbers final double ACCEPTABLE_DELTA = 0.00001; boolean Equals( double Term1, double Term2 ) { if ( Math.abs( Term1 - Term2 ) < ACCEPTABLE_DELTA ) { return true; } else { return false;

Characters and Strings Avoid magic characters and strings Fo r commonly occurring strings use a constant, or Place in string resources file. This allows for translation to other languages Takes up less memory Good names make more sense

Boolean Variables Use boolean variables to document your program Instead of merely testing a boolean expression, you can assign the expression to a variable that makes the implication of the test unmistakable if ( ( elementIndex < 0 ) || ( MAX_ELEMENTS < elementIndex ) || ( elementIndex == lastElementIndex ) ) { ... }

Boolean Variables Improved Test: finished = ( ( elementIndex < 0 ) || ( MAX_ELEMENTS < elementIndex ) ); repeatedEntry = ( elementIndex == lastElementIndex ); if ( finished || repeatedEntry ) { ... }

Boolean Variables Consider If ( ( document.AtEndOfStream() ) And ( Not inputError ) ) And _ ( ( MIN_LINES <= lineCount ) And ( lineCount <= MAX_LINES ) ) And _ ( Not ErrorProcessing() ) Then ' do something or other ... End If}

Boolean Variables Or consider allDataRead = ( document.AtEndOfStream() ) And ( Not inputError ) legalLineCount = ( MIN_LINES <= lineCount ) And ( lineCount <= MAX_LINES ) If ( allDataRead ) And ( legalLineCount ) And ( Not ErrorProcessing() ) Then // do something or other ... End If

Enumerated Types Public Enum Country Country_China Country_England Public Enum Color Color_Red Color_Green Color_Blue End Enum Public Enum Output Output_Screen Output_Printer Output_File Public Enum Country Country_China Country_England Country_France Country_Germany Country_India Country_Japan Country_Usa End Enum

Use enumerated types for readability Instead of: if chosenColor = 1 you can write more readable expressions like if chosenColor = Color_Red

Enumerated Types Anytime you see a numeric literal, ask whether it makes sense to replace it with an enumerated type: int result = RetrievePayrollData( data, true, false, false, true ); int result = RetrievePayrollData( data, EmploymentStatus_CurrentEmployee, PayrollType_Salaried, SavingsPlan_NoDeduction, MedicalCoverage_IncludeDependents );

Enumerated Types Use enumerated types for modifiability Easier to change, makes more sense Use enumerated types as an alternative to boolean variables Often, a boolean variable isn't rich enough to express the meanings it needs to. an enumerated type with the values Status_Success, Status_Warning, and Status_FatalError would be more useful than a boolean with the values true and false.

Enumerated Types Check for invalid values: Select Case screenColor Case Color_Red ... Case Color_Blue Case Color_Green Case Else DisplayInternalError( False, "Internal Error 752: Invalid color." ) End Select

Enumerated Types Define the first and last entries of an enumeration for use as loop limits Public Enum Country Country_First = 0 Country_China = 0 Country_England = 1 Country_France = 2 Country_Germany = 3 Country_India = 4 Country_Japan = 5 Country_Usa = 6 Country_Last = 6 End Enum

Named Constants Using a named constant is a way of "parameterizing" your program When an array size changes, you change only the definition of the constant you used to declare the array. This "single-point control" goes a long way toward making software truly "soft": easy to work with and change.

Named Constants For (int i ; i <=12 ; i++) { profit( i ) = revenue( i ) - expense( i ); } For (int month ; month <=NUM_MONTHS_IN_YEAR ; month++) { profit( month ) = revenue( month ) -- expense( month ); For (monthT month = Month_January; month <= Month_December ; month++) { profit( month ) = revenue( month ) - expense( month );

Arrays Make sure that all array indexes are within the bounds of the array Consider using containers instead of arrays, or think of arrays as sequential structures Consider using container classes that you can access sequentially—sets, stacks, queues, and so on—as alternatives Random access is like GOTO's – very unstructured