Chapter 2. Outline. Simple C++ Programs

Similar documents
Engineering Problem Solving with C++, Etter/Ingber

ANSI C Programming Simple Programs

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

Operations. Making Things Happen

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

Objectives. In this chapter, you will:

C++ Programming Lecture 11 Functions Part I

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

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

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

The C++ Language. Arizona State University 1

BITG 1233: Introduction to C++

Chapter 4: Basic C Operators

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.

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

Chapter 2: Introduction to C++

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

LECTURE 02 INTRODUCTION TO C++

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

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.

Chapter 3. Numeric Types, Expressions, and Output

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

CHAPTER 3 BASIC INSTRUCTION OF C++

Chapter 2 Basic Elements of C++

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

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

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-

Full file at

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

Summary of basic C++-commands

UNIT- 3 Introduction to C++

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

CSCE 110 PROGRAMMING FUNDAMENTALS

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

Introduction to C++ Dr Alex Martin Room 6.10

A First Program - Greeting.cpp

Chapter 1 Introduction to Computers and C++ Programming

Introduction to Programming

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

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

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

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

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

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

CS1010E Lecture 3 Simple C Programs Part 2

Lecture 3 Tao Wang 1

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Chapter 2: Overview of C++

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Programming with C++ as a Second Language

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

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

Add Subtract Multiply Divide

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Computer Programming : C++

Expressions, Input, Output and Data Type Conversions

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++ Programming Pearson Education, Inc. All rights reserved.

C++ Overview. Chapter 1. Chapter 2

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

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

C: How to Program. Week /Mar/05

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

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

CSI33 Data Structures

CS242 COMPUTER PROGRAMMING

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

Operators and Expressions:

VARIABLES & ASSIGNMENTS

Visual C# Instructor s Manual Table of Contents

Understanding main() function Input/Output Streams

Programming. C++ Basics

Fundamental of Programming (C)

Product Price Formula extension for Magento2. User Guide

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

Chapter 2. C++ Basics

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

Topic 2: C++ Programming fundamentals

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

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

Chapter 3 - Notes Input/Output

A SHORT COURSE ON C++

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

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

Creating a C++ Program

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

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

Objectives Outline- we spend lots of time here!

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

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

CSI33 Data Structures

Chapter 1 INTRODUCTION

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

by Pearson Education, Inc. All Rights Reserved. 2

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

Transcription:

Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6. Building C++ Solutions with IDEs:NetBeans 7. Basic Functions in C++ Standard Library 8. Problem Solving Applied 9. System Limitations 1

Integrated Development Environments (IDEs) IDEs are software packages designed to facilitate the development of software solutions. IDEs include: Code editors Compiler Debugger Testing tools Many additional helpful tools Xcode The Xcode IDE was developed by Apple for the development of applications that run on Macs, ipads, and iphones. Xcode is available as a free download at https://developer.apple.com/. 2

