+ All Categories
Transcript
Page 1: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 1

Chapter 2Introduction to C++

Namiq Sultan

University of Duhok

Department of Electrical and Computer Engineerin

Reference: Starting Out with C++, Tony Gaddis, 2nd Ed.

Page 2: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 2

2.1 The Parts of a C++ Program

• C++ programs have parts and components that serve specific purposes.

Page 3: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 3

Program 2-1

//A simple C++ program

#include <iostream>

using namespace std;

int main ()

{

cout<< “Programming is great fun!”;

return 0;

}

Program Output:

Programming is great fun!

Page 4: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 4

Table 2-1 Special CharactersCharacter Name Description // double slash Marks the beginning of a comment. # Pound sign Marks the beginning of a preprocessor

directive < > Opening and

closing brackets

Encloses a filename when used with the #include directive

( ) Opening and closing parenthesis

Used in naming a function, as in int main ()

{ } Opening and closing braces

Encloses a group of statements, such as the contents of a function.

" " Opening and closing quotation marks

Encloses a string of characters, such as a message that is to be printed on the screen

; Semicolon Marks the end of a complete programming statement

Page 5: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 5

2.2 The cout Object

• Use the cout object to display information on the computer’s screen.

The cout object is referred to as the standard output object.

Its job is to output information using the standard output device

Page 6: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 6

Program 2-2

// A simple C++ program

#include <iostream>

using namespace std;

int main ()

{

cout << “Programming is “ << “great fun!”;

return 0;

}

Output:

Programming is great fun!

Page 7: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 7

Program 2-3

// A simple C++ program#include <iostream>using namespace std;int main (){cout<< “Programming is “;cout << “ great fun!”;return 0;

}

Output: Programming is great fun!

Page 8: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 8

Program 2-4

// An unruly printing program

#include <iostream>

using namespace std;

int main()

{

cout << "The following items were top sellers";

cout << "during the month of June:";

cout << "Computer games";

cout << "Coffee";

cout << "Aspirin";

return 0;

}

Program Output

The following items were top sellersduring the month ofJune:Computer gamesCoffeeAspirin

Page 9: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 9

New lines

• cout does not produce a newline at the end of a statement

• To produce a newline, use either the stream manipulator endl• or the escape sequence \n

Page 10: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 10

Program 2-5

// A well-adjusted printing program

#include <iostream>

using namespace std;

int main()

{

cout << "The following items were top sellers" << endl;

cout << "during the month of June:" << endl;

cout << "Computer games" << endl;

cout << "Coffee" << endl;

cout << "Aspirin" << endl;

return 0;

}

Page 11: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 11

Program Output

The following items were top sellers

during the month of June:

Computer games

CoffeeAspirin

Page 12: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 12

Program 2-6

// Another well-adjusted printing program

#include <iostream>

using namespace std;

int main()

{

cout << "The following items were top sellers" << endl;

cout << "during the month of June:" << endl;

cout << "Computer games" << endl << "Coffee";

cout << endl << "Aspirin" << endl;

return 0;

}

Page 13: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 13

Program Output

The following items were top sellers

during the month of June:

Computer games

Coffee

Aspirin

Page 14: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 14

Program 2-7

// Yet another well-adjusted printing program

#include <iostream>

using namespace std;

int main()

{

cout << "The following items were top sellers\n";

cout << "during the month of June:\n";

cout << "Computer games\nCoffee";

cout << "\nAspirin\n";

return 0;

}

Page 15: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 15

Program Output

The following items were top sellers

during the month of June:

Computer games

Coffee

Aspirin

Page 16: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 16

Table 2-2Table 2-2 Common Escape Sequences Escape Sequence

Name Description

\n Newline Causes the cursor to go to the next line for subsequent printing

\t Horizontal tab

Causes the cursor to skip over to the next tab stop

\a Alarm Causes the computer to beep

\b Backspace Causes the cursor to back up, or move left one position

\r Return Causes the cursor to go to the beginning of the current line, not the next line.

\\ Backslash Causes a backslash to be printed

\' Single quote Causes a single quotation mark to be printed

\" Double quote Causes a double quotation mark to be printed

Page 17: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 17

2.3 The #include Directive

• The #include directive causes the contents of another file to be inserted into the program

• Preprocessor directives are not C++ statements and do not require semicolons at the end

Page 18: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 18

2.4 Variables and Constants

