CSE1301 - Kennesaw State University

Module 2 - Part 1 Variables, Assignment, and Data Types 02/11/2020 CSE 1321 Module 2 1 Motivation To learn the basic elements of programming: 1. Declaring variables (a named chunk of memory) 2. Data types (the kind of info youre going to store) 3. Assignment (putting values into a chunk of memory) 4. String literals 5. Review printing

02/11/2020 CSE 1321 Module 2 2 Topics 1.Program Structure 2.Character Strings 3.Variables 4.Assignments 5.Constants 6.Primitive Data Types 02/11/2020 CSE 1321 Module 2 3

Program Structure An application always contains a MAIN method so that the program can be executed. In object-oriented programming (OOP) language, MAIN is inside a class These program elements terms will be explored in detail throughout the course 02/11/2020 CSE 1321 Module 2 4 Comments Comments are just notes that explain the program to yourself and others. Theyre GREEN! Block comments in Java, C++ and C#

Begin with /* and ends with */ Compiler ignores all text between /* and */ Single line comments start with // Compiler ignores text from // to end of line 02/11/2020 CSE 1321 Module 2 5 Identifiers An identifier is just a name you give a variable Rules for names: C# and C++: Must start with a letter, can contain essentially any number of letters and digits, but no spaces, case sensitive. It cannot be keywords or reserved words which turn blue! Java: Must starts with a letter, an underscore (_), or a

dollar sign ($). Cannot start with a digit. Cannot be a keywords (which turn blue). Can be of any length. Case sensitive. 02/11/2020 CSE 1321 Module 2 6 Java Keywords (bad for variable names) 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 02/11/2020 CSE 1321 Module 2 7 C# Keywords (bad for variable names) 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 int interface internal is lock long namespace

new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using var virtual void volatile while 02/11/2020 CSE 1321 Module 2 8 C++ Keywords alignas, alignof, and, and_eq, asm, atomic_cancel, atomic_commit, atomic_noexcept, auto, bitand,bitor, bool, break, case, catch, char, char8_t, char16_t, char32_t, class, compl, concept, const, consteval, constexpr, const_cast, continue, co_await,co_return, co_yield, decltype, default,

delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private, protected, public, reflexpr, register, reinterpret_cast, requires, return, short, signed, sizeof, static, static_assert, static_cast, struct, switch, synchronized, template, this, thread_local, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while, xor, xor_eq 02/11/2020 CSE 1321 Module 2 9 White Space Spaces, blank lines, and tabs are called white space: 1. Used to separate words and symbols in a program. Extra white space is ignored

2. A valid program syntax can be formatted many ways 3. Use whitespace enhance readability, using consistent indentation 02/11/2020 CSE 1321 Module 2 10 Character Strings A string literal contains 0 or more characters enclosed with double quotes. They turn RED. Examples: The quick brown fox jumped. x Square brackets [] can be used to access elements inside the string (later)

02/11/2020 CSE 1321 Module 2 11 Printing strings in Java (review) System.out.println (Whatever you are, be a good one.); 1. System represents the Operating System 2. out is the console/screen data stream 3. println is a function to push data to the console 02/11/2020 CSE 1321 Module 2

12 Printing strings in C# (review) Console.WriteLine (Whatever you are, be a good one.); 1. Console represents the Operating Systems console 2. WriteLine is a function to push data to the console 02/11/2020 CSE 1321 Module 2 13 Printing strings in C++ (review)

cout << Whatever you are, be a good one. << endl; 1. cout is called a stream (an output stream) 2. You push things into cout 3. endl is short for end line 02/11/2020 CSE 1321 Module 2 14 String Concatenation Operator (+) String literals cannot span multiple lines Combines string literals with other data types for printing Example (C#): String hello = "Hello";

String there = "there"; String greeting = hello + ' ' + there; Console.WriteLine(greeting ); Output: Hello there 02/11/2020 CSE 1321 Module 2 15 Pseudocode CLASS CountDown BEGIN METHOD Main() BEGIN s1 "Three... " s2 "Two... " s3 "One... "

s4 "Zero... " PRINT(s1 + s2 + s3 + s4 + "Liftoff!") PRINTLINE() PRINTLINE("Houston, we have a problem.") END Main END CountDown Output: Three... Two... One... Zero... Liftoff! Houston, we have a problem. 02/11/2020 CSE 1321 Module 2 Ps 16 Java // 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. 02/11/2020

CSE 1321 Module 2 17 C# using System; class CountDown { public static void Main(string[] args) { string s1 = "Three... "; string s2 = "Two... "; string s3 = "One... "; string s4 = "Zero... "); Console.WriteLine(s1 + s2 + s3 + s4 + "Liftoff!"); Console.WriteLine("Houston, we have a problem. "); } }

Output: Three... Two... One... Zero... Liftoff! Houston, we have a problem. 02/11/2020 CSE 1321 Module 2 18 C++ #include using namespace std; int main() { cout << "Three..." << "Two..."; cout << "One..." << "Zero...";

cout << "Liftoff!" << endl; cout << "Houston, we have..." << endl; return 0; } Output: Three... Two... One... Zero... Liftoff! Houston, we have a problem. 02/11/2020 CSE 1321 Module 2 19 Escape Sequences Printing and escape sequence prints a special character in an output string. Common escape sequences:

