CS102 Introduction to Computer Programming

Download Report

Transcript CS102 Introduction to Computer Programming

CS102 Introduction to Computer Programming

Week 2 Chapter 2, Introduction to C++ 1

Chapter 2 Introduction to C++

• Parts of a C++ Program • The cout Object • The #include Directive • Variables and Constants • Data Types and Variables • Integer Data Types • Hexadecimal and Octal Constants • The cha r Data Type • Character Constants • Floating Point Data Types • Floating Point Constants • The bool Data Types • Summary of Data Types • Arithmetic Operators • Comments 2

Character Name // # < >

( ) { } " "

The parts of a C++ Program

Description double slash

comment.

Marks the beginning of a

Pound sign

Marks the beginning of a preprocessor directive.

Opening and closing

filename when used with the Encloses a

brackets

#include directive.

Opening and closing

a function as in void main Used in naming

parenthesis

(void).

Opening and closing

Encloses a group of statements such as the

braces

contents of a function.

3

Opening and closing

Encloses a string

Program 2-1

//A simple C++ program, using //the ‘old’ style of programming in // version 3 of Gaddis Book #include void main (void) { cout<< "Programming is great fun!"; } //A simple C++ program, using //the ‘new’ style of programming in // version 4 of Gaddis Book #include < iostream > using namespace std; int main () { cout<< "Programming is great fun!"; return 0; }

Program Output:

Programming is great fun!

Note:

Notice the differences in setting up a program the

‘old’ red.

and

‘new’

way, highlighted

in

In this course, you will run into both styles of programming. They both work as well until later, when the new ‘iostream’ library (without the .h) will be necessary for Object Oriented programming.

4

Check point 2.1

Put these statements in order: 1.

2.

3.

4.

5.

6.

7.

1.

int main() } //A crazy mixed up program return 0; #include cout << "In 1492 Columbus sailed the ocean blue."; { using namespace std; Any line that begins with a

#

is: a. the beginning of a function b. a preprocessor directive c. printed on the screen Every complete C++ program must have a: a. function called main b. #include statement c. comment 3 , 5 , 8, 1, 7 , 6 , 4, 2 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.

6

Program

2-2 //A simple C++ program #include using namespace std; int main () {

Space

cout<< "Programming is “ << "great fun!"; return 0; }

1 Space

Program Output:

Programming is great fun!

7

Program 2-3

//A simple C++ program #include void main (void) { cout<< "Programming is "; cout << "great fun!"; }

Program Output:

Programming is great fun!

8

Program 2-4

// An unruly printing program #include void main(void) { cout << "The following items were top sellers"; cout << "during the month of June:"; cout << "Computer games"; cout << "Coffee"; cout << "Aspirin"; }

Program Output

The following items were top sellersduring the month of June:Computer gamesCoffeeAspirin 9

New lines

• cout does not produce a new line at the end of a statement • To produce a new line, use either the – stream manipulator

endl

or the – escape sequence

\n

10

Program 2-5

// A well-adjusted printing program #include using namespace std; This program used control line spacing int main() { cout << "The following items were top sellers" << endl;

endl

to cout << "during the month of June:" << endl; cout << "Computer games" << endl; cout << "Coffee" << endl; cout << "Aspirin" << endl; return 0; }

Program Output

The following items were top sellers during the month of June: Computer games Coffee Aspirin 11

Program 2-6

// Another well-adjusted printing program // (The ‘old’ programming way) #include This program uses

endl

multiple times in the same

cout

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

Program Output

The following items were top sellers during the month of June: Computer games Coffee Aspirin 12

Program 2-7

// Yet another well-adjusted printing program #include using namespace std; int main() This program uses the escape character \

n

to control line spacing { } cout << "The following items were top sellers\n"; cout << "during the month of June:\n"; cout << "Computer games\nCoffee"; cout << "\nAspirin\n"; return 0;

Program Output

The following items were top sellers during the month of June: Computer games Coffee Aspirin 13

The

cout

Object

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

\t Horizontal Tab Causes the cursor to skip to the next tab stop.

\a Alarm Causes the cursor to beep.

\b Backspace \r Return \\ \' Backslash Single Quote Causes the cursor to move left one position.

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

Causes a single backslash to be printed.