Building C++ Solutions with IDEs:NetBeans The NetBeans IDE is open source software that provides a development environment for multiple languages including Java, C and C++. /*-------------------------------------------------------- * Program chapter1_1 * 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; C++11 recommended notation for initializing objects. distance = sqrt(side1*side1 + side2*side2); // Print distance. cout << "The distance between the two points is " << distance << endl; // Exit program. return 0; } //-------------------------------------------------------- C++ Program Structure 3

/*-------------------------------------------------------- * Program chapter1_1 * 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}, Comments: side1, side2, distance; Document the // Compute sides of a right triangle. program s purpose side1 = x2 - x1; Help the human side2 = y2 - y1; reader understand the distance = sqrt(side1*side1 + side2*side2); program // Print distance. Are ignored by the cout << "The distance between the two points is " compiler << distance << endl; // Exit program. return 0; } //-------------------------------------------------------- // comments to end-of line /* starts a comment block ending with */ /*-------------------------------------------------------- * Program chapter1_1 * 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. Begin with # cout << "The distance between the two points is " << distance << endl; // Exit program. return 0; } //-------------------------------------------------------- Preprocessor Directives: Give instructions to the preprocessor before the program is compiled. #include directives add or insert the contents of the named file into the program 4

/*-------------------------------------------------------- * Program chapter1_1 * 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 " The std, or << distance << endl; // Exit program. return 0; } //-------------------------------------------------------- using Directives: Tell the compiler to use the library names declared in the specified namespace. standard namespace contains C++ languagedefined components. /*-------------------------------------------------------- * Program chapter1_1 * 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. main function header: Defines the starting point (i.e. entry point) for a C++ program The keyword int indicates that the function will return an cout << "The distance between the two points is " integer value to the << distance << endl; operating system. // Exit program. Every C++ program return 0; has exactly one } function named main. //-------------------------------------------------------- 2017 Pearson Education, Inc. Hoboken, NJ. All Rights Reserved. 5

/*-------------------------------------------------------- * Program chapter1_1 * 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; Code blocks: distance = sqrt(side1*side1 + side2*side2); // Print distance. cout << "The distance between the two points is " << distance << endl; // Exit program. return 0; } //-------------------------------------------------------- are zero or more C++ declarations and/or statements enclosed within curly braces { } /*-------------------------------------------------------- * Program chapter1_1 * 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. Declarations: Define identifiers and allocate memory. May also provide initial values for variables. cout << "The distance between the two points is " Identifiers must be << distance << endl; declared before // Exit program. using in a statement. return 0; C++11 recommends } using { } notation. //-------------------------------------------------------- 6

/*-------------------------------------------------------- * Program chapter1_1 * 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; Statements : distance = sqrt(side1*side1 + side2*side2); specify the // Print distance. operations to be cout << "The distance between the two points is " performed. << distance << endl; // Exit program. return 0; } //-------------------------------------------------------- Constants and Variables Constants and variables both represent memory locations that we reference in our program solutions. Constants are objects that store specific data values that can not be modified. 10 is an integer constant 4.5 is a floating point constant "The distance between the two points " is a string constant 'a' is a character constant Variables are named 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. 7

Initial Values C++ does not provide initial values for variables. Thus using the value of a variable before it is initialized may result in garbage. Memory Snapshots Memory snapshots are diagrams that show the types and contents of variables at a particular point in time. double x1{1}, y1{5}, x2{4}, y2{7}, side1, side2, distance; double x1 1.0 double y1 5.0 double x2 4.0 double y2 7.0 double side1? double side2? double distance? 8

Valid C++ Identifiers Must begin with an alphabetic character or the underscore character _ Alphabetic characters may be either upper or lower case. C++ is CASE SENSITIVE, so a!= A, etc May contain digits, but not as the first character. May be of any length, but the first 31 characters must be unique. May NOT be C++ keywords. C++ Keywords 9

C++ Identifiers Should be carefully chosen to reflect the contents of the object. The name should also reflect the units of measurements when applicable. Identifiers must be declared before they may be used. C++ is a strongly typed programming language. Common C++ Data Types Keyword Example of a constant bool true char '5' int 25 double 25.0 string "hello" //#include<string> 10

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] type specifier identifier [{initial value}]; [modifier] type specifier identifier [= initial value]; [modifier] type specifier identifier[(initial value)]; Examples double x1, y1{0}; //C++11 int counter=0; const int MIN_SIZE=0; bool error(false); char comma(','); 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. 11

Auto Type Specifier The C++11 keyword auto supports the declaration of an object without specifying a data type, as long as an initializer is provided. The data type of the initializer defines the data type of the identifier. Examples auto x1 = 0; //x1 is type integer auto comma = ','; //comma is type char auto y1 = 0.5; //y1 is type double auto time = x1; //time is type integer auto can be useful as data types become more complex, and harder to determine. 12

Order of Types Because different data types have different representations, it may be necessary to convert between data types. Conversion from a lower type to a higher type results in no loss of information.(example: double x{1};) Conversion from higher type to lower type may loose information. (Example: int x(7.7);) implicit conversion from 'double' to 'int' changes value from 7.7 to 7 High: Low: long double double float long integer integer short integer C++ Operators Assignment Operator Arithmetic Operators Increment and Decrement Operators Abbreviated Arithmetic Operators 13

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. (Note: x1 must have been previously declared.) Assignment Statements Assignment operator(=) should not be confused with equality operator(==). 14

Arithmetic Expressions Expressions used in assignment statements for numeric variables may be literal constants (e.g. x1 = 10.4;), other variables (e.g. x2= x1;), or compound expressions involving arithmetic operators (e.g. x1 = -3.4*x2 + 10.4). Arithmetic Operators Addition + Subtraction - Multiplication * Division / Modulus % Modulus returns remainder of division between two integers Example 5%2 returns a value of 1 15

Operator Basics The five operators (* / % + -) are binary operators - operators that require two arguments (i.e. operands). C++ also includes unary operators - operators that require only a single argument. For example, the minus sign preceding an expression, as in (y = -x2), is a unary operator. 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 16

Mixed Operations Binary operations on two values of same type yield a value of that type (e.g. dividing two integers results in an integer). Binary operations between values of different types is a mixed operation. Value of the lower type must be converted to the higher type before performing operation. Result is of the higher type. The cast operator. Casting 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 17

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; Increment and Decrement Operators Unary Operators Increment Operator ++ post increment pre increment Decrement Operator -- post decrement pre decrement x++; ++x; x--; --x; For example, assume k=5 prior to executing each of the following statements. m = ++k; n = k- -; // m and k are 6 after execution // n is 5 and k is 4 after execution 18

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; Operator Precedence Precedence Operator Associativity 1 Parenthesis: () Innermost First 2 Unary operators: + - ++ -- (type) Right to left 3 Binary operators: * / % 4 Binary operators: + - 5 Assignment Operators = += -= *= /= %= Left to right Left to right Right to left 19

Standard Input/Output cin Standard input, pronounced c in cout Standard output, pronounced c out Standard 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. 20

Standard 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. Characters and Input The input operator >> skips all whitespace characters. The get() method gets the next character. Example: int x; char ch; cin >> x >> ch; cin >> x; cin.get(ch); x x Input stream: 45 c 39 b Memory Snapshot ch 45 c ch 39 \n 21

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 Ios::setprecision(n) Meaning display the decimal point fixed decimal notation scientific notation set the number of significant digits to be printed to the integer value n Ios::setw(n) ios::right ios::left set the minimum number of columns for printing the next value to the integer value n right justification left justification fabs(x) sqrt(x) pow(x,y) ceil(x) floor(x) exp(x) Math Functions #include<cmath> computes absolute value of x computes square root of x, where x >=0 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 22

sin(x) cos(x) tan(x) asin(x) Trigonometric Functions sine of x, where x is in radians cosine of x, where x is in radians tangent of x, where x is in radians This function computes the arcsine, or inverse sine, of x, where x must be in the range [ 1, 1]. The function returns an angle in radians in the range [ π/2, π/2]. acos(x) This function computes the arccosine, or inverse cosine, of x, where x must be in the range [ 1, 1]. The function returns an angle in radians in the range [0, π]. atan(x) This function computes the arctangent, or inverse tangent, of x. The function returns an angle in radians in the range [ π/2, π/2]. atan2(y,x) This function computes the arctangent or inverse tangent of the value y/x. The function returns an angle in radians in the range [ π, π]. Common Functions Defined 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. 23

24

System Limitations C++ standards do not specify limitations of data types they are compiler-specific. C++ does provide standard methods of accessing the limits of the compiler: <climits> defines ranges of integer types. <cfloat> defines ranges of floating-point types. the sizeof(type) function returns the memory size of the type, in bytes. 25