CPS120: Introduction to Computer Science Lecture 8.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
Introduction to C Programming
Basic Elements of C++ Chapter 2.
Objectives You should be able to describe: Data Types
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
CPS120: Introduction to Computer Science Computer Math: Signed Numbers.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
Chapter 2: Using Data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CPS120: Introduction to Computer Science
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
CPS120: Introduction to Computer Science Operations Lecture 9.
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
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.
Computer Math CPS120 Introduction to Computer Science Lecture 4.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Chapter 2 Variables.
CPS120: Introduction to Computer Science Introduction to C++
CPS120: Introduction to Computer Science Variables and Constants.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
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
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
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.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
CPS120 Introduction to Computer Science Exam Review.
Computer Math CPS120 Introduction to Computer Science Lecture 7.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Bill Tucker Austin Community College COSC 1315
Chapter 2 Variables.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 2: Introduction to C++
BASIC ELEMENTS OF A COMPUTER PROGRAM
Tokens in C Keywords Identifiers Constants
Basic Elements of C++.
Chapter 2: Introduction to C++
Basic Elements of C++ Chapter 2.
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,
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Basics of ‘C’.
Chapter 2 Variables.
C++ Data Types Data Type
Lectures on Numerical Methods
Expressions and Assignment
Chapter 2: Introduction to C++.
CPS120: Introduction to Computer Science
Primitive Types and Expressions
Chapter 2 Variables.
Variables in C Topics Naming Variables Declaring Variables
Variables and Constants
Presentation transcript:

CPS120: Introduction to Computer Science Lecture 8

Comparing the Conventions

Sign-magnitude Operations Addition of two numbers in sign-magnitude is carried out using the usual conventions of binary arithmetic –If both numbers are the same sign, we add their magnitude and copy the same sign –If different signs, determine which number has the larger magnitude and subtract the other from it. The sign of the result is the sign of the operand with the larger magnitude –If the result is outside the bounds of –2 n+1 to +2 n-1 –1, an overflow results

Two’s Complement Convention A positive number is represented using a procedure similar to sign-magnitude To express a negative number 1.Express the absolute value of the number in binary 2.Change all the zeros to ones and all the ones to zeros (called “complementing the bits”) 3.Add one to the number obtained in Step 2 –The range of negative numbers is one larger than the range of positive numbers –Given a negative number, to find its positive counterpart, use steps 2 & 3 above

Two’s Complement Operations Addition: –Treat the numbers as unsigned integers The sign bit is treated as any other number –Ignore any carry on the leftmost position Subtraction –Treat the numbers as unsigned integers –If a "borrow" is necessary in the leftmost place, borrow as if there were another “invisible” one- bit to the left of the minuend

Overflows in Two’s Complement The range of values in two’s-complement is –2 n+1 to +2 n-1 –1 Results outside this band are overflows In all overflow conditions, the sign of the result of the operation is different than that of the operands If the operands are positive, the result is negative If the operands are negative, the result is positive

One’s Complement Devised to make the addition of two numbers with different signs the same as two numbers with the same sign Positive numbers are represented in the usual way For negatives –STEP 1: Start with the binary representation of the absolute value –STEP 2: Complement all of its bits

One's Complement Operations –Treat the sign bit as any other bit –For addition, carry out of the leftmost bit is added to the rightmost bit – end-around carry

Error Detection: Even Parity Bytes Transmitted Parity Block B I T Bytes Received Parity Block B I T

A Simple C++ Program Comments //Simple C++ Program // // Purpose: To demonstrate the // parts of a simple C++ program Compiler Directive #include Main Functionmain ( ) Braces{ Statementscout << "This is a simple program "; return 0; }

Sample Comments At the start of the program /************************************************** ** Miles Per Gallon** ** Programmer: Paul J. Millis** ** Purpose: Calculate mile per gallon and price per mile** ** given miles, gallons and gas price** *************************************************/ Within specific lines of code float PricePerMile = 0.00;//store the price per mile float MilesPerGallon = 0.0;//stores the miler per gallon achieved

Compiler Directives Instructions to the compiler rather than part of the C++ language –Most common directive is #include For Example: #include –A.h file is a header file. It serves as a link between program code and standard C++ code needed to make programs run

Functions A function is a block of code that carries out a specific task Every C++ program has a main function that executes when a program initiates –Includes open parenthesis to designate a function –Ends with a return 0; statement

Braces Mark the beginning and ending of blocks of related code –Every opening brace must have a closing brace

Semicolons There must be a semicolon after every statement –To tell the compiler that the statement is complete –Function definitions and compiler directives are exempt

Uppercase or Lowercase Be careful to use the same combination of uppercase or lowercase lettering when you enter source code Commands and other reserved words are all lower case

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

Data Types - Whole Numbers 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.

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 –A double variable can store a number as high as 1.7 x –A double variable can store a number with up to 15 digits of precision (significant digits)

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.

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

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

Other Data Types unsigned char, short, unsigned int, long, and unsigned long for whole numbers float and long double for decimal values

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

Variable Names 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 Remember, C++ is completely case sensitive

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

Conventions for Naming Variables Use a conventional method of making your variables easy to read at a quick glance. For example: 1.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) 2.Separate successive words with underscore characters ( _ ) (eg. semester_grade, card_value) 3.Hungarian notation Begin with type (eg. iTestScore)

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 programindeterminate value –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";

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

Use of Constants (Literals) Numeric 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 – Start with letter or underscore – Can’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 = const double PA_SALES_TAX = 0.06 const int SPEED_OF_LIGHT = ; // commas can't be used here

Type Compatibilities You cannot store a value of one type in a variable of a different type – a type mismatch occurs 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);

Common Arithmetic Operators + for addition - for subtraction * for multiplication / for division % for modulus (like finding the remainder of a division problem)

Order of Operations Obey the order of operations –Perform the following mathematical operations in this order: Parentheses, Exponentiation, Multiplication, Division, Addition and Subtraction –Multiplication and division are of equal precedence, so you must work left to right within an algebraic expression –The modulus operator (%) has the same precedence as * and / but is higher in precedence than + and -. –Addition and subtraction work left to right within an algebraic expression as well –Use parentheses if necessary to override the order of operations in order to produce the desired result