Engineering Problem Solving with C++, Etter/Ingber

Similar documents
Chapter 2. Outline. Simple C++ Programs

ANSI C Programming Simple Programs

Operations. Making Things Happen

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

Chapter 2: Basic Elements of C++

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++ Objectives. Objectives (cont d.) A C++ Program. Introduction

BITG 1233: Introduction to C++

3.1. Chapter 3: The cin Object. Expressions and Interactivity

Chapter 3. Numeric Types, Expressions, and Output

The C++ Language. Arizona State University 1

I/O Streams and Standard I/O Devices (cont d.)

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Objectives. In this chapter, you will:

Chapter 4: Basic C Operators

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

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

CHAPTER 3 BASIC INSTRUCTION OF C++

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

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

Chapter 2: Introduction to C++

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

LECTURE 02 INTRODUCTION TO C++

C++ Programming Lecture 11 Functions Part I

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Expressions, Input, Output and Data Type Conversions

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Lecture 3 Tao Wang 1

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

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

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

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

CS2141 Software Development using C/C++ Stream I/O

VARIABLES & ASSIGNMENTS

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

Lecture 4 Tao Wang 1

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

Chapter 3: Expressions and Interactivity

Introduction to C++ Introduction and History. Characteristics of C++

Introduction to Programming

Chapter 1 Introduction to Computers and C++ Programming

UNIT- 3 Introduction to C++

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

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

Programming. C++ Basics

Chapter 3 - Notes Input/Output

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

What we will learn about this week:

Introduction to C++ (Extensions to C)

A First Program - Greeting.cpp

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

Chapter 2 Basic Elements of C++

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

Window s Visual Studio Output

Topic 2: C++ Programming fundamentals

by Pearson Education, Inc. All Rights Reserved. 2

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

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

Programming with C++ as a Second Language

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

Introduction. What is function? Multiple functions form a larger program Modular programming

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Chapter 2. C++ Basics

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

2 nd Week Lecture Notes

Fundamental of Programming (C)

This watermark does not appear in the registered version - Slide 1

Computer Programming : C++

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

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

Full file at

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

Programming in C++ 5. Integral data types

CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS

Another Simple Program: Adding Two Integers

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

CHAPTER 3 Expressions, Functions, Output

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

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

ARG! Language Reference Manual

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Fundamentals of Programming

Chapter Two: Fundamental Data Types

Understanding main() function Input/Output Streams

Summary of basic C++-commands

Chapter 15 - C++ As A "Better C"

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages

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

Add Subtract Multiply Divide

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

CS242 COMPUTER PROGRAMMING

A SHORT COURSE ON C++

Transcription:

Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1

Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from the C++ Standard Library 2

The C++ Programming Language A superset of C C++ compilers can be used to compile C programs Supports Programmer Defined Types Templates Overloading of functions and operators Best to think of C++ as its own language C++ second edition, J. ingber 3

Comments Compiler Directives Using Directive Blocks of Code PROGRAM STRUCTURE 4

/* Simple C++ Program */ /* This program computes the */ /* distance between two points. */ #include <iostream> // Required for cout, endl. #include <cmath> // Required for sqrt() using namespace std; int main() { // Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance; // Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2); // Print distance. cout << "The distance between the two points is " << distance << endl; // Exit program. return 0; } 5

Program structure Comments preprocessor directives using directives Block of code { comments statements } C++ second edition, J. ingber 6

Comments Comments help people read programs, but are ignored by the compiler. In C++ there are two types of comments. Line comments begin with // and continue for the rest of the line. Delimited comments begin with /* and end with */ C++ second edition, J. ingber 7

Preprocessor Directives Provide instructions to the compiler that are performed before the program is compiled. Begin with a # Example: #include <iostream> The #include directive instructs the compiler to include statements from the file iostream. C++ second edition, J. ingber 8

using Directive The using directive instructs the compiler to use files defined a specified namespace. Example: using namespace std; std is the name of the Standard C++ namespace. 9

