Chapter 2 Overview of C++. 2 Overview  2.1 Language Elements  2.2 Reserved Words & Identifiers  2.3 Data Types & Declarations  2.4 Input/Output 

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

Introduction to C Programming
1 Chapter 2 C++ Basics. 2 Overview Variables, Constants and Assignments (2.1) Input and Output (2.2) Data Types and Expressions (2.3) Simple Flow of Control.
© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5/e Starting Out with C++: Early Objects 5 th Edition Chapter 2 Introduction.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Overview of C++ Chapter 2 in both books programs from books keycode for lab: get Program 1 from web test files.
Chapter 2: Introduction to C++.
Introduction to C Programming
Admin Office hours 2:45-3:15 today due to department meeting if you change addresses during the semester, please unsubscribe the old one from the.
Basic Elements of C++ Chapter 2.
Introduction to C++ Programming
COMPUTER SCIENCE I C++ INTRODUCTION
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
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
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
1 C++ Programming Basics Chapter 2 Lecture CSIS 10A.
CHAPTER 4: CONTROL STRUCTURES - SEQUENCING 10/14/2014 PROBLEM SOLVING & ALGORITHM (DCT 1123)
C++ Programming: Basic Elements of C++.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
CHAPTER 7 DATA INPUT OUTPUT Prepared by: Lec. Ghader R. Kurdi.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 C++ Basics.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 2- 1 June 3, June 3, 2016June 3, 2016June 3, 2016 Azusa, CA.
C++ How to Program, Late Objects Version, 7/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to C++ Basic Elements of C++. C++ Programming: From Problem Analysis to Program Design, Fourth Edition2 The Basics of a C++ Program Function:
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Two: Fundamental Data Types Slides by Evan Gallagher.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
CS Jan 2007 Chapter 2 sections 1, 2, 4 – 6, 8,
CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output Samples.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Chapter 2 of C++ How to Program, 10/e © by Pearson Education, Inc. All Rights Reserved.
Bill Tucker Austin Community College COSC 1315
© by Pearson Education, Inc. All Rights Reserved.
Chapter 2: Basic Elements of C++
Chapter Topics The Basics of a C++ Program Data Types
Data Types and Expressions
Chapter 2 C++ Basics. Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow.
Chapter 2 C++ Basics.
Data Types and Expressions
Basics (Variables, Assignments, I/O)
Introduction to C++ Programming
Chapter 2 Introduction to C++ Programming
Chapter 2: Introduction to C++
Basic Elements of C++.
Basics (Variables, Assignments, I/O)
Basic Elements of C++ Chapter 2.
Basics (Variables, Assignments, I/O)
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Variables, Identifiers, Assignments, Input/Output
Expressions and Assignment
Chapter 2: Introduction to C++.
Primitive Types and Expressions
Presentation transcript:

Chapter 2 Overview of C++

2 Overview  2.1 Language Elements  2.2 Reserved Words & Identifiers  2.3 Data Types & Declarations  2.4 Input/Output  2.5 Form of a C++ Program  2.6 Arithmetic Expressions  2.8 Common Programming Errors

3 Variables and Assignments  Variables are like small blackboards  We can write a number on them  We can change the number  We can erase the number  C++ variables are names for memory locations  We can write a value in them  We can change the value stored there  We cannot erase the memory location  Some value is always there

4 Identifiers  Variables names are called identifiers  Choosing variable names  Use meaningful names that represent data to be stored  First character must be  a letter  the underscore character  Remaining characters must be  letters  numbers  underscore character

5 Keywords  Keywords (also called reserved words)  Are used by the C++ language  Must be used as they are defined in the programming language  Cannot be used as identifiers

6 Comments  The target audience of your programs is NOT the compiler  You should write code for another programmer  To make your code more readable, you can add comments which describe the purpose of code  Text on a line after // is ignored by the compiler  Text between /* and */ is ignored by the compiler