• Variables represent storage locations in the computer’s memory. Constants are data items whose values do not change while the program is running.

• Every variable must have a declaration.

Page 19: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 19

Program 2-8

#include <iostream>using namespace std;int main(){ int value; value = 5; cout << “The value is “ << value << endl;

return 0;}

Program Output:The value is 5

Page 20: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 20

Assignment statements:

Value = 5; //This line is an assignment statement.

• The assignment statement evaluates the expression on the right of the equal sign then stores it into the variable named on the left of the equal sign

• The data type of the variable was in integer, so the data type of the expression on the right should evaluate to an integer as well.

Page 21: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 21

Constants

• A variable is called a “variable” because its value may be changed. A constant, on the other hand, is a data item whose value does not change during the program’s execution.

Page 22: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 22

2.5 Identifiers

• Must not be a keyword

• The first character must be a letter or an underscore

• The remaining may be letters, digits, or underscores

• Upper and lower case letters are distinct

Page 23: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 23

Table 2-3 The C++ Keywords

Asm auto bool break case catch

char class const const_cast continue default

delete do double dynamic_cast else enum

explicit export extern false float for

friend goto if inline int long

mutable namespace new operator private

protected

public register reinterpret_cast return short signed

sizeof static static_cast struct switch template

this throw true try typedef typeid

Type name union unsigned using virtual

void volatile wchar_t while

Page 24: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 24

Table 2-4 Some Variable Names

Variable Name Legal or Illegal?

dayOfWeek Legal

3dGraph Illegal. Cannot begin with a digit.

_employee_num Legal

june1997 Legal

Mixture#3 Illegal. Cannot use # symbol.

Page 25: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 25

2.6 Integer Data Types

• There are many different types of data. Variables are classified according to their data type, which determines the kind of information that may be stored in them.

• Integer variables only hold whole numbers.

Page 26: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 26

Program 2-12

// This program shows three variables declared on the same line.

#include <iostream>using namespace std;

int main()

{

int floors, rooms, suites;

  floors = 15;

rooms = 300;

suites = 30;

cout << "The Grande Hotel has " << floors << " floors\n";

cout << "with " << rooms << " rooms and " << suites;

cout << " suites.\n";

return 0;

}

Page 27: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 27

Program Output

The Grande Hotel has 15 floors

with 300 rooms and 30 suites.

Page 28: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 28

2.7 The char Data Type

• Usually 1 byte long

• Internally stored as an integer

• ASCII character set shows integer representation for each character

• ‘A’ == 65, ‘B’ == 66, ‘C’ == 67, etc.

• Single quotes denote a character, double quotes denote a string

Page 29: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 29

Program 2-14

// This program uses character constants

#include <iostream>

using namespace std;

int main()

{

char letter;

 

letter = 'A';

cout << letter << endl;

letter = 'B';

cout << letter << endl;

return 0;

}

Page 30: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 30

Program Output

A

B

Page 31: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 31

Strings

• Strings are consecutive sequences of characters and can occupy several bytes of memory.

• Strings always have a null terminator at the end. This marks the end of the string.

• Escape sequences are always stored internally as a single character.

Page 32: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 32

• Let’s look at an example of how a string is stored in memory.

• "Sebastian" would be stored.

• ‘A’ is stored as

• “A” is stored as

S e b a ts \0i a n

65

065

Page 33: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 33

Review key points regarding characters, and strings:

• Printable characters are internally represented by numeric codes. Most computers use ASCII codes for this purpose.

• Characters occupy a single byte of memory.

• Strings are consecutive sequences of characters and can occupy several bytes of memory.

• Strings always have a null terminator at the end. This marks the end of the string.

• Character constants are always enclosed in single quotation marks.

• String constants are always enclosed in double quotation marks.

• Escape sequences are always stored internally as a single character.

Page 34: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 34

2.8 Floating Point Data Types

• Floating point data types are used to declare variables that can hold real numbers

Page 35: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 35

// This program uses floating point data types

#include <iostream>using namespace std;

int main()

{

float distance;

float mass;

distance = 1.495979;

mass = 1.989;

cout << "The Distance is " << distance << " kilometers \n";

cout << "The mass is " << mass << " kilograms.\n";

return 0;

}

Page 36: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 36

Program Output

The Sun is 1.4959 kilometers

The mass is 1.989 kilograms.

Page 37: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 37

