CIS 3260 Intro to Programming with C#

Similar documents
Lesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT

Lesson 02 Working with Data Types MIT 31043, Visual Programming By: S. Sabraz Nawaz

Programming Language 2 (PL2)

Visual C# Instructor s Manual Table of Contents

Chapter 2: Using Data

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS

Full file at

Full file at

IT 374 C# and Applications/ IT695 C# Data Structures

Basics of Java Programming

Ex: If you use a program to record sales, you will want to remember data:

Program Fundamentals

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

COMP Primitive and Class Types. Yi Hong May 14, 2015

Reserved Words and Identifiers

Microsoft Visual Basic 2015: Reloaded

Datatypes, Variables, and Operations

Programming in C++ 5. Integral data types

Java Notes. 10th ICSE. Saravanan Ganesh

LECTURE 3 C++ Basics Part 2

Fundamentals of Programming

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Programming Lecture 3

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

DEPARTMENT OF MATHS, MJ COLLEGE

3. Java - Language Constructs I

Fundamental of Programming (C)

Chapter 2 Elementary Programming

C/C++ Programming for Engineers: Working with Integer Variables

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

UNIT- 3 Introduction to C++

MODULE 02: BASIC COMPUTATION IN JAVA

Microsoft Visual Basic 2005: Reloaded

These are reserved words of the C language. For example int, float, if, else, for, while etc.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Chapter 8. Arrays The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Introduction to Data Entry and Data Types

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Pseudocode is an abbreviated version of the actual statement t t (or code ) in the program.

Introduction to C# Applications

Basics of Programming

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 2: Using Data

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Variables and Operators 2/20/01 Lecture #

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Chapter 2. Outline. Simple C++ Programs

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

CS313D: ADVANCED PROGRAMMING LANGUAGE

Outline. Data and Operations. Data Types. Integral Types

Unit 3. Operators. School of Science and Technology INTRODUCTION

Java Primer 1: Types, Classes and Operators

Lecture 3 Tao Wang 1

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

BITG 1233: Introduction to C++

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

CIS Intro to Programming in C#

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Chapter 2: Using Data

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Engineering Problem Solving with C++, Etter/Ingber

Chapter 03: Computer Arithmetic. Lesson 09: Arithmetic using floating point numbers

Computer System and programming in C

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

CMPT 125: Lecture 3 Data and Expressions

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Introduction to Programming EC-105. Lecture 2

Arithmetic Operations

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

LECTURE 02 INTRODUCTION TO C++

Lecture 2 Tao Wang 1

2. Numbers In, Numbers Out

Language Fundamentals

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Programming for Engineers Iteration

Objectives. In this chapter, you will:

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Introduction to Computer Use II

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

REVIEW. The C++ Programming Language. CS 151 Review #2

ARG! Language Reference Manual

Chapter-8 DATA TYPES. Introduction. Variable:

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Transcription:

Variables, Constants and Calculations McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Define a variable Distinguish between variables, constants, and control objects Differentiate among the various data types Differentiate accessing by value or by reference Apply naming conventions incorporating standards and indicating the data type Declare variables and constants Select the appropriate scope for a variable Convert text input to numeric values McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-2 Perform calculations using variables and constants Convert between numeric data types Format values for output using the ToString method The string.format method (quick intro more later) Use try/catch blocks for error handling Display message boxes with error messages Accumulate sums and generate counts McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-3 Dr. David McDonald Chapter 3 Page 1

Variable A named location in memory that holds data that can change during project execution Example: Customer's name Constant Memory locations that hold data that cannot change during execution Examples: Company name or sales tax rate McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-4 Sample declaration statements //Declare a string variable. string namestring; //Declare integer variables. int counterinteger; int maxinteger = 100; //Declare a named constant. const decimal DISCOUNT_RATE_Decimal =.15M; McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-5 bool true or false values byte 0 to 255, binary data char Single Unicode character DateTime 1/1/0001 00:00:00 through 12/31/9999 23:59:59 decimal Decimal fractions, such as dollars & cents, precision of 28 digits float Single-precision floating-point numbers, six digits of accuracy double Double-precision floating-point numbers, 14 digits of accuracy short Small integer in the range 32,768 to +32,767 int Whole numbers in the range 2,147,483,648 to +2,147,483,647 long Larger whole numbers string Alphanumeric data: letters, digits and other characters object Any type of data McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-6 Dr. David McDonald Chapter 3 Page 2

Common types of variables and constants string int decimal Guideline for use Data used in calculations must be numeric decimal any decimal fraction including dollars int whole number calculations float and double scientific applications Text characters and numbers not used in calculations string including phone or social security numbers McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-7 May contain letters, digits, and underscores Must begin with a letter or underscore Cannot contain spaces or periods Cannot be reserved words (keywords) Examples: print, name, value Case sensitive suminteger, SumInteger, suminteger and SUMINTEGER are different variables McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-8 Should follow naming conventions Identifiers must be meaningful Clearly indicate the purpose Do not abbreviate Do not use X or Y Include the class (data type) Use camel casing for variables Begin with a lowercase letter Capitalize each successive word Use uppercase for constants Separate words with underscores McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-9 Dr. David McDonald Chapter 3 Page 3

