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

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

Command-line interface DOS Graphical User interface (GUI) -- Windows

- Developed by Bjarne Stroustrup at AT&T Bell Laboratories

Chapter 2 C++ Fundamentals

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

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

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

Programming. C++ Basics

Objectives. In this chapter, you will:

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++

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

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

Why Is Repetition Needed?

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

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

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

The C++ Language. Arizona State University 1

LECTURE 02 INTRODUCTION TO C++

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

CS242 COMPUTER PROGRAMMING

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

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

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

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

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

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

Computer Science II Lecture 1 Introduction and Background

Creating a C++ Program

BITG 1233: Introduction to C++

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 2: Overview of C++

Introduction to Programming using C++

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

A First Program - Greeting.cpp

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

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

The following expression causes a divide by zero error:

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.1

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

Problem Solving: Storyboards for User Interaction

From Pseudcode Algorithms directly to C++ programs

Computer Science II Lecture 2 Strings, Vectors and Recursion

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

CS2255 HOMEWORK #1 Fall 2012

2 nd Week Lecture Notes

COMP322 - Introduction to C++ Lecture 01 - Introduction

UNIT- 3 Introduction to C++

Chapter 1 INTRODUCTION

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

6.096 Introduction to C++ January (IAP) 2009

CS101 PLEDGED SPRING 2001

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

Computer Programming : C++

Perfect square. #include<iostream> using namespace std; int main(){ int a=1; int square; while(true){ } cout<<square<<endl; }

READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Do not start the test until instructed to do so!

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

CSCE Practice Midterm. Data Types

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

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

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

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

CSC 1300 Exam 4 Comprehensive-ish and Structs

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

do { statements } while (condition);

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

Boolean Algebra Boolean Algebra

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Introduction to Programming

UNIT-2 Introduction to C++

Introduction to Computer Science Midterm 3 Fall, Points

Programming Language. Functions. Eng. Anis Nazer First Semester

Introduction to Programming EC-105. Lecture 2

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

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

Chapter 2. C++ Basics

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Exercise 1.1 Hello world

MODULE 02: BASIC COMPUTATION IN JAVA

Fundamentals of Programming CS-110. Lecture 2

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Exercise: Inventing Language

Pointers, Dynamic Data, and Reference Types

Pointers II. Class 31

Chapter 2: Introduction to C++

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

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

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 4

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 5

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; 6 Major = "Computer Science";

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; 7

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; 8

Comments It is good practice to include descriptive comments in code. Comments may explain the purpose of a declared identifier, or of a statement or group of statements that perform some calculation, or input or output. int quizscore; int numquizzes = 0; int totalpoints; double quizaverage; // score on a quiz // number of quizzes given // sum of all quiz scores // average of all quiz scores /* Read in quiz scores until the user enters one that's negative. */ cin >> quizscore; while (quizscore >= 0) { totalpoints = totalpoints + quizscore; numquizzes = numquizzes + 1; cin >> quizscore; } // Calculate average quiz score: quizaverage = double(totalpoints) / numquizzes; 9

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; // Declaring and Initializing Person s first name, last name, middle initial const string FIRST = "Herman"; const string LAST = "Smith"; const char MIDDLE = G ; 10

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; cout << firstlast << endl; lastfirst = LAST + ", " + FIRST + " "; cout << "Name in first-last format is " << endl << lastfirst << MIDDLE <<. << endl; } return 0; 11

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

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. - Compiler prints error messages, but usually continues to compile. 13

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. 14

Categories of Programming Errors Execution (runtime) errors: - Error occurs while the program is running, causing the program to "crash" (terminate abnormally. - Frequently an illegal operation of some sort. Arithmetic errors like an attempt to divide by zero, Access violations: try to use some resource like a memory address that is not allocated to it. - Code compiles and links without errors. - 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 computer but not on 15 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. 16

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 17

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. 18

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 19

Algorithm Repeat four times Output five whiterows Output five blackrows 20

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 21

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; 22

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; 23

Is a year a leap year? Problem You need to write a set of instructions that can be used to determine whether a year is a leap year. The instructions must be very clear because they are to be used by a class of fourth graders, who have just learned about multiplication and division. They plan to use the instructions as part of an assignment to determine whether any of their relatives were born in a leap year. 24

Leap Year Algorithm Prompt the user to enter a four-digit year Read the year If IsLeapYear Write Year is a leap year Otherwise Write Year is not a leap year 25

What is a Leap Year? Every year whose number is divisible by four without a remainder is a leap year Except the full centuries, which, to be leap years, must be divisible by 400 without a remainder. If not so divisible they are common years. 1900, therefore, is not a leap year 26

IsLeapYear Algorithm Divide the year by 4 If the remainder isn't zero, Return false(the year is not a leap year) Otherwise divide the year by 10 and If the remainder isn't 0, Return true(the year is a leap year) Otherwise, divide the year by 400 and If the remainder isn't 0 Return false(the year is not a leap year) Otherwise, Return true(the year is a leap year) 27

C++ Program //****************************************************** // LeapYear program // This program inputs a year and prints whether the year // is a leap year or not //****************************************************** #include <iostream> // Access output stream using namespace std; bool IsLeapYear(int); // Access cout, endl, cin // Prototype for subalgorithm int main() 28

Body of Main { } int year; // Year to be tested cout << "Enter a year AD, for example, 1997." << endl; // Prompt for input cin >> year; // Read year if(isleapyear(year)) // Test for leap year cout << year << " is a leap year." << endl; else cout << year << " is not a leap year." << endl; return 0; // Indicates successful // completion 29

IsLeapYear bool IsLeapYear(int year) // IsLeapYear returns true if year is a leap year and // false otherwise { if(year % 4!= 0) // Is year not divisible by 4? return false; // If so, can't be a leap year else if(year % 100!= 0) // Is year not a multiple of 100? return true; // If so, is a leap year else if(year % 400!= 0) // Is year not a multiple of 400? return false; // If so, then is not a leap year else return true; // Is a leap year } 30