J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. The Fundamentals of C++ Basic programming elements and concepts.

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

C++ Basics Variables, Identifiers, Assignments, Input/Output.
Types and Variables. Computer Programming 2 C++ in one page!
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Sixth.
Data types and variables
The Fundamentals of C++ Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc.
Overview of C++ Chapter 2 in both books programs from books keycode for lab: get Program 1 from web test files.
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
By Dr. Awad Khalil Computer Science & Engineering Department
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Seventh.
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
Input & Output: Console
C Tokens Identifiers Keywords Constants Operators Special symbols.
C-Language Keywords(C99)
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
The Fundamentals of C++ Chapter 2: Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Week 1 Algorithmization and Programming Languages.
C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
C++ Programming: Basic Elements of C++.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
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++
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Sixth.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
Chapter 2: Introduction to C++. Outline Basic “Hello World!!” Variables Data Types Illustration.
1 Comments Allow prose or commentary to be included in program Importance Programs are read far more often than they are written Programs need to be understood.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ for Engineers and Scientists Second Edition
Objects Variables and Constants. Our Scuba Problem #include // cin, cout, > using namespace std; int main() { const double FEET_PER_ATM = 33.0, LBS_PER_SQ_IN_PER_ATM.
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.
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)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
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)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
C++ Lesson 1.
Asst.Prof.Dr. Tayfun ÖZGÜR
Variables, Identifiers, Assignments, Input/Output
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Introduction to C++
Data types Data types Basic types
Chapter 2: Introduction to C++
Reserved Words.
Chapter 2: Introduction to C++
C++ Basics.
2.1 Parts of a C++ Program.
Basics of ‘C’.
Variables, Identifiers, Assignments, Input/Output
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
COMS 261 Computer Science I
Chapter 2: Introduction to C++.
COMS 261 Computer Science I
The Fundamentals of C++
Presentation transcript:

J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. The Fundamentals of C++ Basic programming elements and concepts

Ch 2 / Foil 2 l Program statement n Definition n Declaration n Action l Executable unit n Named set of program statements n Different languages refer to executable units by different names –Subroutine: Fortran and Basic –Procedure: Pascal –Function : C++ Program Organization

Ch 2 / Foil 3 Program Organization l C++ program n Collection of definitions, declarations and functions n Collection can span multiple files l Advantages n Structured into small understandable units n Complexity is reduced n Overall program size decreases

Ch 2 / Foil 4 Object l Object is a representation of some information Name Values or properties –Data members Ability to react to requests (messages)!! –Member functions l When an object receives a message, one of two actions are performed Object is directed to perform an action Object changes one of its properties

Ch 2 / Foil 5 // Program: Display greetings // Author(s): Ima Programmer // Date: 1/25/1999 #include using namespace std; int main() { cout << "Hello world!" << endl; return 0; } A First Program - Greeting.cpp Preprocessor directives Insertion statement Ends executions of main() which ends program Comments Function Function named main() indicates start of program Provides simple access

Ch 2 / Foil 6 Greeting Output

Definitions Extraction Definition with initialization Area.cpp #include using namespace std; int main() { // Extract length and width cout << "Rectangle dimensions: "; float Length; float Width; cin >> Length >> Width; // Compute and insert the area float Area = Length * Width; cout << "Area = " << Area << " = Length " << Length << " * Width " << Width << endl; return 0; }

Ch 2 / Foil 8 Area.cpp Output

Ch 2 / Foil 9 Comments l Allow prose or commentary to be included in program l Importance n Programs are read far more often than they are written n Programs need to be understood so that they can be maintained l C++ has two conventions for comments // single line comment (preferred) /* long comment */ (save for debugging) l Typical uses n Identify program and who wrote it n Record when program was written n Add descriptions of modifications

Ch 2 / Foil 10 Fundamental C++ Objects l C++ has a large number of fundamental or built-in object types l The fundamental object types fall into one of three categories n Integers objects n Floating-point objects n Character objects Z 5 P 3.14

Ch 2 / Foil 11 Integer Object Types The basic integer object type is int The size of an int depends on the machine and the compiler –On PCs it is normally 16 or 32 bits l Other integers object types short: typically uses less bits long: typically uses more bits l Different types allow programmers to use resources more efficiently l Standard arithmetic and relational operations are available for these types

