Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

Similar documents
Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

C++ Programming: From Problem Analysis to Program Design, Third Edition

- Developed by Bjarne Stroustrup at AT&T Bell Laboratories

Objectives. In this chapter, you will:

6.096 Introduction to C++ January (IAP) 2009

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

LECTURE 02 INTRODUCTION TO C++

Chapter 2 Basic Elements of C++

Creating a C++ Program

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Lab # 02. Basic Elements of C++ _ Part1

The C++ Language. Arizona State University 1

III. Check if the divisors add up to the number. Now we may consider each of these tasks separately, assuming the others will be taken care of

UNIT- 3 Introduction to C++

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Computer Programming : C++

CS201 - Introduction to Programming Glossary By

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Short Notes of CS201

Programming. C++ Basics

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

CSc Introduction to Computing

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Chapter 2 C++ Fundamentals

Variables. Data Types.

BITG 1233: Introduction to C++

Lecture 2 Tao Wang 1

CS242 COMPUTER PROGRAMMING

Variables and numeric types

BTE2313. Chapter 2: Introduction to C++ Programming

A Fast Review of C Essentials Part I

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

DEPARTMENT OF MATHS, MJ COLLEGE

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

REVIEW. The C++ Programming Language. CS 151 Review #2

A First Program - Greeting.cpp

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

UNIT-2 Introduction to C++

CS2141 Software Development using C/C++ C++ Basics

Fundamentals of Programming CS-110. Lecture 2

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Introduction to Programming EC-105. Lecture 2

UEE1302 (1102) F10: Introduction to Computers and Programming

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

BASIC ELEMENTS OF A COMPUTER PROGRAM

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Chapter 2: Overview of C++

Types, Values, Variables & Assignment. EECS 211 Winter 2018

1. In C++, reserved words are the same as predefined identifiers. a. True

Exercise: Inventing Language

Programming in C++ 4. The lexical basis of C++

Exercise: Using Numbers

2 nd Week Lecture Notes

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

C Language, Token, Keywords, Constant, variable

CHAPTER 3 BASIC INSTRUCTION OF C++

Review of Important Topics in CS1600. Functions Arrays C-strings

Input And Output of C++

C: How to Program. Week /Mar/05

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Differentiate Between Keywords and Identifiers

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Unit 3. Constants and Expressions

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

CSCI 123 Introduction to Programming Concepts in C++

CS201 Some Important Definitions

Chapter 2 - Introduction to C Programming

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CSCI 1061U Programming Workshop 2. C++ Basics

Chapter 8 - Notes User-Defined Simple Data Types, Namespaces, and the string Type

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Syntax and Variables

Maciej Sobieraj. Lecture 1

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Pointers, Dynamic Data, and Reference Types

Your first C++ program

Exercise 1.1 Hello world

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

Chapter 3. Numeric Types, Expressions, and Output

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

VARIABLES AND CONSTANTS

Integer Data Types. Data Type. Data Types. int, short int, long int

Full file at

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Chapter 2. Outline. Simple C++ Programs

Transcription:

Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems 1

Chapter 2 Topics Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation Output Statements C++ Program Comments 2

An Important Problem Solving Technique Divide and conquer -- break up large problems into manageable units Functions 3

A C++ program is a collection of one or more functions There must be a function called main() Execution always begins with the first statement in function main() Any other functions in your program are subprograms and are not executed until they are called 4

Program With Several Functions main function square function cube function 5

Program With Three Functions #include <iostream> int Square(int); int Cube(int); // Declares these two // value-returning functions using namespace std; int main() { cout << The square of 27 is << Square(27)<< endl; // Function call } cout << The cube of 27 is << Cube(27)<< endl; // Function call return 0; 6

Rest of Program int Square(int n) { return n * n; } int Cube(int n) { return n * n * n; } 7

Output of program The square of 27 is 729 The cube of 27 is 19683 8

Shortest C++ Program type of returned value name of function int main() { return 0; } 9

What is in a heading? type of returned value name of function says no parameters int main( ) 10

