Varriables CSC 171 FALL 2001 LECTURE 2
History The abacus
History – use of gears William Schickard 1623 Blaise Pascal 1642 Gottfried Leibniz 1673
Variables Variables are “places to put things/values” Variables correspond to locations in the computer’s memory – Name – Type – Size – Value
Declaration & assignment int x; int y = 7; x = 5; y = 12;
Expressions int x, y, z, a, b, c ; y = 7 ; x = 5 ; z = x + y ; a = x - 10 ; b = a * x + y ; a = a + x ;
Variables The variable “count” used above – Name : “count” – Type : integer (int) – Size : 4 bytes (32 bits) – machine dependent – Value : starts at zero, but the value varies/changes
Integers Assignment : a = 0; Arithmetic : +,-,* Integer division discards fractions – 17 / 5 == 3 Modulus operator generates remainders – 17 % 5 == 2
History – first “programs” 1801 Joseph-Marie Jacquard invented an automatic loom using punched cards for the control of the patterns in the fabrics.
Strings Generating new strings – String s1 = new String(); – s1 = new String(“*”); Adding Strings – s2 = s1 + s1 ; // == “**” Generating new strings from strings – s1 = new String(s1 + s2); // == “***”
Boolean expressions boolean expressions can take on one of two values (true or false) 3 <= 5 – true 3 > 5 – false
Boolean variables int x = 5, y = 3; boolean test1, test2, test3, test4; test1 = x < y ; test2 = x >= y; test3 = test1 && test2; test4 = test1 || test 2;
“OR” OPERATION ABA || B False True FalseTrue
“AND” OPERATION ABA && B False TrueFalse TrueFalse True
The Binding Pattern = ; Examples int score = 59 ; double todaysTemp = 67.4 ; char letterGrade = ‘A’; String firstName = “Ted”;
JAVA Primitive Data Types boolean – true or false char – character values ‘a’, byte – 8 bit values short – 16 bit integers int – 32 bit integers long – 64 bit integers float – 32 bit values, with decimal point double – 64 bit values, with decimal point
Identifiers The name of the thing is an identifier Must begin with a – ‘_’ – a letter The rest can consist of – ‘_’ – letters – digits
Style Choose meaningful variable names – Accurately describe the data entity – Neither too long nor too short – Adopt a convention Good variable naming is good documentation Good variable naming requires you to think about what your program is doing (design)
Code from Hell X = X – XX ; XXX = Aretha + ST(Aretha); X = X + LF(X1,X) + XXX; X = X + Intrst(X1,X);
As opposed to : Balance = Balance – LastPayment; MonthlyTotal = NewPurchases + SalesTax(NewPurchases); Balance = Balance + LateFee(CustomerID,Balance) + MontlyTotal; Balance = Balance + Interest(CustomerID,Balance);