Ch 2 / Foil 12 Integer Constants l Integer constants are positive or negative whole numbers l Integer constant forms n Decimal n Octal (base 8) –Digits 0, 1, 2, 3, 4, 5, 6, 7 n Hexadecimal (base 16) –Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f l Consider n 31 oct and 25 dec

Ch 2 / Foil 13 Specifying Syntax l Need n A notation for exactly expressing a programming language element –Notation is describing the programming language –Notation is not part of the programming language l Notation must be able to describe n Elements that have several forms n Elements that are –Required –Optional –Repeated

Ch 2 / Foil 14 Notation Conventions l Parentheses () n Anything surrounded by parentheses must be used l Braces [] n Anything surrounded by brackets is optional l Vertical line | n Elements on either side of the line are acceptable l Ellipsis... n The pattern established before the ellipsis continues l Specifier n Name of a language element

Ch 2 / Foil 15 Notation Examples l NonZeroDigit n 1 | 2 |... 9 l Digit n 0 | NonZeroDigit l OctalDigit n 0 | 1 |... 7 l HexDigit n 0 | 1 |... 9 | A | B |... F | a | b |... f l Digits n NonZeroDigit [ Digit... Digit ]

Ch 2 / Foil 16 Decimal Constants l Examples n 97 n 40000L n n 23a (illegal) l The type of the constant depends on its size, unless the type specifier is used

Ch 2 / Foil 17 Octal Constants l Examples n 017 n L n l n n 0482 (illegal) l The type of the constant depends on its size, unless the type specifier is used

Ch 2 / Foil 18 Hexadecimal Constants l Letters represent the hex digits a or A - 10d or D - 13 b or B - 11e or E - 14 c or C - 12f or F - 15 l Examples n 0x2C n 0XAC12EL l The type of the constant depends on its size, unless the type specifier is used

Ch 2 / Foil 19 Character Object Types Character type char is related to the integer types l Characters are encoded using a scheme where an integer represents a particular character l ASCII is the dominant encoding scheme n Examples – ' ' encoded as 32 – '+' encoded as 43 – 'A' encoded as 65 – 'Z' encoded as 90 – 'a' encoded as 97 – 'z' encoded as 122

Ch 2 / Foil 20 Character Operations l Arithmetic and relational operations are defined for characters types 'a' < 'b' is true '4' > '3' is true 'b' + 2 produces the number that represents 'd' '8' - '3' produces 5 l Arithmetic with characters needs to be done with care '9' + 3 produces the number that represents '<'

Ch 2 / Foil 21 Character Constants l Explicit characters within single quotes 'a' 'D' '*' l Special characters - delineated by a backslash \ n Two character sequences (sometimes called escape codes) within single quotes n Important special characters '\t' denotes a tab '\n' denotes a new line '\\' denotes a backslash

Ch 2 / Foil 22 Escape Codes CharacterASCII NameSequence newlineNL\n horizontal tabHT\t backspaceBS\b form feedFF\f alert or bellBEL\a carriage returnCR\r vertical tabVT\v backslash \ \\ single quote' \' double quote"\" question mark?\?

Ch 2 / Foil 23 Literal String Constants l A literal string constant is a sequence of zero or more characters enclosed in double quotes "Are you aware?\n" l Individual characters of string are stored in consecutive memory locations The null character ('\0') is appended to strings so that the compiler knows where in memory strings ends

Ch 2 / Foil 24 Floating-Point Object Types l Floating-point object types represent real numbers n Integer part n Fractional part l The number breaks down into the following parts n integer part n fractional part l C++ provides three floating-point object types float double long double

Ch 2 / Foil 25 Floating-Point Constants l Standard decimal notation n Digits. Digits [ f | F | l | L] F l Standard scientific notation n Digits. Digits Exponent [ f | F | l | L] n Where –Exponent is (e | E) [ + | -] Digits 1.45E e-3L When not specified, floating-point constants are of type double

