Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language



Similar documents
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Chapter 5 Functions. Introducing Functions

Chapter One Introduction to Programming

C++ Language Tutorial

Informatica e Sistemi in Tempo Reale

Chapter 2: Elements of Java

C++ Input/Output: Streams

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Sequential Program Execution

C Programming Language

El Dorado Union High School District Educational Services

Sources: On the Web: Slides will be available on:

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 2 Elementary Programming

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

A brief introduction to C++ and Interfacing with Excel

The C Programming Language course syllabus associate level

Final Exam Review: VBA

Basics of I/O Streams and File I/O

So far we have considered only numeric processing, i.e. processing of numeric data represented

An Incomplete C++ Primer. University of Wyoming MA 5310

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

C++ INTERVIEW QUESTIONS

While Loop. 6. Iteration

Pemrograman Dasar. Basic Elements Of Java

Moving from CS 61A Scheme to CS 61B Java

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Introduction to Python

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Number Representation

Some Scanner Class Methods

Computer Science 281 Binary and Hexadecimal Review

Formatting Numbers with C++ Output Streams

Introduction to Java. CS 3: Computer Programming in Java

Moving from C++ to VBA

Install Java Development Kit (JDK) 1.8

7.7 Case Study: Calculating Depreciation

C++ Programming Language

Member Functions of the istream Class

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Introduction to Python

Introduction to Visual C++.NET Programming. Using.NET Environment

PL / SQL Basics. Chapter 3

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

6.170 Tutorial 3 - Ruby Basics

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Objective-C Tutorial

Object Oriented Software Design

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

JavaScript: Control Statements I

Answers to Selected Exercises

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Divide: Paper & Pencil. Computer Architecture ALU Design : Division and Floating Point. Divide algorithm. DIVIDE HARDWARE Version 1

Variables, Constants, and Data Types

Object Oriented Software Design

The OptQuest Engine Java and.net Developer's Guilde

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Chapter 3 Operators and Control Flow

Fundamentals of Programming

Measures of Error: for exact x and approximation x Absolute error e = x x. Relative error r = (x x )/x.

Comp151. Definitions & Declarations

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

5 Arrays and Pointers

SOME EXCEL FORMULAS AND FUNCTIONS

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Java Basics: Data Types, Variables, and Loops

How to think like a computer scientist. Allen B. Downey

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

HOMEWORK # 2 SOLUTIO

CHAPTER 5 Round-off errors

Introduction to Java

FX 260 Training guide. FX 260 Solar Scientific Calculator Overhead OH 260. Applicable activities

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Syllabus OBJECT ORIENTED PROGRAMMING C++

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Programming in Java Course Technology, a part of Cengage Learning.

VB.NET Programming Fundamentals

The C Programming Language

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Example of a Java program

The programming language C. sws1 1

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Chapter 5. Selection 5-1

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

PHP Tutorial From beginner to master

Transcription:

Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from the C++ Standard Library C++, Second Edition, J. Ingber 1 2 The C++ Programming Language Dev-C++ 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 Bloodshed Software http://www.bloodshed.net/dev/devcpp.htm l Dev-C++ 5.0 beta 9.2 (4.9.9.2) (9.0 MB) with Mingw/GCC 3.4.2 Download from: SourceForge 3 Dev-C++ New Source File Windows Friendly Exit // Windows friendly exit system("pause"); Compile Run

Program structure C++ Program Comments preprocessor directives using directives Block of code comments statements } 7 /*-----------------------------------------------------------*/ /* Hello World program */ /* */ #include <iostream> char ch; // Print Hello World cout << "Hello World" << endl; cin >> ch; // Exit program return( 0); } /*-------------------------------------------------------------------------------*/ 5 Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a hand example. 4. Develop a solution. 5. Test your solution. Example Problem Statement Compute the straight-line distance between two points in a plane Input/Output Description Point 1 (x1, y1) Point 2 (x2, y2) Distance (d) 9 Example Hand Example p1 = (1, 3) p2 = (4, 7) Algorithm Development (outline) Give values to the two points Compute lengths of two sides of right triangle Compute distance between points (hypotenuse) Print distance between points /* Simple C++ Program */ /* This program computes the */ /* distance between two points. */ #include <iostream> // Required for cout, endl. #include <cmath> // Required for sqrt() // 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. } 12

