Module 2 - Part 1 Variables, Assignment, and Data Types

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Advertisements

Chapter 1: Computer Systems
C++ Basics Variables, Identifiers, Assignments, Input/Output.
The Java Programming Language
Outline Java program structure Basic program elements
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Prepared by Uzma Hashmi Instructor Information Uzma Hashmi Office: B# 7/ R# address: Group Addresses Post message:
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
© 2006 Pearson Education Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition.
Java Language and SW Dev’t
Input & Output: Console
System development with Java Lecture 2. Rina Errors A program can have three types of errors: Syntax and semantic errors – called.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 2: Java Fundamentals
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
SE-1010 Dr. Mark L. Hornick 1 Variables & Datatypes.
Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; Copyright © 2012 Pearson Education,
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Chapter 2 Data and Expressions Part One. © 2004 Pearson Addison-Wesley. All rights reserved2-2/29 Data and Expressions Let's explore some other fundamental.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
Basic Types, Variables, Literals, Constants. What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet)
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
C++ Lesson 1.
Asst.Prof.Dr. Tayfun ÖZGÜR
Variables, Identifiers, Assignments, Input/Output
Lecture 2A Data Types Richard Gesick
Working with Java.
Data types Data types Basic types
Lecture 2 Data Types Richard Gesick.
Lecture 2: Data Types, Variables, Operators, and Expressions
CS180 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
University of Central Florida COP 3330 Object Oriented Programming
Computing with C# and the .NET Framework
Reserved Words.
Escape Sequences What if we wanted to print the quote character?
Data and Expressions Part One
Starting JavaProgramming
null, true, and false are also reserved.
2.1 Parts of a C++ Program.
Introduction to Java Programming
An overview of Java, Data types and variables
Chapter 1: Computer Systems
Keywords.
Variables, Identifiers, Assignments, Input/Output
Units with – James tedder
Units with – James tedder
Chapter 2 Create a Chapter 2 Workspace Create a Project called Notes
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
Focus of the Course Object-Oriented Software Development
Chapter 2: Introduction to C++.
Module 2 - Part 1 Variables, Assignment, and Data Types
Module 2 Variables, Assignment, and Data Types
Module 2 - Part 1 Variables, Assignment, and Data Types
Java Basics Data Types in Java.
Chap 2. Identifiers, Keywords, and Types
Java Programming Presented by Dr. K. SATISH KUMAR,
Module 2 - Part 1 Variables, Assignment, and Data Types
Presentation transcript:

Module 2 - Part 1 Variables, Assignment, and Data Types 7/3/2019 CSE 1321 Module 2

Motivation To learn the basic elements of programming: Declaring variables (a named chunk of memory) Data types (the kind of info you’re going to store) Assignment (putting values into a chunk of memory) String literals Review printing 7/3/2019 CSE 1321 Module 2

Topics Program Structure Character Strings Variables Assignments Constants Primitive Data Types 7/3/2019 CSE 1321 Module 2

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 7/3/2019 CSE 1321 Module 2 4

Comments Comments are just notes that explain the program to yourself and others. They’re 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 7/3/2019 CSE 1321 Module 2

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. 7/3/2019 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 7/3/2019 CSE 1321 Module 2

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 7/3/2019 CSE 1321 Module 2

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 7/3/2019 CSE 1321 Module 2

White Space Spaces, blank lines, and tabs are called white space: Used to separate words and symbols in a program. Extra white space is ignored A valid program syntax can be formatted many ways Use whitespace enhance readability, using consistent indentation 7/3/2019 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) 7/3/2019 CSE 1321 Module 2 11

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

Printing strings in C# (review) Console.WriteLine (“Whatever you are, be a good one.”); Console represents the Operating System’s console WriteLine is a “function” to push data to the console 7/3/2019 CSE 1321 Module 2 13

Printing strings in C++ (review) cout << “Whatever you are, be a good one.” << endl; cout is called a stream (an output stream) You “push” things into cout endl is short for “end line” 7/3/2019 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 7/3/2019 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. Ps 7/3/2019 CSE 1321 Module 2 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. 7/3/2019 CSE 1321 Module 2 17

C# Output: 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. 7/3/2019 CSE 1321 Module 2 18

C++ Output: cout << "One..." << "Zero..."; #include <iostream> 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. 7/3/2019 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 7/3/2019 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. 7/3/2019 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."); } 7/3/2019 CSE 1321 Module 2 22

C++ #include <iostream> 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; } 7/3/2019 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 7/3/2019 CSE 1321 Module 2 24

Ps 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. Ps 7/3/2019 CSE 1321 Module 2 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. 7/3/2019 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. 7/3/2019 CSE 1321 Module 2 27

C++ #include <iostream> using namespace std; int main() { int keys = 88; cout << "A piano has " << keys << " keys." << endl;    return 0; } Output: A piano has 88 keys 7/3/2019 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 7/3/2019 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! 7/3/2019 CSE 1321 Module 2 30

Pseudocode // Print the number of sides of several geometric shapes. CLASS Geometry BEGIN METHOD Main() 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. Ps 7/3/2019 CSE 1321 Module 2 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."); } 7/3/2019 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."); } 7/3/2019 CSE 1321 Module 2 33

C++ #include <iostream> 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; } 7/3/2019 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 7/3/2019 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 7/3/2019 CSE 1321 Module 2 36

Data Types Data type tells compiler: Compiler monitors use of data 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 7/3/2019 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, we’ll define our own data types! 7/3/2019 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) A float only has 7 significant digits Signed numbers have both positive and negative values Unsigned numbers are >= 0 7/3/2019 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. 7/3/2019 CSE 1321 Module 2

Literal Numbers int testGrade = 100; byte ageInYears = 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 F double interestRate = 0.725; double avogadroNumber = +6.022E23; 7/3/2019 CSE 1321 Module 2 41

char Data Type Two common ways to hold characters: ASCII (8 bits) – how many characters in English? Unicode (16 bits) – how many characters in Mandarin? Unicode is most commonly used Example declarations: char finalGrade = ‘A’; // NOTE single quotes char newline, tab, doubleQuotes; 7/3/2019 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 7/3/2019 CSE 1321 Module 2 43

Summary Variable declaration indicates its type and possibly its initial value. A value is assigned using assignment operator. A constant value doesn’t change 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. Primitive data types include integer, floating point, character, boolean, and decimal. 7/3/2019 CSE 1321 Module 2