CPS120: Introduction to Computer Science

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Structure of a C program
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
Data types and variables
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
String Escape Sequences
Basic Elements of C++ Chapter 2.
The Data Element. 2 Data type: A description of the set of values and the basic set of operations that can be applied to values of the type. Strong typing:
Objectives You should be able to describe: Data Types
CPS120: Introduction to Computer Science Lecture 8.
Chapter 8 High-Level Programming Languages (modified by Erin Chambers)
The Data Element. 2 Data type: A description of the set of values and the basic set of operations that can be applied to values of the type. Strong typing:
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
C Tokens Identifiers Keywords Constants Operators Special symbols.
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 2: Using Data.
Chapter 8 High-Level Programming Languages. 8-2 Chapter Goals Describe the translation process and distinguish between assembly, compilation, interpretation,
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Course Title: Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 03 Conditional statement 1 BY ADEEL ANJUM (MSc-cs, CCNA,WEB DEVELOPER)
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Computer Engineering 1 st Semester Dr. Rabie A. Ramadan 3.
CONSTANTS Constants are also known as literals in C. Constants are quantities whose values do not change during program execution. There are two types.
Copyright Curt Hill Variables What are they? Why do we need them?
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
CPS120: Introduction to Computer Science Variables and Constants.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
Chapter # 2 Part 2 Programs And data
Chapter Topics The Basics of a C++ Program Data Types
BASIC ELEMENTS OF A COMPUTER PROGRAM
Variables A variable is a placeholder for a value. It is a named memory location where that value is stored. Use the name of a variable to access or update.
Multiple variables can be created in one declaration
Chapter 2: Introduction to C++
IDENTIFIERS CSC 111.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Variables in C Topics Naming Variables Declaring Variables
Basics of ‘C’.
C++ Data Types Data Type
Chapter 2: Java Fundamentals
Variables in C Topics Naming Variables Declaring Variables
High Level Programming Languages
Chapter # 2 Part 2 Programs And data
Chapter 2: Java Fundamentals
Chapter 2: Introduction to C++.
The Data Element.
Primitive Types and Expressions
Chap 2. Identifiers, Keywords, and Types
The Data Element.
Variables in C Topics Naming Variables Declaring Variables
Variables in C Topics Naming Variables Declaring Variables
Variables in C Topics Naming Variables Declaring Variables
Variables and Constants
Programming Fundamental-1
Variables in C Topics Naming Variables Declaring Variables
Presentation transcript:

CPS120: Introduction to Computer Science Variables and Constants

Anatomy of a C++ Program //Simple C++ Program // // Purpose: To demonstrate the // parts of a simple C++ program #include <iostream.h> main ( ) { cout << "This is a program "; return 0; } Comments // Compiler Directive # Main Function ( ) Braces { } Statements ;

Variables Used to store values in virtually every computer program Used for “remembering” things during program execution Variables have names, types and values Values can change during execution

Languages and Data Types Strong typing: the requirement that only a value of the proper type can be stored into a variable A data type is a description of the set of values and the basic set of operations that can be applied to values of the type

Data Types Integer numbers Real numbers Characters Boolean values Strings

Declarations A declaration is a statement that associates an identifier with a variable, an action, or some other entity within the language that can be given a name so that the programmer can refer to that item by name

Declarations in Various Languages