Block(Compound Statement) A block is a sequence of zero or more statements enclosed by a pair of curly braces { } SYNTAX { } Statement (optional)... 11

Every C++ function has 2 parts int main() { return 0; } heading body block 12

Syntax and Semantics syntax (grammar) rules that specify how valid instructions (constructs) are written semantics rules that specify the meaning of syntactically valid instructions The syntax of an assignment statement requires that you have: l-value = expression; where l-value is something, like a variable, whose value can be changed, and expression is a valid C++ expression. The semantic rule for an assignment statement specifies that the value of the expression on the right side is stored in the l-value on the left side. For example: const int totaldays = 25567; // NOT an l-value int dayspassed; // l-values int daysleft; dayspassed = 17094; daysleft = totaldays - dayspassed; 13

C++ Reserved Words The C++ Standard specifies certain symbols and words as the official "vocabulary" of the C++ language. These reserved words (and symbols) are preempted by the C++ language definition and may only be used in the manner the language rules specify. Fortunately the number of reserved words is relatively small (< 300). Here's a sample: bool const double for return break continue else if struct case default enum int switch char delete false long typedef class do float new while There is a complete list of C++ reserved words in Appendix A of the Dale book. Note that all the C++ reserved words are strictly lower-case. Your C++ code will be more readable if you choose mixedcase or upper-case identifiers. 14

Directives Directives provide instructions to the pre-processor, which "edits" your C++ language code before it is read by the C++ compiler. Directives are most commonly used to incorporate standard header files into your program: #include <iostream> // embed the file "iostream" here Directives may also be used to declare identifiers: #define NUMBER 100 // replace every occurrence of NUMBER // with the value 100 15

What is an Identifier? An identifier is the name used for a data object(a variable or a constant), or for a function, in a C++ program Beware: C++ is a case-sensitive language Using meaningful identifiers is a good programming practice 16

Identifiers An identifier must start with a letter or underscore, and be followed by zero or more letters (A-Z, a-z), digits(0-9), or underscores VALID age_of_dog PrintHeading taxratey2k ageofhorse NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat 17

More About Identifiers Some C++ compilers recognize only the first 32 characters of an identifier as significant Then these identifiers are considered the same: age_of_this_old_rhinoceros_at_my_zoo age_of_this_old_rhinoceros_at_my_safari Consider these: Age_Of_This_Old_Rhinoceros_At_My_Zoo age_of_this_old_rhinoceros_at_my_zoo 18

C++ Data Types simple structured integral enum floating array struct union class char short int long bool float double long double address pointer reference 19

C++ Simple Data Types simple types integral floating char short int long bool enum float double long double unsigned 20

Standard Data Types in C++ Integral Types represent whole numbers and their negatives declared as int, short, or long Floating Types represent real numbers with a decimal point declared as float, or double Character Types represent single characters declared as char 21

The Simple Data Types C++ has only four simple data types (classes of data): integer - positive or negative whole number: 5280, -47, 0, +93143234 - three subtypes: int, short, long real - positive or negative decimal number: 3.14159, 98.6, -3.45E04 - three subtypes: float, double, long double character - letter, digit, punctuation, special symbols: 'x', ' ', '!', '\n' - one subtype: char Boolean* - logical value (true or false) - one subtype: bool 22

More on the Simple Data Types Integer representation: - short is typically 2 bytes, int and long are typically 4 bytes. - int values range roughly from 2 billion to 2 billion. Decimal number representation: - float is typically 4 bytes, double is typically 8 bytes. - double stores (at best) approximately 15 significant digits, float about 7 - normally use double for increased accuracy of computed results. - double values range roughly from 10 308 to 10 308. - most decimal values cannot be stored EXACTLY, even as a double, so use integer types when possible. - decimal values are stored in a different way than integer values (even 1.0!). Character representation: - char variable holds a single character at a time. - stored value is a binary code representing the character, usually ASCII. - char variables occupy 1 byte. Boolean value representation: - bool variables typically occupy 1 byte. 23

