Lesson 02 Working with Data Types MIT 31043: VISUAL PROGRAMMING Senior Lecturer in MIT
Variables A variable is a storage location in memory that is represented by a name. A variable stores data, which are processed with statements. A program is a list of statements that manipulate variables. To write even simple applications, you need a basic understanding of some fundamental topics, such as the data types (the kind of data you can store in a variable), the scope and lifetime of variables, and how to write procedures and pass arguments to them. A variable has a name and a value. The variable UserName, for example, can have the value MIT, and the variable Salary can have the value 10000. UserName and Salary are variable names, and MIT and 10000 are their values. MIT is a string (that is, text or an alphanumeric value), and 10000 is a numeric value. When a variable s value is a string, it must be enclosed in double quotes. In your code, you can refer to the value of a variable by the variable s name. In addition to a name and a value, variables have a data type, which determines what kind of values we can store to a variable. C# supports several data types. The data type of a variable is specified when the variable is declared, and you should always declare variables before using them. Slide 2
Naming variables You should adopt a naming convention for variables that helps you to avoid confusion concerning the variables you have defined. This is especially important if you are part of a project team with several developers working on different parts of an application; a consistent naming convention helps to avoid confusion and can reduce the scope for bugs. The following list contains some general recommendations: o In a multiword identifier, start the second and each subsequent word with an uppercase letter. (This is called camelcasenotation.) o Don t start an identifier with an underscore o Don t create identifiers that differ only by case. For example, myvariable and MyVariable o Start the name with a lowercase letter. Slide 3
Declaring variables In most programming languages, variables must be declared in advance. Historically, the reason for doing this has been to help the compiler generate the most efficient code. If the compiler knows all the variables and their types ahead of time, it can produce the most compact and efficient, or optimized, code. You declare the type and name of a variable in a declaration statement. int age; The variable type int is the name of one of the primitive C# types, integer, which is a whole number. After declaring, you can assign it a value. age = 38; Slide 4
Data Types: Integer Types TYPE ALLOWED VALUES sbyte Integer between 128 and 127 byte Integer between 0 and 255 short Integer between 32768 and 32767 ushort Integer between 0 and 65535 int Integer between 2147483648 and 2147483647 uint Integer between 0 and 4294967295 long Integer between 9223372036854775808 and 9223372036854775807 ulong Integer between 0 and 18446744073709551615 The u characters before some variable names are shorthand for unsigned, meaning that you can t store negative numbers in variables of those types, as shown in the Allowed Values column of the preceding table. Slide 5
Data Types: Floating-point Types TYPE APPROX MIN VALUE APPROX MAX VALUE float 1.5 10 45 3.4 1038 double 5.0 10 324 1.7 10308 decimal 1.0 10 28 7.9 1028 Slide 6
Data Types: Text and Boolean Types TYPE char bool string ALLOWED VALUES Single Unicode character, stored as an integer between 0 and 65535 Boolean value, true or false A sequence of characters Slide 7
Syntax type variablename = value; Examples int intcounter = 1; Declaring variables long lngnumberofbytes = 20000; float fltinterestrate = 8.125f; // f or F indicates a float value double dblprice = 14.95; decimal dectotal = 24218.1928m; // m or M indicates a decimal value char chrletter = 'A'; // enclose a character value in single quotes bool blnvalid = false; int intx = 0, inty = 0; // initialize 2 variables with 1 statement Slide 8
Named Constant A named constant is a name that represents a value that cannot be changed during the program s execution. Assume that the following statement appears in a banking program that calculates data pertaining to loans: o amount = balance * 0.069; Two potential problems arise: o First, it is not clear to anyone other than the original programmer what 0.069 is. o The second problem occurs if this number is used in other calculations throughout the program and must be changed periodically. Slide 9
Declaring Constants How to declare and initialize a constant Syntax const type CONSTANT_NAME = value; Examples const int DAYS_IN_NOVEMBER = 30; const decimal SALES_TAX =.075m; Naming conventions Capitalize all letters for each word of a constant name, separating with underscores. Slide 10
Arithmetic Operators Operator Name Description + Addition Adds two operands. - Subtraction Subtracts the right operand from the left operand. * Multiplication Multiplies the right operand and the left operand. / Division Divides the right operand into the left operand. If both operands are integers, then the result is an integer. % Modulus Returns the value that is left over after dividing the right operand into the left operand. Slide 11
Arithmetic operators (continued) Operator Name Description + Positive sign Returns the value of the operand. - Negative sign Changes a positive value to negative, and vice versa. ++ Increment Adds 1 to the operand (x = x + 1). -- Decrement Subtracts 1 from the operand (x = x - 1). Slide
Assignment Operators Operator Name = Assignment += Addition -= Subtraction *= Multiplication /= Division %= Modulus Slide 13
Assignment Operators The syntax for a simple assignment statement variablename = expression; Typical assignment statements intcounter = 7; intnewcounter = intcounter; decdiscountamount = decsubtotal *.2m; dectotal = decsubtotal decdiscountamount; Slide 14
Assignment Operators Statements that use the same variable on both sides of the equals sign dectotal = dectotal + 100m; dectotal = dectotal 100m; decprice = decprice *.8m; Statements that use the shortcut assignment operators dectotal += 100m; dectotal -= 100m; decprice *=.8m; Slide
The order of precedence for arithmetic operations 1. Increment and decrement 2. Positive and negative 3. Multiplication, division, and modulus 4. Addition and subtraction Slide 16
Common methods for data conversion Method Description ToString([format]) A method that converts the value to its equivalent string representation using the specified format. If the format is omitted, the value isn t formatted. Parse(string) A static method that converts the specified string to an equivalent data value. Slide
Sample ToString formats Variable Value Format specifier code Output totaldecimal 1125.6744 ToString("C" ) $1,125.67 totaldecimal 1125.6744 ToString("N") 1,125.67 totaldecimal 1125.6744 ToString(" N0 ") 1,126 balancedecimal 1125.6744 ToString(" N3 ") 1,125.674 balancedecimal 1125.6744 ToString(" F0 ") 1126 pininteger 123 ToString(" D6 ") 000123 ratedecimal 0.075 ToString(" P " ) 7.50 % ratedecimal 0.075 ToString(" P3 ") 7.500 % ratedecimal 0.075 ToString(" P0 ") 8 % valueinteger 10 ToString(" C " ) ($10.00) valueinteger 10 ToString(" N " ) 10.00 valueinteger 10 ToString(" D3 ) 010 Code Formats C or c Currency, P or p Percent, N or n Number, F or f Float, D or d Digits, E or e Exponential, G or g General Slide 18
Some of the static methods of the Convert class Method ToDecimal(value) ToDouble(value) ToInt32(value) ToChar(value) ToBool(value) ToString(value) Description Converts the value to the decimal data type. Converts the value to the double data type. Converts the value to the int data type. Converts the value to the char data type. Converts the value to the bool data type. Converts the value to the string data type. Slide
Statements that use ToString and Parse decimal decsales = 2574.98m; string strsalesstring = decsales.tostring(); // decimal to string decsales = Decimal.Parse(strSalesString); // string to decimal Conversion statements that use the Convert class decimal decsubtotal = Convert.ToDecimal(txtSubtotal.Text); // string to decimal int intyears = Convert.ToInt32(txtYears.Text); // string to int txtsubtotal.text = Convert.ToString(decSubtotal); // decimal to string int subtotalint = Convert.ToInt32(decSubtotal); // decimal to int
Practical Exam - 01 Write a Visual C# program that takes Amount as input and displays the possible currency denominations as output. Currency denominations are 5000/=, 2000/=, 1000/=, 500/=, 100/=, 50/=, 20/=, 10/= and Coins. Practice 02: By. SaNa 21
Interface Design Practice 02: By. SaNa 22
Practice Practice 02: By. SaNa 23
Interface Design basicsalarytextbox otratetextbox othourstextbox loantextbox bonustextbox allowancetextbox netsalarytextbox Practice 02: By. SaNa 24
Codes Practice 02: By. SaNa 25
Codes (casting) Practice 02: By. SaNa 26
Design the form as below Ex 01 Slide
Ex 01 Double click on Convert button and add the following code Slide
Ex 01 Double click on Clear button and add the following code Double click on Exit button and add the following code Slide
Ex 02: Invoice Total Slide
Ex 02: Code Slide
Understanding Numeric Type Conversion When you perform arithmetic with variables or constants of the same type, the result of the arithmetic retains the same type. For example, when you divide two ints, the result is an int; when you subtract two doubles, the result is a double. Often, however, you need to perform mathematical operations on different types. For example, in the following code, you multiply an int by a double: o int hoursworked = 36; o double payrate = 12.35; o double grosspay = hoursworked * payrate; Slide 34
Understanding Numeric Type Conversion When you perform arithmetic operations with operands of dissimilar types, C# chooses a unifying type for the result and implicitly (or automatically) converts nonconforming operands to the unifying type, which is the type with the higher type precedence. The conversion is called an implicit conversion or an implicit cast the automatic transformation that occurs when a value is assigned to a type with higher precedence. For example, if you multiply an int and a double, the result is implicitly a double. This requirement means the result must be stored in a double; if you attempt to assign the result to an int, you will receive a compiler error message like the one shown in Figure. Slide 35
Understanding Numeric Type Conversion Error message received when trying to compile a program that attempts to store a double in an int The error message in figure asks are you missing a cast? You may explicitly (or purposefully) override the unifying type imposed by C# by performing an explicit cast. An explicit cast involves placing the desired result type in parentheses followed by the variable or constant to be cast, as shown below Slide 36
Understanding Numeric Type Conversion Another example is shown here o The value of bankbalance / 4 is implicitly a double because a double divided by an int produces a double. o The double result is then converted to a float before it is stored in weeklybudget. o The float value weeklybudget is converted to an int before it is stored in rupees. o When the float value is converted to an int, the decimal-place values are lost. Implicit conversions are not always the result of arithmetic calculations; simple assignments often result in implicit conversions. For example, if money is declared as a double, then the following statement implicitly converts the integer 15 to a double: o double money; o money = 15; Slide 37
The implicit numeric conversions From sbyte short, int, long, float, double, or decimal From byte short, ushort, int, uint, long, ulong, float, double, or decimal From short int, long, float, double, or decimal From ushort int, uint, long, ulong, float, double, or decimal From int long, float, double, or decimal From uint long, ulong, float, double, or decimal From long float, double, or decimal From ulong float, double, or decimal From char ushort, int, uint, long, ulong, float, double, or decimal From float double Slide 38
End