\b is backspace. (e.g B\bsecz\bret prints what?) \t is tab \n newline \r carriage return \ double quote \ single quote \\ backslash 02/11/2020 CSE 1321 Module 2 20 Java 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 friends At this point in our relationship. 02/11/2020 CSE 1321 Module 2

21 C# // Escape sequences class 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."); } } 02/11/2020

CSE 1321 Module 2 22 C++ #include using namespace std; int main() { cout << "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." << endl; return 0; } 02/11/2020

CSE 1321 Module 2 23 Variables A variable is a name for a location in memory used to hold a data value. A variable must be declared by specifying the variable's name and the type of information that it will hold. Examples: int total; // chunk of memory named total int count, temp, result; // three variables Multiple variables can be created in one declaration 02/11/2020 CSE 1321 Module 2

24 Pseudocode // Prints the number of keys on a piano. CLASS PianoKeys BEGIN METHOD Main() BEGIN CREATE keys 88 PRINT("A piano has " + keys + " keys.") END Main END PianoKeys Output: A piano has 88 keys. 02/11/2020 CSE 1321 Module 2 Ps

25 Java // Prints the number of keys on a piano. public class PianoKeys { public static void main (String[] args) { int keys = 88; //declare and initialize System.out.println ("A piano has " + keys + " keys."); } } Output: A piano has 88 keys. 02/11/2020 CSE 1321 Module 2

26 C# // Prints the number of keys on a piano using System; class PianoKeys { public static void Main (string[] args) { int keys = 88; //declare and initialize Console.WriteLine("A piano has " + keys + " keys."); } } Output: A piano has 88 keys. 02/11/2020 CSE 1321 Module 2 27

C++ #include using namespace std; int main() { int keys = 88; cout << "A piano has " << keys << " keys." << endl; return 0; } Output: A piano has 88 keys 02/11/2020 CSE 1321 Module 2

28 Conventions Naming Variables Names of variables: should be meaningful reflect the data they will store. variable names will self document the program small variable names are NOT more efficient avoid extremely long names Avoid names similar to keywords 02/11/2020 CSE 1321 Module 2 29 Assignment

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! 02/11/2020 CSE 1321 Module 2 30 Pseudocode

// Print the number of sides of several geometric shapes. CLASS Geometry BEGIN METHOD Main() BEGIN CREATE sides 7 PRINTLINE("A heptagon has " + sides + " sides.") CREATE sides 10 PRINTLINE("A decagon has " + sides + " sides.") CREATE sides 12 PRINTLINE("A dodecagon has " + sides + " sides.") END Main END Geometry Output: A heptagon has 7 sides. A decagon has 10 sides. A dodecagon has 12 sides.

02/11/2020 CSE 1321 Module 2 Ps 31 Java // Print the number of sides of several geometric shapes. public class Geometry { public static void main (String[] args) { int sides = 7; // declare and initialize System.out.println ("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides."); sides = 12; // assignment statement System.out.println ("A dodecagon has " + sides + " sides."); } }

02/11/2020 CSE 1321 Module 2 32 C# // Print the number of sides of several geometric shapes. using System; class Geometry { public static void Main (string[] args) { int sides = 7; // declare and initialize Console.WriteLine("A heptagon has " + sides + " sides."); sides = 10; // assignment statement Console.WriteLine("A decagon has " + sides + " sides."); sides = 12; // assignment statement Console.WriteLine("A dodecagon has " + sides + " sides.");

} } 02/11/2020 CSE 1321 Module 2 33 C++ #include using namespace std; int main() { int sides = 7; // Original variable and assignment cout << "A heptagon has " << sides << " sides" << endl; sides = 10; // Reassign the same variable cout << "A decagon has " << sides << " sides" << endl; sides = 12; // Reassign the same variable

cout << "A dodecagon has " << sides << " sides" << endl; return 0; } 02/11/2020 CSE 1321 Module 2 34 Constants Values that cannot change. A value must be assigned before the constant is used. Three reasons: They give meaning to otherwise unclear literal values. For example, MAX_LOAD means more than the literal 250

Program maintenance. If a constant is used in multiple places, its value need only be updated in one place. Avoid errors by other programmers 02/11/2020 CSE 1321 Module 2 35 Constants Java and C# Use all CAPITAL LETTERS for constants and separate words with an underscore: Java: final double TAX_RATE = .05; C# and C++: const double TAX_RATE = .05; C++ only: #define TAX_RATE .05 Declare constants at the top of the program