Causes a single quotation mark to be printed.

\" Double Quote Causes a double quotation mark to be printed.

Concept - Use the

cout

object to display information on the computer's screen and escape characters for formating.

14

The #include Directive

• This is not a C++ statement and does not end in a semicolon (;) – It is not seen by the C++ compiler.

• It must always contain the name of a file.

– The C++ compiler sees only the contents of the file.

Concept - The #include directive causes the contents of another file to be inserted into the program.

15

2.4 Variables and Constants

• •

Variables

represent storage locations in the computer’s memory.

– Every variable must be declared.

Constants

are data items whose values do not change while the program is running.

Both Variables and constants are of specific data types and stored in unique memory locations 16

Variables

• The programmer determines: – the number of variables used in a program – the name of each variable – the type of data each variable will hold.

– the variables initial value • Each variable must be declared before it is used.

• The value of a variable can be changed during the execution of a program.

Concept - Variables represent storage locations in the computer’s memory.

17

Program 2-7

Definition and initialization Definition and assignment #include using namespace std; int main() { int number = 5; cout << "The value in number is "; } cout << number << endl; return 0; #include using namespace std; int main() { } int number ; number = 5; cout << "The value in number is "; cout << number << endl; return 0;

Program Output:

The value in number is 5

Program Output:

The value in number is 5 18

Assignment statements:

• The assignment statement evaluates the expression on the right of the equal sign, – the

rvalue

• Then stores it into the variable named on the left of the equal sign – the

lvalue

lvalue Value = 5; rvalue 19

Constants

• Constants can be used: – to assign known values to variables – as part of mathematical expressions – to display messages on a screen or printout • Constants cannot appear on the left side of an assignment statement.

• All constants have data types the same as variables Concept - A constant is a

data item

whose value does not change while the program is running.

20

asm char delete explicit auto class do extern goto if namespace new register static throw union wchart_t reinterpret_cast static_cast true unsigned while

C++ Key Words

break bool case const double false inline operator return struct try using const_cast dynamic_cast float int private short switch typedef virtual continue else for long protected signed template typeid void catch default emun friend mutable public sizeof this typename volatile Concept - Chose variable names that are not key words and indicate what the variables are used for.

21

Variable Names

• The first character must be one of the letters a-z, A-Z or an underscore ( _ ).

• After the first character, you can use any of the characters above or digits 0-9.

• Only the first 31 characters are considered by the compiler.

• Upper and lower case characters are distinct.

• You cannot declare two variables of the same name in a function.

• You cannot give a variable the same name as a function.

22

Table 2-4 Some Variable Names

Variable Name

a O 3 G h _ m y _ m

Legal or Illegal?

Legal.

Illegal. Variable names cannot begin with a digit .

Legal.

J n 9 tu e Legal.

Illegal. Variable names may only use alphabetic letters, digits, or underscores .

23

Data Types of Variables

• The primary considerations for selecting a numeric data type are: – the largest and smallest numbers stored in the variable, – how much memory the variable uses, – whether the variable stores signed or unsigned numbers, – the number of decimal places of precision, – the relative speed at which the variable is processed.

Concept -Variables are classified according to their data type, which determines the kind of information that may be stored in them.

24

Integer Data Types Visual C++

• Integer – int 4 bytes, -2,147,483,648 to 2,147,483,647 • Unsigned Integer – unsigned 4 bytes, 0 to 4,294,967,295 • Short Integer – short 2 bytes, -32,768 to 32,767 • Unsigned Short Integer – unsigned short 2 bytes, 0 to 65,535 integer • Long Integer – long 4 bytes, -2,147,483,648 to 2,147,483,647 • Unsigned Long Integer – unsigned long 4 bytes, 0 to 4,294,967,295 25

Integer and Long Integer Constants

• C++ allows you to control the amount of memory allocated to store an integer constant.

– You can force an integer constant to be stored as a long integer.

• Try not to use a lower case 'l' to designate a long integer constant.

l32 looks like 132 Instead L32 26

Program 2-10

// This program has variables of several of the integer types.

#include void main(void)

Program Output