Ch 2 / Foil 26 Names l Used to denote program values or components l A valid name is a sequence of n Letters (upper and lowercase) n Digits –A name cannot start with a digit n Underscores –A name should not normally start with an underscore l Names are case sensitive n MyObject is a different name than MYOBJECT l There are two kinds of names n Keywords n Identifiers

Ch 2 / Foil 27 Keywords l Keywords are words reserved as part of the language –int, return, float, double n They cannot be used by the programmer to name things n They consist of lowercase letters only n They have special meaning to the compiler

Ch 2 / Foil 28 Keywords asm do if return typedef auto double inline short typeid bool dynamic_cast int signed typename break delete long sizeof union case else mutable static unsigned catch enum namespace static_cast using char explicit new struct virtual class extern operator switch void const false private template volatile const_cast float protected this wchar_t continue for public throw while default friend register true union delete goto reinterpret_cast try unsigned

Ch 2 / Foil 29 Identifiers l Identifiers should be n Short enough to be reasonable to type (single word is norm) –Standard abbreviations are fine (but only standard abbreviations) n Long enough to be understandable –When using multiple word identifiers capitalize the first letter of each word l Examples n Min n Temperature n CameraAngle n CurrentNbrPoints

Ch 2 / Foil 30 Definitions l All objects that are used in a program must be defined l An object definition specifies n Type n Name l A common definition form n Our convention is one definition per statement !

Ch 2 / Foil 31 Examples char Response; int MinElement; float Score; float Temperature; int i; int n; char c; float x; Objects are uninitialized with this definition form (Value of a object is whatever is in its assigned memory location)

Ch 2 / Foil 32 Arithmetic Operators l Common n Addition+ n Subtraction- n Multiplication* n Division/ n Mod% l Note n No exponentiation operator n Single division operator n Operators are overloaded to work with more than one type of object Write m*x + b not mx + b

Ch 2 / Foil 33 Integer Division l Integer division produces an integer result n Truncates the result l Examples 3 / 2 evaluates to 1 4 / 6 evaluates to 0 10 / 3 evaluates to 3

Ch 2 / Foil 34 Mod l Produces the remainder of the division l Examples 5 % 2 evaluates to 1 12 % 4 evaluates to 0 4 % 5 evaluates to 4

Ch 2 / Foil 35 Operators and Precedence l Consider mx + b Consider m*x + b which of the following is it equivalent to (m * x) + b m * (x + b) l Operator precedence tells how to evaluate expressions l Standard precedence order n ()Evaluate first, if nested innermost done first n * / %Evaluate second. If there are several, then evaluate from left-to-right n + -Evaluate third. If there are several, then evaluate from left-to-right

Ch 2 / Foil 36 Operator Precedence l Examples * 3 / * 4 / * 5 % * 3 / 4 (1 + 3) * ((2 + 4 * 6) * 3) / 2 + 2

Ch 2 / Foil 37 Defining and Initializing l When an object is defined using the basic form, the memory allotted to it contains random information n Good idea to specify its desired value at the same time –Exception is when the next statement is an extraction for the object l Our convention is one definition per statement !

Ch 2 / Foil 38 Examples int FahrenheitFreezing = 32; char LetterGrade = 'A'; cout << "Slope of line: "; float m; cin >> m; cout << "Intercept: "; float b; cin >> b; cout << "X value of interest: "; float x; cin >> x; float y = (m * x) + b;

// Program 2.11: Compute velocity of car #include using namespace std; int main() { cout << "All inputs are integers!\n"; cout << "Start milepost? "; int StartMilePost; cin >> StartMilePost; cout << "Elapsed time (hours minutes seconds)? ”; int EndHour; int EndMinute; int EndSecond; cin >> EndHour >> EndMinute >> EndSecond; cout << "End milepost? ";

int EndMilePost; cin >> EndMilePost; float ElapsedTime = EndHour + (EndMinute / 60.0) + (EndSecond / ); int Distance = EndMilePost - StartMilePost; float Velocity = Distance / ElapsedTime; cout << "\nCar traveled " << Distance << " miles in "; cout << EndHour << " hrs " << EndMinute << " min " << EndSecond << " sec\n"; cout << "Average velocity was " << Velocity << " mph " << endl; return 0; }