02/11/2020 CSE 1321 Module 2 36 Data Types Data type tells compiler: How much memory to allocate Format in which to store data Types of operations you will perform on data Compiler monitors use of data C#, Java, and C++ are "strongly typed" languages. That is, variables cannot be implicitly coerced to unrelated types 02/11/2020 CSE 1321 Module 2

37 Data Types 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, well define our own data types! 02/11/2020 CSE 1321 Module 2 38

Why so many types? Difference is in amount of memory reserved for each (i.e the size of the value stored) 1. A float only has 7 significant digits 2. Signed numbers have both positive and negative values 3. Unsigned numbers are >= 0 02/11/2020 CSE 1321 Module 2 39 Static v. Dynamic Typing Static type checking (C#, C++ and Java) Static type checking occurs during compilation Requires you to declare variable types before you use them Dynamic type checking (e.g. Python)

Dynamic type checking occurs while program is running Does not require you to declare the data types of your variables before you use them Python uses dynamic typing, but is also is strongly typed, as the interpreter keeps track of all variables types. 02/11/2020 CSE 1321 Module 2 40 Literal Numbers 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 F double interestRate = 0.725; double avogadroNumber = +6.022E23; 02/11/2020 CSE 1321 Module 2 41 char Data Type Two common ways to hold characters:

1. ASCII (8 bits) how many characters in English? 2. Unicode (16 bits) how many characters in Mandarin? 3. Unicode is most commonly used Example declarations: char finalGrade = A; // NOTE single quotes char newline, tab, doubleQuotes; 02/11/2020 CSE 1321 Module 2 42 boolean Data Type Two values only: true false

Used for decision making or as "flag" variables Example declarations: bool isEmpty = false; //in C# and C++ boolean passed = true; //in Java 02/11/2020 CSE 1321 Module 2 43 Summary 1. Variable declaration indicates its type and possibly its initial value. 2. A value is assigned using assignment operator. 3. A constant value doesnt 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. 02/11/2020 CSE 1321 Module 2 44

Recently Viewed Presentations

  • Case Records & Work File CASE RECORD /

    Case Records & Work File CASE RECORD /

    MORD issued indicative framework for case records / work file under MGNREGS vide circular F. No. J-11017/6/2016-MGNREGA -VII dated 19th July, 2017 Standard list of 21 documents emphasized in the circular. State/UTs can add more documents based on their State...
  • DRPSCI - nbm.nic.in

    DRPSCI - nbm.nic.in

    One representative from each participating unit can travel by AC-II Tier (train) or Economy Class (air). Local participants to be paid @ Rs. 12/- per km as freight charge upto 50 km. One MSE would be allowed reimbursement for maximum...
  • Slayt 1

    Slayt 1

    Kim, Allah'a, meleklerine, peygamberlerine, Cebrail'e ve Mikâil'e düşman olursa bilsin ki Allah da inkârcı kâfirlerin düşmanıdır. Bakara 98. Muhammed, ancak bir peygamberdir. Ondan önce de peygamberler gelip geçmiştir. Şimdi o ölür veya öldürülürse gerisingeriye (eski ...
  • Medical Marijuana/Cannabis How, when, why should it fit

    Medical Marijuana/Cannabis How, when, why should it fit

    Dr. Eric Cassell: The Nature of Suffering and the Goals of Medicine " A state of severe distress associated with events that threaten the intactness of personhood or the interconnected physical, social, spiritual, an psychological aspect of self"
  • Slide 1

    Slide 1

    Arial MS Pゴシック Wingdings 3 Tahoma AEB-New Microsoft Graph Chart Microsoft Office Excel Chart 2007 Grocery SuperStudy 2007 Grocery SuperStudy Average Weekly Sales Per Item Weekly Movement Per SKU Percent SKU's Making Money Profitability Return on Investment Return on Investment...
  • Quí te por de la MQ - CSIC

    Quí te por de la MQ - CSIC

    Qui té por de la MQ ?. Discusió científico-filosòficaen cinc ActesiFinale, a mésd'un(important) Pre-acte. Emili Elizalde. ICE-CSIC, IEEC, UAB
  • Unit 3-Cultural Patterns and Processes

    Unit 3-Cultural Patterns and Processes

    Cultural Ecology is the field that studies the relationship between the natural environment and culture. ... Golf. What sports fan are you? Sports. ... Displaying a relatively few differences in grammar and vocabulary. Language group. Evolved from Latin. Spain, Portugal,...
  • cogsim.3nets.dvi

    cogsim.3nets.dvi

    Left over fromunits.. Bias weight. General cell excitability is plastic, regardless of particular synaptic inputs (weights). See review by Mozzachido & Byrne, 2010 TINS on non-synapticplasticity.