C++ Program /*-----------------------------------------------*/ /* Program chapter1_1 */ /* */ /* This program computes the distance between */ /* two points */ #include <iostream> #include <cmath> 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 */ 14 Preprocessor Directives using Directive 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. 15 The using directive instructs the compiler to use files defined a specified namespace. Example: std is the name of the Standard C++ namespace. 16 Block of Code A block of code is defined by a set of curly braces }. Example: //Block defines body of main function double x1(1), x2(4), side1; side1 = x2 x1; cout << side1 << endl; // 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() C++ Program // Declare and initialize objects double x1(1), y1(3), x2(4), y2(7), side1, side2, distance; // Compute sides of right triangle side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1 * side1 + side2 * side2); 17

C++ Program // Print distance cout << "The distance between the two points is " << distance << endl; // Windows friendly exit system("pause"); } /*----------------------------------------------*/ 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. Engineering Problem Solving with 20 Memory Snapshot #include<iostream> double x1(1.0), x2(4.5), side1; double x1 double x2 double side1 side1 = x2-x1; double x1 double x2 double side1 1.0 4.5? 1.0 4.5 3.5 Output: side 1 has length: 3.5 Common C++ Data Types Keyword Example of a constant bool true char '5' int 25 double 25.0 string "hello" //#include<string> cout << side 1 has length: side1; 21 22 C++ Identifiers Declarations 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. 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; 23 24

Symbolic Constants C++ OPERATORS 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. Assignment Operators Arithmetic Operators Precedence of Operators 25 26 Assignment Operator Assignment Operators - Examples 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. Example 1 - initialization double sum = 0; Example 2 int x; x=5; Example 3 char ch; ch = 'a'; sum 27 x ch 0 5 a 28 Assignment Statements - continued Arithmetic Operators Example 3 int x, y, z; x=y=0; z=2; How is the memory map affected by the following statement? y = z; z y x 0 0 2 Addition + Subtraction - Multiplication * Division / Modulus % Modulus returns remainder of division between two integers Example 5%2 returns a value of 1 29 30

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 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 31 32 Priority of Operators Practice! Evaluate Expressions 1. Parentheses Inner most first 2. Unary operators Right to left (+ -) 3. Binary operators Left to right (* / %) 4. Binary operators Left to right (+ -) 33 7 + 3 * 5 2 4 + 7 / 3 8 % 3 * 6 (7 + 3) * 5-2 34 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; 35 Numeric Data Types Integers short int long Floating-Point float double long double

Boolean Data Type Example bool error(false), status(true); cout << error << endl << status; Program Output 0 1 Increment and Decrement Operators Increment Operator ++ post increment x++; pre increment ++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 38 Abbreviated Assignment Operators Precedence of Arithmetic and Assignment Operators Precedence Operator Associativity 1 Parentheses: () Innermost first 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; 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 39 40 STANDARD INPUT AND OUTPUT The cout Object The cin Object 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. 41 42

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. 43 //Example1: Determine the output #include <iostream> #include <string> int i, j; double x; string units = " cm"; cin >> i >> j; cin >> x; cout << "output \n"; 1 2 4.5 output 1,2 4.5 cm _ cout << i << ',' << j << endl << x << units << endl; } //Input stream: 44 //Example 2: Determine the output #include <iostream> int i, j; double x, y; First output 1, 2, 3.4, 5 Second output 3.4, 7, 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; } //Input stream is: 1 2 3.4 5 2 3 3.4 7 45 Characters and input The >> operator discards leading whitespace get() method gets the next character even if it is a whitespace character Example: int x; char ch; cin >> x >> ch; cin >> x; cin.get(ch); x 45 ch c Input stream: 45 c 39 b x 39 \n ch 46 Standard Output Standard Output #include <iostream> cout << "Hello " << name; Stream Manipulators #include <iomanip> setprecision(n), fixed, scientific setw(n), left, right, setfill(ch) dec, oct, hex endl Standard Output // Output results cout << setprecision(4) << "The radius of the circle is: " << setw(10) << radius << " centimeters" << endl; cout << scientific << "The area of the circle is: " << setw(12) << area << " square centimeters" << endl;

Common Functions in <cmath> abs(x) computes absolute value of x sqrt(x) computes square root of x, where x >=0 pow(x,y) computes x y cmath cctype C++ STANDARD LIBRARYS ceil(x) floor(x) exp(x) 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 49 50 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. 51