7 Declaring Variables  Before use, variables must be declared  Tells the compiler the type of data to store Examples: int number_of_bars; float one_weight, total_weight;  int is an abbreviation for integer  could store 3, 102, 3211, -456, etc.  number_of_bars is of type integer  float can represents a number with a fractional component  could store 1.34, 4.0, , etc.  one_weight and total_weight are both of type float

8 Declaring Variables int main() { … int sum; //here the declaration is just before use sum = score1 + score2; … return 0; } int main() { int sum; //here the declaration is at the start … sum = score1 + score2; … return 0; }

9 Assignment Statements  An assignment statement changes the value of a variable  total_weight = one_weight + number_of_bars;  total_weight is set to the sum one_weight + number_of_bars  Assignment statements end with a semi-colon  The single variable to be changed is always on the left of the assignment operator '='  On the right of the assignment operator can be  Literals -- age = 21;  Variables -- my_cost = your_cost;  Expressions -- circumference = diameter * ;

10 Assignment Statements and Algebra  The '=' operator in C++ is not an equal sign  The following statement cannot be true in algebra number_of_bars = number_of_bars + 3;  In C++ it means the new value of number_of_bars is set to the previous value of number_of_bars plus 3

11 Initializing Variables  Declaring a variable does not give it a value  Giving a variable a value at declaration is initializing the variable  Un-initialized variables can be given their first value with a separate assignment statement  float mpg; // declare the variable mpg = 26.3; // assign it a value  It is more efficient, and better style, to declare and initialize together instead of using 2 statements  float mpg=26.3, area=0.0;

12 Concept Check  Can you  Declare and initialize two integers variables to zero  The variables are named feet and inches  Declare and initialize two variables, one int and one float  Both should be initialized to the appropriate form of 5  Give good variable names for identifiers to store  the speed of an automobile  an hourly pay rate  the highest score on an exam

13 Input and Output  A data stream is a sequence of data  Typically in the form of characters or numbers  An input stream is data for the program to use  Typically originates  at the keyboard  at a file  An output stream is the program’s output  Destination is typically  the monitor  a file

14 Output using cout  cout is an output stream sending data to the monitor  The insertion operator << inserts data into cout  Example: cout << number_of_bars << " candy bars" << endl;  This line sends two items to the monitor  The value of number_of_bars  The string literal " candy bars" Notice the space before the ‘c’ in candy The << endl causes a new line to be started following the ‘s’ in bars  A new insertion operator is used for each item of output

15 Examples Using cout  This produces the same result as the previous sample cout << number_of_bars; cout << " candy bars" << endl;  Here arithmetic is performed in the cout statement cout << "Total cost is $" << (price + tax);  String literals are enclosed in float quotes ("Hello")  Don’t use two single quotes (')  A blank space can also be inserted with cout << " ";

16 Include Directives  Include Directives add library files to our programs  To make the definitions of the cin and cout available to the program: #include  Using Directives include a collection of defined names  To make the names cin and cout available to our program: using namespace std;

17 Input Using cin  cin is an input stream bringing data from the keyboard  The extraction operator (>>) removes data to be used  Example: cout > number_of_bars; cin >> one_weight;  This code prompts the user to enter data then reads two data items from cin  The first value read is stored in number_of_bars  The second value read is stored in one_weight  Data is separated by spaces when entered

18 Reading Data From cin  Multiple data items are separated by spaces  Data is not read until the enter key is pressed  Allows user to make corrections  Example: cin >> v1 >> v2 >> v3;  Requires three space separated values  User might type

19 Designing Input and Output  Prompt the user for input that is desired  cout statements provide instructions cout > age;  Notice the absence of a new line before using cin  Echo the input by displaying what was read  Gives the user a chance to verify data cout << age << " was entered." << endl;

20 Data Types and Expressions  We use 2 and 2.0 to denote different representations of the value 2  A whole number such as 2 is of type int  A real number such as 2.0 is of type float (actually 2.0 is not quite a float, but the details of C++types are not critical to our current dicsussion)  Numbers of type int are stored with perfect precision  Numbers of type float may be stored as approximate values due to limitations on number of significant digits that can be represented  This is known as round-off error

21 Constants  A variable is a named container of a particular type of data, whose value can be changed  A constant is also a named container of a particular type of data, with 2 differences  It must be initialized when declared  Its value cannot be changed  Constants are used to hold values that don't change while the program is running, but may need to be updated in future versions

22 Declaring a const  Declaring a const is much like declaring any other variable with initialization, plus the keyword const const float pi = ;  Why not just type ?  If you later want to use a different approximation for pi, you would have to change all instances of in your program  With a named const, you can make the change once

23 Constants vs. Literals  A constant is a named container of a particular type of data, whose value cannot be changed  A literal is an instance of an actual value of a particular data type const float tax_rate = 0.051; float tax, income = 50000; tax = tax_rate * income;

24 Writing Integer Literals  Type int does not contain decimal points  Examples:

25 Writing Floating-Point Literals  Literals for type float can be written in two ways  Simple form must include a decimal point  Examples:  Floating Point Notation (Scientific Notation)  Examples: 3.41e1 means e17 means e-6means  Number left of e does not require a decimal point  Exponent cannot contain a decimal point

26 Type Compatibilities  In general store values in variables of the same type  This is a type mismatch: int int_variable; int_variable = 2.99;  int_variable will contain the value 2, not 2.99  The.99 is cut off in a process known as truncation  the compiler may produce a warning

27 Arithmetic  Arithmetic is performed with operators  + for addition  - for subtraction  * for multiplication  / for division  Example: storing a product in the variable total_weight total_weight = one_weight * number_of_bars;

28 Results of Operators  Arithmetic operators can be used with any numeric type, or combination of numeric types  An operand is a number or variable used as input by the operator  Result of an operator depends on the types of operands  If both operands are int, the result is int  If one or both operands are float, the result is a floating point value

29 Division of floats  Division with at least one operator of type float produces the expected results  float divisor, dividend, quotient; divisor = 3; dividend = 5; quotient = dividend / divisor;  quotient = …  Result is the same if either dividend or divisor is of type int

30 Division of Integers  Be careful with the division operator!  int / int produces an integer result (true for variables or numeric constants) int dividend, divisor, quotient; dividend = 5; divisor = 3; quotient = dividend / divisor;  The value of quotient is 1, not 1.666…  Integer division does not round the result, the fractional part is discarded!

31 Integer Remainders  % operator gives the remainder from integer division: int dividend, divisor, remainder; dividend = 5; divisor = 3; remainder = dividend % divisor; The value of remainder is 2

32 Arithmetic Expressions  Use spacing to make expressions readable  Which is easier to read? x+y*z or x + y * z  Precedence rules for operators are the same as used in your algebra classes  Use parentheses to alter the order of operations x + y * z ( y is multiplied by z first) (x + y) * z ( x and y are added first)

33 Operator Shorthand  Increment & Decrement  ++ count = count + 1; becomes ++count; //or count++  -- bonus = bonus-1; becomes bonus--; //or –bonus  There is a slight difference between ++a and a++  Such details are covered in CS 251

34 Common Errors  Syntax Errors  Your code violates the rules of C++  Your logic might be good: add a semi-colon, and the program might work perfectly  The compiler detects syntax errors at compile time; the program won't compile if it contains syntax errors  Run-Time Errors  Your program tries to execute an operation (or call a function) on input for which is was not designed  Division by zero

35 Common Errors  Logic Errors  The program compiles successfully  The program runs without error  But the program doesn't do what it is supposed to do  Debugging  The act of removing errors from a program  The compiler lists all syntax errors, these are easy to debug  Only careful testing/evaluation will reveal logic errors  Run-time errors generally indicate one of a handful of programming mistakes, each indicated its own error

36 Debugging Help  Syntax Errors  The compiler gives hints  Sometimes the actual error is one or more lines before the one reported by the compiler  Logical Errors  Use of cout to display the value of intermediate results can help you find logical errors  Runtime Errors  cout can help you identify which line caused the error