Constants contain a value that does not change Intrinsic a.k.a. keyword identifiers Built into the environment, not defined Named Defined by programmer McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-10 Declare using keyword const Assign name, data type, value Data type declared and data type of value must match Two advantages to using Easier to read Precision is the same for all calculations Const Statement Examples: const string COMPANY_ADDRESS_String = 101 S. Main Street ; const decimal SALES_TAX_RATE_Decimal =.08m; McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-11 Declared in system class libraries Specify class name or group name and constant name (this is really known as an enumeration) Example Color.Red is the constant Red in the class Color McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-12 Dr. David McDonald Chapter 3 Page 4

Declare a variable Specify data type and follow with an identifier Assign an initial value (optional) string customernamestring; string customernamestring = textboxname.text; private int totalsoldinteger; int totalsoldinteger = 0; float temperaturefloat; float temperaturefloat = 32f; decimal pricedecimal; private decimal pricedecimal = 99.95m; McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-13 IntelliSense helps in entering declaration statements Type correct entry List scrolls to correct section When correct entry is highlighted Press Enter (move to a new line of code), or Tab, spacebar, or double-click entry with mouse(stay on the same line of code) McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-14 Visibility of a variable is its scope Namespace Also referred to as global Class-level Local Block Scope of variable determined by where it is declared McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-15 Dr. David McDonald Chapter 3 Page 5

Period of time a variable exists Local or block variable One execution of a method After execution variables disappear, memory locations are released Class-level variable Entire time class is loaded (usually lifetime of project) Variables maintain value for multiple executions of a method McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-16 Variable declared inside a method is local in scope Known only to that method Must be declared prior to first use All declarations should appear at the top of a method (after comments) McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-17 Variables declared at class level can be used anywhere in that form s class Place after opening brace for class, outside of any method Values remain in memory as long as the class exists in memory Class variables and constants McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-18 Dr. David McDonald Chapter 3 Page 6

Calculations are performed with Variables Constants Properties of certain objects i.e. Text property of text box or label Character strings must be converted to correct data type first McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-19 Parse method converts the Text property of a control to a numeric value that can be used in calculations int.parse converts text to an integer decimal.parse converts text to a decimal Pass the text string to convert as an argument of the Parse method // Convert input values to numeric variables. quantityinteger = int.parse(quantitytextbox.text); pricedecimal = decimal.parse(pricetextbox.text); //Calculate the extended price. extendedpricedecimal = quantityinteger * pricedecimal; McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-20 Parse attempts to convert the string to the specified data type Values such as blanks or nonnumeric characters cause an error Parse methods exist for long, float or double conversions quantityinteger = int.parse(quantitytextbox.text); pricedecimal = decimal.parse(pricetextbox.text); wholenumberinteger = int.parse(digitstring); McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-21 Dr. David McDonald Chapter 3 Page 7

Assignment must be of like types Assign a string value to a string variable or property Assign a numeric value to a numeric variable or property To assign the result of a calculation to the Text property of a control, use the ToString method resulttextbox.text = resultdecimal.tostring(); counttextbox.text = countinteger.tostring(); idstring = idinteger.tostring(); McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-22 Operator Operation + Addition Subtraction Multiplication / Division % Modulus remainder of division McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-23 Exponentiation C# does not have an operator for exponentiation Use Math.Pow See Appendix B for Math methods McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-24 Dr. David McDonald Chapter 3 Page 8

Hierarchy of operations or order of precedence in arithmetic expressions 1. Any operation inside parentheses 2. Multiplication and division 3. Modulus 4. Addition and subtraction 3 + 4 2 = 11 Multiply then add (3 + 4) 2 = 14 Add then multiply 8 / 4 2 = 4 Divide then multiply 8 / (4 2) = 1 Multiply then divide McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-25 Perform calculations in assignment statements Calculation appears on the right side of the assignment sign (=) Result is assigned to a variable or property on the left side of the equal sign (never a constant) averagedecimal = sumdecimal / countinteger; amountduelabel.text = (pricedecimal (pricedecimal * discountratedecimal)).tostring(); commissiontextbox.text = (salestotaldecimal * commissionratedecimal).tostring(); McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-26 Combined assignment operators Perform both a calculation and an assignment += Add to the operator on the left totalsalesdecimal += saledecimal; = Subtract from the operator on the left countdowninteger = 1; = Multiply by operator on left and assign result to the operator resultinteger = 2; /= Divide into operator on left and assign result to the operator sumdecimal /= countinteger; += (Strings) concatenate to the operator on the left bigstring += smallstring; McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-27 Dr. David McDonald Chapter 3 Page 9