2.9 The bool Data Type

• Boolean variables are set to either true or false

Page 38: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 38

Program 2-17

#include <iostream>

using namespace std;

int main ()

{

bool boolValue;

boolValue = true;

cout << boolValue << endl;

boolValue = false;

cout << boolValue << endl;

return 0;

}

Page 39: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 39

Program Output

1

0

Internally, true is represented as the number 1 and false is represented by the number 0.

Page 40: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 40

2.11 Variable Assignment and Initialization

• An assignment operation assigns, or copies, a value into a variable. When a value is assigned to a variable as part of the variable’s declaration, it is called an initialization.

Page 41: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 41

Program 2-19

#include <iostream>using namespace std;

int main ()

{

int month = 2, days = 28;

cout << “Month “ << month << “ has “ << days << “ days.\n”;

return 0;

}

Program output:

Month 2 has 28 days.

Page 42: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 42

2.13 Arithmetic Operators

• There are many operators for manipulating numeric values and performing arithmetic operations.

• Generally, there are 3 types of operators: unary, binary, and ternary.

Unary operators operate on one operand Binary operators require two operands Ternary operators need three operands ( ?: in ch 4)

Page 43: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 43

Table 2-8

Table 2-8 Fundamental Arithmetic Operaotrs Operator Meaning Type Example

+ Addition Binary Total = Cost + Tax;

- Subtraction Binary Cost = Total - Tax;

* Multiplication Binary Tax = Cost * Rate;

/ Division Binary SalePrice = Original/2;

% Modulus Binary Remainder = Value%3;

Page 44: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 44

Program 2-21

// This program calculates hourly wages. The variables are used as follows:// regWages: holds the calculated regular wages.// basePay: holds the base pay rate.// regHours: holds the number of hours worked less overtime.// otWages: holds the calculated overtime wages.// otPay: holds the payrate for overtime hours.// otHours: holds the number of overtime hours worked.// totalWages: holds the total wages.

#include <iostream>using namespace std;int main(){

float regWages, basePay = 18.25, regHours = 40.0;float otWages, otPay = 27.78, otHours = 10;float totalWages;

 

Page 45: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 45

Program 2-21

  regWages = basePay * regHours;

otWages = otPay * otHours;

totalWages = regWages + otWages;

cout << "Wages for this week are $" << totalWages << endl;

return 0;

}

Page 46: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 46

2.14 Comments

• Comments are notes of explanation that document lines or sections of a program.

• Comments are part of a program, but the compiler ignores them. They are intended for people who may be reading the source code.

• Commenting the C++ Way

//

• Commenting the C Way

/* */

Page 47: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 47

Program 2-22

// PROGRAM: PAYROLL.CPP

// Written by Herbert Dorfmann

// This program calculates company payroll

 

#include <iostream>using namespace std;

int main(void)

{

float payRate; // holds the hourly pay rate

float hours; // holds the hours worked

int empNum; // holds the employee number

 

(The remainder of this program is left out.)

Page 48: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 48

Program 2-24

/* PROGRAM: PAYROLL.CPP

Written by Herbert Dorfmann

This program calculates company payroll */

#include <iostream>using namespace std;

int main(void)

{

float payRate; /* payRate holds hourly pay rate */

float hours; /* hours holds hours worked */

int empNum; /* empNum holds employee number */

 

(The remainder of this program is left out.)

Page 49: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 49

2.15 Programming Style

• Program style refers to the way a programmer uses identifiers, spaces, tabs, blank lines, and punctuation characters to visually arrange a program’s source code.

Generally, C++ ignores white space. Indent inside a set of braces. Include a blank line after variable declarations.

Page 50: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 50

Program 2-26

#include <iostream>

using namespace std;

int main( ){float shares=220.0; float avgPrice=14.67; cout <<"There

were "<<shares<<" shares sold at $"<<avgPrice<<" per share.\

n";return 0;}

Program Output

There were 220 shares sold at $14.67 per share.

Page 51: C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:

C++ Programming, Namiq Sultan 51

Program 2-27

// This example is much more readable than Program 2-26.

 #include <iostream>using namespace std;

int main(void)

{

float shares = 220.0;

float avgPrice = 14.67;

 

cout << "There were " << shares << " shares sold at $";

cout << avgPrice << " per share.\n";

return 0;

}

Program Output

There were 220.0 shares sold at $14.67 per share.


Top Related