{ We have made a long journey of 4276 miles.

int Checking; unsigned int Miles; long Days; Checking = -20; Our checking account balance is -20.

Exactly 184086 days ago Columbus stood on this spot.

Miles = 4276; Days = 184086; cout << "We have made a long journey of " << Miles; cout << " miles.\n"; cout << "Our checking account balance is " << Checking; cout << "\nExactly " << Days << " days ago "; cout << " Columbus stood on this spot.\n"; }

27

Program 2-11

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

#include

Program Output

void main(void) { int Floors, Rooms, Suites; The Grande Hotel has 15 floors with 300 rooms and 30 suites.

} Floors = 15; Rooms = 300; Suites = 30; cout << "The Grande Hotel has " << Floors << " floors\n"; cout << "with " << Rooms << " rooms and " << Suites; cout << " suites.\n";

28

Hexadecimal and Octal Constants

• Hexadecimal numbers are designated by placing a 0x in front of the number.

int num; num = 0x10; cout << num; • hexadecimal numbers use the digits 0 thru F • Octal numbers are designated by placing a 0 (zero) in front of the number.

int num; num = 010; cout << num; • Octal numbers use the digits 0 thru 7 Run sample Program hex_oct 29

Check Point

• Which of the following are illegal variable names:

x

R&D

99bottles

grade_report

July'97

Grade_Report1 TheSalesFiguresforFiscalYear1998 TheSalesFiguresforFiscalYear1999 12345678901234567890123456789012 30

The

char

Data Type

• The char data type is a 1-byte integer data type.

• It is used to store single character values.

– Characters are represented in the computer by numbers from 0 to 255.

• Most computers use the ASCII character set to represent both printable and unprintable characters.

– See appendix B of the text.

31

Character Constants

• Character constants are enclosed in single quotes ' ' and take one byte of storage.

– 'A' is stored as 65 (01000001 bin , 0X41).

• Character strings are enclosed in double quotes "" and take one byte per character plus one more for the null character.

– "A" is stored in two locations containing 65 and 0 respectively (01000001,00000000).

• Escape characters are always stored as a single character.

32

Program 2-12

// This program demonstrates the close relationship between // characters and integers.

#include using namespace std; int main() { char Letter; } Letter = 65; cout << Letter << endl; Letter = 66; cout << Letter << endl; return 0;

Program Output

A B 33

Program 2-13

// This program uses character constants #include using namespace std; int main() { char Letter; } Letter = 'A'; cout << Letter << endl; Letter = 'B'; cout << Letter << endl; return 0;

Program Output

A B 34

Strings

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

• Strings use a null terminator at the end to mark the end of the string.

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

35

Program 2-14

// This program uses character constants #include using namespace std; int main() { char Letter; } Letter = 'A'; cout << Letter << '\n'; Letter = 'B'; cout << Letter << '\n'; return 0;

Program Output

A B 36

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 use a null terminator at the end to mark 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.

37

Check Point

• What are the ASCII codes for C,F,W?

67 70 88 • Is "B" or 'B' a character constant?

'B' • How many bytes do the following character constants use?

'Q' , "Q", "Sales", \n 1 2 6 1 • Is this a valid C++ statement?

char letter = "Z"; No "" defines a character string not a character constant 38

Floating Point Data Types

• Floating point data types allow the use of fractional values.

• The values are stored in the computer in E notation.

• You can specify the precision for storing a floating point data type: – Single float – Double double 4 bytes +3.4E+38 8 bytes +1.7E+308 – Long Double long double 10 bytes +3.4E+4832 39

Floating Point Constants

• Floating point constants can be expressed in E notation or in decimal notation.

• Floating point constants are normally stored in double precision.

– Appending an F will force single precision • 32.75F takes 4 bytes – Appending an L will force long double precision • 3.275E1L takes 10 bytes 40

Program 2-15

// This program uses floating point data types #include void main(void) { float Distance; double Mass; Distance = 1.495979E11; Mass = 1.989E30; cout << "The Sun is " << Distance << " kilometers away.\n"; cout << "The Sun\'s mass is " << Mass << " kilograms.\n"; }

Program Output

The Sun is 1.4959e+11 kilometers away.

The Sun's mass is 1.989e+30 kilograms 41

The

bool

Data Type

• Allows the creation of one byte integer variables that can be used in logical expressions.

• True = 1 • False = 0 Note - Borland does not support this data type Concept - Boolean variables are set to either True or False. 42