What is a Variable? A variable is a location in memory that can be referred to by an identifier and in which a data value that can be changed is stored Declaring a variable means specifying both its name and its data type 24

What Does a Variable Declaration Do? int ageofdog; float taxrate; char middleinitial; A declaration tells the compiler to allocate enough memory to hold a value of this data type and to associate the identifier with this location 4 bytes for taxratey2k 1 byte for middleinitial 25

Initialization Declaring a variable does not (usually) automatically provide it with a specific starting value. A variable is just a name for a location in the computer's memory. Memory cannot be "empty", it always stores some value. For all practical purposes, the variable declarations on the previous slide create variables whose initial values are random garbage, whatever happens to be at the corresponding location in memory when the program is executed. Using the value of a variable that has not yet been properly set is one of the most common sources of errors in programs. Therefore, it is good practice to always give every newly declared variable a specific initial value. This can be combined with the declaration or accomplished via a later assignment: int Weight = 0, Height = 0, Length = 0; double ClassAverage = 0.0, GPA = 0.0; string Major; 26 Major = "Computer Science";

C++ Data Type String A string is a sequence of characters enclosed in double quotes Sample string values Hello Year 2000 1234 The empty string(null string)contains no characters and is written as 27

More About Type String A string is not a built-in(standard)type It is a programmer-defined data type It is provided in the C++ standard library String operations include Comparing 2 string values Searching a string for a particular character Joining one string to another 28

What is a Named Constant? A named constant is a location in memory that can be referred to by an identifier and in which a data value that cannot be changed is stored Valid constant declarations const string STARS = **** ; const float NORMAL_TEMP = 98.6; const char BLANK = ; const int VOTING_AGE = 18; const float MAX_HOURS = 40.0; 29

Giving a Value to a Variable Assign(give)a value to a variable by using the assignment operator = Variable declarations string firstname; char middleinitial; char letter; int ageofdog; Valid assignment statements firstname = Fido ; middleinitial = X ; letter = middleinitial; ageofdog = 12; 30

What is an Expression in C++? An expression is a valid arrangement of variables, constants, and operators In C++ each expression can be evaluated to compute a value of a given type The value of the expression 9 + 5 is 14 31

Assignment Operator Syntax Variable = Expression Done second Result is stored in variable Expression is evaluated Done first 32

String Concatenation(+) Concatenation is a binary operation that uses the + operator At least one of the operands must be a string variable or named string constant-- the other operand can be a string literal or a char variable, literal, or constant 33

Concatenation Example const string WHEN = Tomorrow ; const char EXCLAMATION =! ; string message1; string message2; message1 = Yesterday ; message2 = and ; message1 = message1 + message2 + WHEN + EXCLAMATION; 34

Insertion Operator(<<) Variable cout is predefined to denote an output stream that goes to the standard output device(display screen) The insertion operator << called put to takes 2 operands The left operand is a stream expression, such as cout The right operand is an expression of a simple type or a string constant 35

Output Statements SYNTAX cout << Expression << Expression...; These examples yield the same output: cout << The answer is ; cout << 3 * 4; cout << The answer is << 3 * 4; 36

Is compilation the first step? No; before your source program is compiled, it is first examined by the preprocessor that removes all comments from source code handles all preprocessor directives--they begin with the # character such as #include <iostream> This include tells the preprocessor to look in the standard include directory for the header file called iostream and insert its contents into your source code 37

No I/O is built into C++ Instead, a library provides an output stream executing program ostream Screen 38

Using Libraries A library has 2 parts Interface(stored in a header file)tells what items are in the library and how to use them Implementation(stored in another file)contains the definitions of the items in the library #include <iostream> Refers to the header file for the iostream library needed for use of cout and endl. 39

Function Concept in Math f(x) = 5 x - 3 Function definition Name of function Parameter of function When x = 1, f(x)= 2 is the returned value When x = 4, f(x)= 17 is the returned value Returned value is determined by the function definition and by the values of any parameters 40