Data Types You need to first choose an appropriate data type when you use a variable.Values can either be: whole numbers decimal numbers letters (i.e. characters) whole words (i.e. string values For example, if you want to store coffee in a container, you would use a Styrofoam cup and not a Dixie cup. Otherwise, you would burn your hands. Likewise, if you want to store chicken soup in a container, you would use a bowl and not a plate. Otherwise, the soup would spill off of the edge of the plate.

Choosing a Type Most computer languages have a select number of different data types You must select the proper data type for each variable that you use in a program in order to program efficiently This decreases memory (RAM) usage This increases the speed of your program

Integers The range varies depending upon how many bytes are assigned to represent an integer value Some high-level languages provide several integer types of different sizes Operations that can be applied to integers are the standard arithmetic and relational operators

Data Types - Whole Numbers In C++, to store whole numbers in a variable, we use a variable of the int data type. An int variable uses 4 bytes of memory. An int variable can store a number as low as -2,147,483,648. An int variable can store a number as high as 2,147,483,647.

Other Data Types unsigned char, short, unsigned int, long, and unsigned long for whole numbers

Real Numbers Like the integer data type, the range varies depending on the number of bytes assigned to represent a real number Many high-level languages have two sizes of real numbers The operations that can be applied to real numbers are the same as those that can be applied to integer numbers

Data Types - Decimal Numbers To store decimal numbers in a variable, we use a variable of the double data type A double variable uses 8 bytes of memory A double variable can store a number as low as -1.7 x 10308 A double variable can store a number as high as 1.7 x 10308 A double variable can store a number with up to 15 digits of precision (significant digits)

Other Data Types float and long double for decimal values

Characters It takes one byte to represent characters in the ASCII character set Two bytes to represent characters in the Unicode character set Our English alphabet is represented in ASCII, which is a subset of Unicode

Characters Applying arithmetic operations to characters doesn’t make much sense Comparing characters does make sense, so the relational operators can be applied to characters The meaning of “less than” and “greater than” when applied to characters is “comes before” and “comes after” in the character set

Data Types - Characters To store a letter or a single character (such as #, $, *, etc.), we use a variable of the char data type. A char variable only uses 1 byte of memory. A char variable can only hold one letter, digit, or character.

Strings A string is a sequence of characters considered as one data value For example: “This is a string.” Containing 17 characters: one uppercase letter, 12 lowercase letters, three blanks, and a period The operations defined on strings vary from language to language They include concatenation of strings and comparison of strings in terms of lexicographic order

Data Types – Words / Phrases To store a word or phrase (string value), we use a variable that is a string Technically string is not a data type You can think of it as a data type for now

Boolean The Boolean data type consists of two values: true and false Not all high-level languages support the Boolean data type If a language does not, then you can simulate Boolean values by saying that the Boolean value true is represented by 1 and false is represented by 0

Data Types – True and False The data type bool is useful to store true and false values Alternatively, we can simply use an int variable with either a 1 value (to represent true) or a 0 value (to represent false) if necessary

Using Variables in C++ Variables must be declared before they are used in C++. Get into the habit of doing this at the top of your functions char grade; // a students semester grade int numStudents; // number of students in our class double price; // price of item string userName; // user's name

Remember A reserved word is a word in a language that has special meaning Case-sensitive means that uppercase and lowercase letters are not considered the same Remember, C++ is completely case sensitive

Variable Names in C++ Variable names are technically known as identifiers Choose your own variable names but you must be careful to use valid ones. Otherwise, the compiler will be confused and errors will result. When choosing your variable names: do not use keywords that are defined in the programming language (Reserved Words) do not include spaces or other disallowed characters do not use more than 31 characters do begin the identifier with a letter Use meaningful variable names Rate, RATE and rate are different variable

Conventions for Naming Variables Use a conventional method of making your variables easy to read at a quick glance. For example: Begin variable identifiers with lowercase letters (eg. score) if you wish to use more than one word within the identifier, you must capitalize the following words or parts of words (eg. semesterGrade, testScore) Separate successive words with underscore characters ( _ ) (eg. semester_grade, card_value) Hungarian notation Begin with type (eg. iTestScore)

Common Reserved Words break case char const default do double else extern float for if int long return switch void while

Initializing Variables C++ does not automatically initialize all variables to the value 0 If you do not initialize a variable to a certain value, the variable will have an indeterminate value that can corrupt the logic of your program You should usually initialize your variables at the same time that you declare them. This is done with a declaration statement that is also an initialization statement int numberOfPizzas = 3;           double monthlyCarPayment = 685; char letterGrade = 'A'; string firstName = "Paul"; Garbage values can corrupt the logic of your program and cause errors when you least expect Note: char values must be surrounded with single quotes and string values must be surrounded with double quotes. Open up vc_demo1.cpp // Variable declarations float StartingMileage = 0.0; // stores mileage at beginning of trip float EndingMileage = 0.0; // stores mileage at end of trip float MilesTravelled = 0.0; // stores the total distance float GallonsOfGas = 0.0; // stores the amount of fuel used float PriceOfGas = 0.00; // stores the amount paid for gas float PricePerMile = 0.00; // store the price per mile float MilesPerGallon = 0.0; // stores the miler per gallon achieved

Assignment statement Assignment statement: an action statement (not a declaration) that says to evaluate the expression on the right-hand side of the symbol and store that value into the place named on the left-hand side Note this is not a variable declaration. It is a program statement in the body of the program.

Sample Assignment Statements Declares and initializes

Constants Named constant: A location in memory, referenced by an identifier, that contains a data value that cannot be changed

Constants Sometimes you need to use the same value many times throughout a program. In this case, it is proper to use a constant rather than a variable Constants allow you to give a name to a value used several times in a program The value never changes For example, if you need to use the number 6% many times because of the fact that the Michigan tax rate is 6%then it would be wise and efficient to use a constant named TAXRATE that is initialized to the value .06 rather than to type the number .06 itself throughout your program. Using the constant named TAXRATE makes your program easier for others to understand. It also makes the program easy to upgrade down the road. For example, if the government were to change the TAXRATE, then it would be easier to update your program if you had used the constant TAXRATE.

Use of Constants (Literals) Numeric 5 3.14159 -17.29 Characters 'a' '7' '*' Strings (a sequence of symbols) "I will be an better person "

Naming Constants Constants are defined in a way that is similar to variables Select a data type and give the constant a name Any valid identifier name can be used to name a constant do start with letter or underscore don’t use reserved words

Conventions for Naming Constants Traditionally, all uppercase letters have been used when naming constants Use the underscore character ( _ ) between consecutive words. This allows other programmers to be able to "pick out" your constants at a quick glance Examples: const double PI = 3.14159 const double PA_SALES_TAX = 0.06 const int SPEED_OF_LIGHT = 299792458; // commas can't be used here Open up vc_demo2.cpp

Type Compatibilities You cannot store a value of one type in a variable of a different type – a type mismatch occurs Promotion occurs automatically You can typecast Supply the name of the data type you want to use to interpret the variable followed by the variable placed in parenthesis C = PI * float (diameter); Promotion: int answer, I; float x; i =3; x= 0.5; answer = x * I;