Summary of Data Types

• Character • Integer • Unsigned integer • Short integer • Unsigned short integer or • Long integer • Unsigned long integer or • Single precision • Double precision • Long double precision char int unsigned or unsigned int short or short int unsigned short unsigned short int long or long int unsigned long unsigned long int float double long double 43

Determining the Size of Data Types

• The size of variables of each data type (in bytes) is not the same on all systems.

• C++ provides an instruction to determine the number of bytes used by your system for storing specific data types: int data_size; data_size = sizeof (

data type key word

); • Determine the size of the data types for your system.

44

Program 2-17

#include void main (void) { long double Apple; cout << “The size of an integer is “ << sizeof(int); cout << “ bytes.\n”; cout << “The size of a long integer is “ << sizeof(long); cout << “ bytes.\n”; cout << “An apple can be eaten in “ << sizeof(Apple); } cout << “ bytes!\n”;

Program Output

The size of an integer is 4 bytes.

The size of a long integer is 4 bytes.

An apple can be eaten in 10 bytes!

45

Variable Assignments and Initialization

• An assignment operation copies a value into a variable's memory location.

age = 30; • When a value is assigned to a variable as part of its declaration, it is called an initialization.

int age warning.

= 30; • If you attempt to use an uninitialized variable before it is assigned a value, the compiler will issue a – Using un-initialized or unassigned variables will yield unpredictable results.

46

Program 2-18

#include 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.

47

Program 2-19

// This program can't find its variable #include void main(void) { cout << Value; int Value = 100; 48

Arithmetic Operators

• There are three types of operators: – unary single operand – binary double operands – ternary three operands (x<0?y=10:z=20) • Binary operators: (-5) (6 + 7) + addition / subtraction * multiplication division % Modulus Concept - There are many operators for manipulating numeric values and performing arithmetic operations.

49

Program 2-20

// This program calculates hourly wages #include using namespace std; int main() { float RegWages, BasePay = 18.25, RegHours = 40.0; float OTWages, OTPay = 27.78, OTHours = 10; float TotalWages; } RegWages = BasePay * RegHours; OTWages = OTPay * OTHours; TotalWages = RegWages + OTWages; cout << "Wages for this week are $" << TotalWages << endl; return 0;

Program Output

Wages for this week are $1007.8

Press any key to continue 50

Comments

• Document your thought process for future reference.

• Communicate your thoughts to others reading your code.

• Incorrect comments are worse than no comments at all.

– update your comments each time you change your code.

Concept - Comments are notes of explanation intended to inform people and are ignored by the compiler.

51

Commenting

• C++ defines comments as anything after a // to the end of the line.

//This is a C++ comment • C requires a comment to begin with a /* and end with a */ /* This is a C comment */ • C comments can reside on multiple lines.

52

Program 2-21

// PROGRAM: PAYROLL.CPP

// Written by Herbert Dorfmann // This program calculates company payroll // Last modification: 3/30/96 #include using namespace std; int main() { float PayRate; float Hours; int EmpNum; // holds the hourly pay rate // holds the hours worked // holds the employee number (The remainder of this program is left out.) 53

Program 2-22

(bad comment example) // PROGRAM: PAYROLL.CPP

// Written by Herbert Dorfmann // Also known as "The Dorfmiester" // Last modification: 3/30/96 // This program calculates company payroll.

// Payroll should be done every Friday no later than // 12:00 pm. To start the program type PAYROLL and // press the enter key.

#include void main(void) { float PayRate; float Hours; int EmpNum; // Need the iostream.h file because the program uses cout.

// This is the start of function main.

// This is the opening brace for main.

// PayRate is a float variable. It holds the hourly pay rate.

// Hours is a float variable too. It holds the hours worked.

// EmpNum is an integer. It holds the employee number.

(The remainder of this program is left out.) 54

Program 2-23

(Comments in ‘c’ style) /* PROGRAM: PAYROLL.CPP

Written by Herbert Dorfmann This program calculates company payroll Last modification: 3/30/96 */ #include void main(void) { float PayRate; float Hours; int EmpNum; /* PayRate holds hourly pay rate */ /* Hours holds hours worked */ /* EmpNum holds employee number */ (The remainder of this program is left out.) 55