C++ Program // ****************************************************** // PrintName program // This program prints a name in two different formats // ****************************************************** #include <iostream> #include <string> // for cout and endl // for data type string using namespace std; const string FIRST = Herman ; // Person s first name const string LAST = Smith ; // Person s last name const char MIDDLE = G ; // Person s middle initial 41

C++ Code Continued int main() { string firstlast; // Name in first-last format string lastfirst; // Name in last-first format firstlast = FIRST + + LAST; cout << Name in first-last format is << endl << firstlast << endl; lastfirst = LAST +, + FIRST + ; cout << Name in first-last format is << endl << lastfirst << MIDDLE <<. << endl; } return 0; 42

Output of Program Name in first-last format is Herman Smith Name in last-first-initial format is Smith, Herman G. 43

Categories of Programming Errors Language syntax (compilation) errors: - Error is in the form of the statement: misspelled word, unmatched parenthesis, comma out of place, etc. - Error is detected by the compiler (at compile time). - Compiler cannot correct error, so no object file is generated. - Compiler prints error messages, but usually continues to compile. 44

Categories of Programming Errors Linking errors: - Error is typically in the form of the declaration or implementation or call of a function. - Error may also result from including the wrong header file. - Error is detected by the linker (after the compiler has produced an object file). - Linker cannot correct error, so no executable file is generated. - Linker prints error messages, but usually 45 continues link analysis.

Categories of Programming Errors Execution (runtime) errors: - Error occurs while the program is running, causing the program to "crash" (terminate abnormally) and usually producing an error message from the operating system. - Error is frequently an illegal operation of some sort. The most common are arithmetic errors like an attempt to divide by zero, and access violations when the program tries to use some resource like a memory address that is not allocated to it. - Program source code compiles and links without errors no help there. - Unfortunately, some operating systems do not reliably detect and respond to some kinds of execution errors. In that case, an incorrect program may appear to function correctly on one 46 computer but not on another.

Categories of Programming Errors Logic errors: - Error occurs while the program is running, causing the production of incorrect results, but not necessarily a runtime "crash". - Program source code compiles and links without errors no help there. - Logic errors are detected by checking results computed by the program. - The cause(s) of the error must be determined by a logical analysis of the error and the source code. This must be done by the developer. This is the hardest type of error to deal with. 47

Analyze the problem statement Design a solution Enter/edit source code Find error in source code check syntax Compile/link source code Compiler/Linker errors? no yes Find cause of runtime error check code check input data rethink analysis/design or Test the program Execution errors? no Results incorrect? yes yes no Find cause of logic error check code check input data rethink analysis/design Success! At least with this input. or 48

Creating a Chessboard Problem Your college is hosting a chess tournament, and the people running the tournament want to record the final positions of the pieces in each game on a sheet of paper with a chessboard preprinted on it. Your job is to write a program to preprint these pieces of paper. The chessboard is an eight-by-eight pattern of squares that alternate between black and white, with the upper left square being white. You need to print out squares of light characters(spaces)and dark characters(such as *)in this pattern to form the chessboard. 49

Chessboard Constants NameValue Function BLACK '********' Characters forming one line of a black square WHITE ' ' Characters forming one line of a white square Variables Name Data Type Description whiterow string A row beginning with a white square blackrow string A row beginning with a black square 50

Algorithm Repeat four times Output five whiterows Output five blackrows 51

C++ Program //***************************************************** // Chessboard program // This program prints a chessboard pattern that is // built up from basic strings of white and black // characters. //***************************************************** #include <iostream> #include <string> using namespace std; const string BLACK = "********"; // Define black square line const string WHITE = " "; // Define white square line 52

C++ Program int main() { string whiterow; // White square beginning row string blackrow; // Black square beginning row // Create a white-black row whiterow = WHITE + BLACK + WHITE + BLACK + WHITE + BLACK + WHITE + BLACK; // Create a black-white row blackrow = BLACK + WHITE + BLACK + WHITE + BLACK + WHITE + BLACK + WHITE; 53

C++ Program } // Print five white-black rows cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; // Print five black-white rows cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; // Print rest of the rows... return 0; 54