Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
Module2- Part1
Variables,Assignment,andDataTypes
1/23/19 CSE1321MODULE2 1
MotivationTolearnthebasicelementsofprogramming:
1. Declaringvariables(anamedchunkofmemory)
2. Datatypes(thekindofinfoyou’regoingtostore)
3. Assignment(puttingvaluesintoachunkofmemory)
4. Stringliterals
5. Reviewprinting
1/23/19 CSE 1321 MODULE 2 2
Topics
1.ProgramStructure2.CharacterStrings3.Variables4.Assignments5.Constants6.PrimitiveDataTypes
1/23/19 CSE 1321 MODULE 2 3
4CSE1321Module21/23/19
AnapplicationalwayscontainsaMAINmethodsothattheprogramcanbeexecuted.
Inobject-orientedprogramming(OOP)language,MAIN isinsidea“class”
Theseprogramelementstermswillbeexploredindetailthroughoutthecourse
ProgramStructure
5CSE 1321 MODULE 21/23/19
Commentsarejustnotes thatexplaintheprogramtoyourselfandothers.They’reGREEN!
BlockcommentsinJavaandC#◦ Beginwith/*andendswith*/◦ Compilerignoresalltextbetween/*and*/◦ Singlelinecommentsstartwith//◦ Compilerignorestextfrom //toendofline
BlockcommentsinPython◦ Single-linecommentsusethehash(#)character◦ Commentsthatspanmultiple linesarecreatedbyaddingadelimiter(“””)oneachendofthecomment.
Comments
6CSE1321Module21/23/19
Anidentifierisjustanameyougive avariable
Rulesfornames:◦ C#:Muststartwithaletter,cancontainessentiallyanynumberoflettersanddigits,butnospaces,casesensitive.Itcannotbekeywordsorreservedwords– whichturnblue!
◦ Java:Muststartswithaletter,anunderscore(_),oradollarsign($).Cannotstartwithadigit.Cannotbeakeywords(whichturnblue).Canbeofanylength.Casesensitive.
◦ Python:MuststartswithaletterAtoZoratozoranunderscore(_)followedbyzeroormoreletters,underscoresanddigits(0to9).
Identifiers
7CSE 1321 MODULE 21/23/19
abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while
JavaKeywords(badforvariablenames)
8CSE 1321 MODULE 21/23/19
abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in intinterface internal is lock long namespace new null object operator out override paramsprivate protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushortusing var virtual void volatile while
C#Keywords(badforvariablenames)
9CSE1321MODULE21/23/19
False def if raise None del import return True elif in try and else is while as except lambda with assert finally nonlocal yield break for not class from or continue global pass
PythonKeywords
10CSE1321Module21/23/19
Spaces,blanklines,andtabsarecalledwhitespace:
1. Usedtoseparatewords andsymbolsinaprogram.Extrawhitespaceisignored
2. Avalidprogramsyntaxcanbeformattedmanyways
3. Usewhitespaceenhancereadability,usingconsistentindentation
WhiteSpace
11CSE1321Module21/23/19
A“stringliteral”contains0ormorecharactersenclosedwithdoublequotes(inJavaandC#)orsinglequotes(inPython).They’reRED.Examples:◦ “Thequickbrownfoxjumped.”(JavaandC#)◦ 'Thequickbrownfoxjumped.'(Python)◦ “x”(JavaandC#)◦ 'x'(Python)
Squarebrackets[]canbeusedtoaccesselementsinsidethestring(later)
CharacterStrings
12CSE1321Module21/23/19
System.out.println (“Whatever you are, be a good one.”);
1. SystemrepresentstheOperatingSystem
2. “out”istheconsole/screendatastream
3. println isa“function”topushdatatotheconsole
PrintingstringsinJava(review)
13CSE1321Module21/23/19
Console.WriteLine (“Whatever you are, be a good one.”);
1. ConsolerepresentstheOperatingSystem’sconsole
2. WriteLine isa“function”topushdatatotheconsole
PrintingstringsinC#(review)
14CSE1321Module21/23/19
print (‘Whatever you are, be a good one.’)
1. It’sjustprint!
PrintingstringsinPython(review)
15CSE1321Module21/23/19
StringliteralscannotspanmultiplelinesCombinesstringliteralswithotherdatatypesforprintingExample(C#):
String hello = "Hello";String there = "there";String greeting = hello + ' ' + there;Console.WriteLine(greeting );
◦ Output:Hellothere
StringConcatenationOperator(+)
16CSE1321Module21/23/19
CLASS CountDown BEGIN METHOD Main()BEGIN s1 ← "Three... "s2 ← "Two... " s3 ← "One... "s4 ← "Zero... "PRINT(s1 + s2 + s3 + s4 + "Liftoff!") PRINTLINE()
PRINT("Houston, we have a problem.") END Main
END CountDown
Output:
Three... Two... One... Zero... Liftoff!Houston, we have a problem.
Pseudocode
17CSE1321Module21/23/19
// Program CountDown.java
public class CountDown {
public static void main (String[] args) {
String s1 = "Three... "; String s2 = "Two... "; String s3 = "One... "; String s4 = "Zero... "; System.out.println (s1 + s2 + s3 + s4 + "Liftoff!"); System.out.println ("Houston, we have a problem.");
} }
Output:
Three... Two... One... Zero... Liftoff!Houston, we have a problem.
Java
18CSE1321Module21/23/19
using System;class CountDown {
public static void Main(string[] args){
Console.Write("Three... ");Console.Write("Two... ");Console.Write("One... ");Console.Write("Zero... ");Console.WriteLine("Liftoff!"); //on first lineConsole.WriteLine("Houston, we have a problem. ");
}}
Output:Three... Two... One... Zero... Liftoff!Houston, we have a problem.
C#
19CSE1321Module21/23/19
def main():s1='Three... 's2='Two...'s3='One... 's4='Zero... 'print (s1+s2+s3+s4+'Liftoff!')print()print ('Houston,wehaveaproblem.')
if__name__=='__main__':main()
Output:Three... Two... One... Zero... Liftoff!Houston, we have a problem.
Python
20CSE1321Module21/23/19
Printingandescapesequence printsaspecialcharacterinanoutputstring.Commonescapesequences:◦ \b backspace.(e.g “B\bsecz\bret”printswhat?)◦ \t tab◦ \n newline◦ \r carriagereturn◦ \” doublequote◦ \’ singlequote◦ \\ backslash
EscapeSequences
21CSE1321Module21/23/19
public class Roses {
public static void main (String[] args) {
System.out.println ("Roses are red,\n\tViolets are blue,\n"+ "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t"+ "So I'd rather just be friends\n\tAt this point in our "+ "relationship.");
}}Output:
Roses are red,Violets are blue,
Sugar is sweet,But I have "commitment issues",So I'd rather just be friendsAt this point in our relationship.
Java
22CSE1321Module21/23/19
// Escape sequencesclass Roses{
public static void Main(string [] args){
Console.WriteLine("Roses are red,\n\tViolets are blue,\n" + "Sugar is sweet,\n\tBut I have " + "\"commitment issues\",\n\t" + "So I'd rather just be friends\n\t" + "At this point in our relationship.");
}}
C#
23CSE1321Module21/23/19
#Escapesequencesdef main():print ('Rosesarered,\n\tVioletsareblue,\n'+'Sugarissweet,\n\tButIhave\'commitmentissues\',\n\t'+'SoI\'dratherjustbefriends\n\tAtthispointinour'+'relationship.')
if__name__=='__main__':main()
Python
24CSE1321Module21/23/19
Avariable isanameforalocationinmemoryusedtoholdadatavalue.Avariablemustbedeclaredbyspecifyingthevariable'sname andthetype ofinformationthatitwillhold.
Examples(JavaandC#):int total; // chunk of memory named totalint count, temp, result; // three variables
Multiplevariablescanbecreatedinonedeclaration
Variables
25CSE1321Module21/23/19
// Prints the number of keys on a piano.CLASS PianoKeysBEGIN
METHOD Main()BEGINkeys ← 88PRINT("A piano has " + keys + " keys.")
END MainEND PianoKeys
Output: A piano has 88 keys.
Pseudocode
26CSE1321Module21/23/19
// Prints the number of keys on a piano.public class PianoKeys{
public static void main (String[] args){
int keys = 88; //declare and initializeSystem.out.println ("A piano has " + keys + " keys.");
}}
Output: A piano has 88 keys.
Java
27CSE1321Module21/23/19
// Prints the number of keys on a pianousing System;
class PianoKeys {public static void Main (string[] args) {
int keys = 88; //declare and initializeConsole.WriteLine("A piano has " + keys + " keys.");
}}
Output: A piano has 88 keys.
C#
28CSE1321Module21/23/19
#prints the number of keys on a piano.
def main():keys = 88print("A piano has ", keys, " keys.");
if __name__ == '__main__':main()
Output: A piano has 88 keys.
Python
29CSE1321Module21/23/19
Namesofvariables:◦ shouldbemeaningful◦ reflectthedata theywillstore.◦ variablenameswill“selfdocument”theprogram◦ smallvariablenamesareNOTmoreefficient◦ avoidextremelylongnames
Avoidnamessimilartokeywords
Conventions– NamingVariables
30CSE1321Module21/23/19
Assignment statements change the value of a variable
The assignment operator is the = sign
total = 55; // put value of 55 into total
The expression on the right is evaluated and the result is stored in the variable on the left
The value that was in total is overwritten
The data type on the right must match the data type on the left!
Assignment
31CSE1321Module21/23/19
// Print the number of sides of several geometric shapes.CLASS GeometryBEGIN
METHOD Main()BEGIN
sides ← 7PRINT("A heptagon has " + sides + " sides.")sides ← 10PRINT("A decagon has " + sides + " sides.")sides ← 12PRINT("A dodecagon has " + sides + " sides.")
END MainEND Geometry
Output:A heptagon has 7 sides.A decagon has 10 sides.A dodecagon has 12 sides.
Pseudocode
32CSE1321Module21/23/19
// Print the number of sides of several geometric shapes.public class Geometry {
public static void main (String[] args) {int sides = 7; // declare and initializeSystem.out.println ("A heptagon has " + sides + " sides.");sides = 10; // assignment statementSystem.out.println ("A decagon has " + sides + " sides.");sides = 12; // assignment statementSystem.out.println ("A dodecagon has " + sides + " sides.");
}}
Java
33CSE1321Module21/23/19
// Print the number of sides of several geometric shapes.using System;
class Geometry {public static void Main (string[] args) {
int sides = 7; // declare and initializeConsole.WriteLine("A heptagon has " + sides + " sides.");sides = 10; // assignment statementConsole.WriteLine("A decagon has " + sides + " sides.");sides = 12; // assignment statementConsole.WriteLine("A dodecagon has " + sides + " sides.");
}}
C#
34CSE1321Module21/23/19
def main():sides=7#declareandinitializeprint("Aheptagonhas",sides,"sides.")sides=10#assignmentstatementprint("Adecagonhas",sides,"sides.")sides=12#assignmentstatementprint("Adodecagonhas ",sides,"sides.")
if __name__=='__main__':main()
Python
35CSE1321Module21/23/19
Valuesthatcannotchange.
Avaluemustbeassignedbeforetheconstantisused.
Threereasons:◦ Theygivemeaningtootherwiseunclearliteralvalues.Forexample,MAX_LOADmeansmorethantheliteral250
◦ Programmaintenance.Ifaconstantisusedinmultipleplaces,itsvalueneedonlybeupdatedinoneplace.
◦ Avoiderrors byotherprogrammers
Constants
36CSE1321Module21/23/19
UseallCAPITALLETTERSforconstantsandseparatewordswithanunderscore:
Forexample(Java):final double TAX_RATE = .05;
Declareconstantsatthetopoftheprogram
PythondoesnotsupportConstants.
Constants– JavaandC#
37CSE1321Module21/23/19
Datatypetellscompiler:– Howmuchmemory toallocate– Format inwhichtostoredata– TypesofoperationsyouwillperformondataCompilermonitorsuseofdata– C#,Java,andPythonare"stronglytyped"language.Thatis,variablescannotbeimplicitlycoercedtounrelatedtypes
DataTypes
38CSE1321Module21/23/19
• 8 simple data types:– 4 subsets of integers– 2 subsets of floating point numbers– Character– Boolean
• Everything else is a complex data type, built from simple or other complex data types
• Later, we’ll define our own data types!
DataTypes
39CSE1321Module21/23/19
Differenceisinamountofmemoryreservedforeach(i.e thesizeofthevaluestored)1. Afloatonlyhas7significantdigits2. Signednumbershavebothpositiveandnegative
values3. Unsignednumbersare>=0
Whysomanytypes?
40CSE1321MODULE21/23/19
Statictypechecking(C#andJava)•Statictypecheckingoccursduringcompilation•Requiresyoutodeclarevariabletypesbeforeyouusethem
Dynamictypechecking(Python)•Dynamictypecheckingoccurswhileprogramisrunning•Doesnot requireyoutodeclarethedatatypesofyourvariablesbeforeyouusethem
•Pythonusesdynamictyping,butisalsoisstronglytyped,astheinterpreterkeepstrackofallvariablestypes.
Staticv.DynamicTyping
41CSE1321Module21/23/19
Values without a decimal point are considered int
Values with decimal point are considered double, which is bigger than a float!
Examples (Java)int testGrade = 100;byte ageInYears = 19;long cityPopulation = 425612340L float salesTax = .05F; // NOTE the Fdouble interestRate = 0.725; double avogadroNumber = +6.022E23;
LiteralNumbers
42CSE1321Module21/23/19
Twocommonwaystoholdcharacters:1. ASCII(8bits)– howmanycharactersinEnglish?2. Unicode(16bits)– howmanycharactersinMandarin?3. Unicodeismostcommonlyused
Exampledeclarations:char finalGrade = ‘A’; // NOTE single quoteschar newline, tab, doubleQuotes;
PythonhasNOchardatatype.
char DataType(JavaandC#)
43CSE1321Module21/23/19
Two values only:– true
– false
Used for decision making or as "flag" variablesExample declarations:bool isEmpty = false; //in C#boolean passed = true; //in JavaA = True //in Python
boolean DataType
44CSE 1321 MODULE 21/23/19
1. Variable declaration indicates its type and possibly its initial value.
2. A value is assigned using assignment operator.
3. A constant value doesn’t change
4. Data type tells how much memory to allocate, the format in which
to store data, and the types of operations you will perform on
data.
5. Primitive data types include integer, floating point, character,
boolean, and decimal.
Summary