Increment (++) Adds 1 to a variable countinteger++; Decrement ( ) Subtracts 1 from the variable countdowninteger ; Prefix notation Prefix to perform the increment before the arithmetic operation Add 1 to countinteger before subtracting from 100 resultinteger = 100 ++countinteger; Postfix notation Postfix to perform the increment after the arithmetic operation Subtract countinteger from 100 before incrementing countinteger resultinteger = 100 countinteger++; McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-28 Explicit conversions Also called casting Convert between data types without implicit conversions Specify the destination data type in parentheses before the data value to convert Generates an exception if significant digits will be lost numberdecimal = (decimal) numberfloat; valueint = (int) valuedouble; McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-29 Convert class methods C# methods available ToDecimal, ToSingle, ToDouble Integer data types use.net class names short ToInt16 int ToInt32 long ToInt64 Examples numberdecimal = Convert.ToDecimal(numberSingle); valueinteger = Convert.ToInt32(valueDouble); valuedouble = Convert.ToDouble(textBoxInput.text); McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-30 Dr. David McDonald Chapter 3 Page 10

Round decimal fractions using decimal.round Returns a decimal result rounded to the specified number of digits // Round to two decimal positions. resultdecimal = decimal.round(amountdecimal, 2); decimal.round and Convert methods use "rounding toward even" if the digit to the right of the final digit is exactly 5. Decimal value to round Number of decimal positions Result 1.455 2 1.46 1.445 2 1.44 1.5 0 2 2.5 0 2 McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-31 Display numeric data in a label or text box by converting the value to a string Use ToString method displaytextbox.text = numberinteger.tostring(); Format the data using formatting codes as an argument of the ToString method Specifies dollar sign, percent sign, and commas Specifies the number of digits to the right of the decimal point McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-32 "C" or "c" Currency String formatted with a dollar sign, commas separating each group of three digits, and two digits to the right of the decimal point extendedpricetextbox.text = (quantityinteger * pricedecimal).tostring("c"); "N" or "n" Number String formatted with commas separating each group of three digits, two digits to right of the decimal point discounttextbox.text = discountdecimal.tostring("n"); Specify number of decimal positions by placing a numeric digit following the specifier code discounttextbox.text = discountdecimal.tostring("n3"); McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-33 Dr. David McDonald Chapter 3 Page 11

Additional Format Specifier Codes "F" or "f" Fixed point String of numeric digits, no commas, two decimal places, minus sign at left for negative values "D" or "d" Digits Force a specified number of digits to display For integer data types only, minus sign at left "P" or "p" Percent Multiplies the value by 100, adds a space and a percent sign, rounds to two decimal places Additional codes for dates and times d, D, t, T, f, F, g, G, m, M, r, R Date and time codes are case sensitive McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-34 Variable Value Format Specifier Code Output totaldecimal 1125.6744 "C" $1,125.67 totaldecimal 1125.6744 "N" 1,125.67 totaldecimal 1125.6744 "N0" 1,126 balancedecimal 1125.6744 "N3" 1,125.674 balancedecimal 1125.6744 "F0" 1126 pininteger 123 "D6" 000123 ratedecimal 0.075 "P" 7.50 % ratedecimal 0.075 "P3" 7.500 % ratedecimal 0.075 "P0" 8 % valueinteger 10 "C" ($10.00) valueinteger 10 "N" 10.00 valueinteger 10 "D3" 010 McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-35 Exceptions cause run-time errors Blank or non-numeric data cause Parse methods to fail Entering a number that results in an attempt to divide by zero Exception Handling catches bad data before a run-time error occurs Writing code to catch exceptions is called exception handling Exception handling in Visual Studio.NET is standardized for all languages that use the CLR McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-36 Dr. David McDonald Chapter 3 Page 12

Enclose any statement(s) that might cause an error in a try/catch block If an exception occurs while the statements in the try block are executing, program control transfers to the catch block The code in a finally block (if included) executes last, whether or not an exception occurred McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-37 try { // Statements that may cause error. } catch [(ExceptionType [VariableName])] { // Statements for action when exception occurs. } [finally { // Statements that always execute before exit of try block. }] McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-38 Display a message in a message box User has entered invalid data User neglects to enter required data Specify message, optional icon, title bar text and buttons Use Show method of the MessageBox object to display a message box McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-39 Dr. David McDonald Chapter 3 Page 13

Arguments must match one of the formats Do not reverse, transpose or leave out any argument MessageBox.Show(TextMessage); MessageBox.Show(TextMessage, TitlebarText); MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons); MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons, MessageBoxIcon); McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-40 Overloading allows the Show method to act differently for different arguments Each argument list is called a signature The Show method has several signatures Supplied arguments must exactly match one of the signatures IntelliSense helps in entering the arguments (no need to look up or memorize the signatures) McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-41 Declare a class level variable Retains its value for multiple calls Allows accumulation of totals Summing numbers totalamountdecimal += amountdecimal; Counting numbers Add 1 to the counter variable in the calculate event method salecountinteger ++; Calculating an average Divide the sum of items by the count of items averagesaledecimal = totalamountdecimal / salecountinteger; McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-42 Dr. David McDonald Chapter 3 Page 14