Block of Code A block of code is defined by a set of curly braces { }. Example: int main() { //Block defines body of main function double x1(1), x2(4), side1; side1 = x2 x1; cout << side1 << endl; return 0; // main()returns int value of 0 } //end definition of main Every C++ problem solution contains exactly one function named main(). C++ program solutions always begin execution in main() 10

Identifiers Memory Snapshots CONSTANTS AND VARIABLES 11

Constants and Variables Constants and variables represent memory locations that we reference in our program solutions. Constants are objects that store specific data that can not be modified. 10 is an integer constant 4.5 is a floating point constant "Side1" is a string constant 'a' is a character constant Variables are memory locations that store values that can be modified. double x1(1.0), x2(4.5), side1; side1 = x2-x1; x1, x2 and side1 are examples of variables that can be modified. 12

Memory Snapshot #include<iostream> using namespace std; int main() { double x1(1.0), x2(4.5), side1; double x1 double x2 double side1 1.0 4.5? Output: side 1 has length: 3.5 side1 = x2-x1; double x1 double x2 double side1 1.0 4.5 3.5 cout << side 1 has length: side1; 13

Common C++ Data Types Keyword Example of a constant bool true char '5' int 25 double 25.0 string "hello" //#include<string> 14

C++ Identifiers Identifiers are used to name objects in C++. Rules for selecting valid identifiers: Identifier must begin with a letter or underscore _ Identifiers consists of alphanumeric characters and underscore character only. An identifier can not be a reserved word. Only the first 31 characters of an identifier are used to distinguish it from other identifiers. C++ is case sensitive. Thus, Side1 and side1 are unique identifiers that represent different objects. 15

Declarations A type declaration statement defines new identifiers and allocates memory. An initial value may be assigned to a memory location at the time an identifier is defined. Syntax: [modifier] data_type identifier_list; Examples: double length( 20.75), width(11.5), volume; int numberoffeetinyard(3); const int MIN_SIZE = 0; 16

Symbolic Constants A symbolic constant is defined in a declaration statement using the modifier const. A symbolic constant allocates memory for an object that can not be modified during execution of the program. Any attempt to modify a constant will be flagged as a syntax error by the compiler. A symbolic constant must be initialized in the declaration statement. 17

Assignment Operators Arithmetic Operators Precedence of Operators C++ OPERATORS 18

Assignment Operator The assignment operator (=) is used in C++ to assign a value to a memory location. The assignment statement: x1 = 1.0; assigns the value 1.0 to the variable x1. Thus, the value 1.0 is stored in the memory location associated with the identifier x1. 19

Assignment Operators - Examples Example 1 - initialization double sum = 0; Example 2 int x; x=5; Example 3 char ch; ch = 'a'; sum x ch 0 5 a 20

Assignment Statements - continued Example 3 int x, y, z; x=y=0; z=2; x y z 0 0 2 How is the memory map affected by the following statement? y = z; 21

Arithmetic Operators Addition + Subtraction - Multiplication * Division / Modulus % Modulus returns remainder of division between two integers Example 5%2 returns a value of 1 22

Integer Division Division between two integers results in an integer. The result is truncated, not rounded Example: The expression 5/3 evaluates to 1 The expression 3/6 evaluates to 0 23

C++ Operators The cast operator. The cast operator is a unary operator that requests that the value of the operand be cast, or changed, to a new type for the next computation. The type of the operand is not affected. Example: int count(10), sum(55); double average; average = (double)sum/count; Memory snapshot: int count int sum 10 55 double average 5.5 24

Priority of Operators 1. Parentheses Inner most first 2. Unary operators Right to left (+ -) 3. Binary operators Left to right (* / %) 4. Binary operators Left to right (+ -) 25

Practice! Evaluate Expressions 7 + 3 * 5 2 4 + 7 / 3 8 % 3 * 6 (7 + 3) * 5-2 26

Overflow and Underflow Overflow answer too large to store Example: using 16 bits for integers result = 32000 +532; Exponent overflow answer s exponent is too large Example: using float, with exponent range 38 to 38 result = 3.25e28 * 1.0e15; Exponent underflow answer s exponent too small Example: using float, with exponent range 38 to 38 result = 3.25e-28 *1.0e-15; 27

Increment and Decrement Operators Increment Operator ++ post increment pre increment x++; ++x; Decrement Operator - - post decrement x- -; pre decrement - -x; For examples assume k=5 prior to executing the statement. m= ++k; both m and k become 6 n = k- -; n becomes 5 and k becomes 4 28

Abbreviated Assignment Operators operator example equivalent statement += x+=2; x=x+2; -= x-=2; x=x-2; *= x*=y; x=x*y; /= x/=y; x=x/y; %= x%=y; x=x%y; 29

Precedence of Arithmetic and Assignment Operators Precedence Operator Associativity 1 Parentheses: () Innermost first 2 Unary operators + - ++ -- (type) 3 Binary operators * / % 4 Binary operators + - 5 Assignment operators = += -= *= /= %= Right to left Left ot right Left ot right Right to left 30

The cout Object The cin Object STANDARD INPUT AND OUTPUT 31

Simple Input - cin cin is an istream object defined in the header file iostream cin is defined to stream data from standard input (the keyboard) We use the input operator >> with cin to assign values to variables General Form: cin >> identifier >> identifier; Note: Data entered from the keyboard must be compatible with the data type of the variable. 32

Simple Output - cout cout is an ostream object, defined in the header file iostream cout is defined to stream data to standard output (the display) We use the output operator << with cout to output the value of an expression. General Form: cout << expression << expression; Note: An expression is a C++ constant, identifier, formula, or function call. 33

//Example1: Determine the output #include <iostream> #include <string> using namespace std; int main() { int i, j; double x; string units = " cm"; cin >> i >> j; cin >> x; cout << "output \n"; output 1,2 4.5 cm _ cout << i << ',' << j << endl << x << units << endl; return 0; } //Input stream: 1 2 4.5 34

//Example 2: Determine the output #include <iostream> using namespace std; int main() { int i, j; double x, y; First output 1,2,3.4,5 Second output 3,2,2,3 _ cin >> i >> j >> x >> y; cout << "First output " << endl; cout << i << ',' << j << ',' << x << ',' << y << endl; cin >> x >> y >> i >> j; cout << "Second output" << endl; cout << i << ',' << j << ',' << x << ',' << y << endl; return 0; } //Input stream is: 1 2 3.4 5 2 3 3.4 7 35

Characters and input The input operator >> skips all whitespace characters. The get() method gets the next character. Example: int x; Memory Snapshot char ch; cin >> x >> ch; cin >> x; cin.get(ch); Input stream: 45 c 39 b 36

Characters and input >> discards leading whitespace get() method used to input whitespace characters Example: int x; char ch; cin >> x >> ch; cin >> x; cin.get(ch); x ch Input stream: 45 c 39 b x 45 c 39 \n ch 37

Manipulators and methods endl places a newline character in the output buffer and flushes the buffer. setf() and unsetf() Flag ios::showpoint ios::fixed ios::scientific Meaning display the decimal point fixed decimal notation scientific notation ios::right ios::left right justification left justification Manipulators in <iomanip> setprecision(n) setw(n) 38

cmath cctype C++ STANDARD LIBRARYS 39

Common Functions in <cmath> abs(x) computes absolute value of x sqrt(x) computes square root of x, where x >=0 pow(x,y) ceil(x) floor(x) exp(x) computes x y nearest integer larger than x nearest integer smaller than x computes e x log(x) computes ln x, where x >0 log10(x) computes log 10 x, where x>0 sin(x) cos(x) tan(x) sine of x, where x is in radians cosine of x, where x is in radians tangent of x, where x is in radians 40

Common Functions in <cctype> isalpha(ch) isdigit(ch) isspace(ch) islower(ch) isupper(ch) tolower(ch) toupper(ch) Returns true if ch is an upper or lower case letter. Returns true if ch is a decimal digit Returns true if ch is a whitespace character. Returns true if ch is an lower case letter. Returns true if ch is an upper case letter. Returns the lowercase version of ch if ch is an uppercase character, returns ch otherwise. Returns the uppercase version of ch if ch is a lowercase character, returns ch otherwise. 41