Chap 2 c++

49
CHAPTER TWO EDITING, COMPILING AND EXECUTING A SIMPLE C++ PROGRAM REFERENCES: 1. C++ How to program, Deital, H.M. and Deital, P.J. Prentice Hall, Eaglewood (NJ), 2008. 2. Code complete: A practical Handbook of Software Construction. McConnell, S. Microsoft Press, Redmond (WA), 1993. 3. C++ Program Design An Introduction to Programming and Object-Oriented Design. LECTURER: Samson Mekbib

Transcript of Chap 2 c++

Page 1: Chap 2 c++

CHAPTER TWO

EDITING, COMPILING AND EXECUTING A

SIMPLE C++ PROGRAM

REFERENCES:

1. C++ How to program, Deital, H.M. and Deital,

P.J. Prentice Hall, Eaglewood (NJ), 2008.

2. Code complete: A practical Handbook of

Software Construction. McConnell, S. Microsoft

Press, Redmond (WA), 1993.

3. C++ Program Design An Introduction to

Programming and Object-Oriented Design.

LECTURER: Samson Mekbib

Page 2: Chap 2 c++

POINTS TO REMEMBER (CHAP. 1)

The speed of a computer is usually expressed in cycles per second. Typical machines operate at 1 to 3 Gigahertz or 1 to 3 billion cycles per second.

Computers use a binary number system. A binary digit is called a bit.

The basic unit of storage in a computer is byte, or 8 bits.

Negative numbers are usually stored in two’s complement representation.

The central processing unit (CPU) is the brain of the computer where arithmetic and logical operations are performed.

Current desktop machines commonly have a main memory or RAM of 512 megabytes (MB) up to 3 gigabytes (GB).

The capacity of the hard disk commonly found in desk top programs typically ranges from 80 to 200 GB.

2

Page 3: Chap 2 c++

CONT.…

A programming language is a language that gives commands or instructions to a computer.

A compiler translates a programming language to machine language. A machine language consists of primitive operations (binary codes) that a computer can perform directly.

Application software is software that solves a particular problem or provides a particular service.

Systems software is software that supports the development and execution of other programs.

An operating system is system software that controls and manages the computing resources such as the memory, the input and output devices, and the CPU.

An algorithm is a detailed, step-by-step description of how to perform a given task.

3

Page 4: Chap 2 c++

LESSON OUTCOMES (CHAP. 2)

1. Become familiar with functions, special symbols, and identifiers in C++

2. Explore simple data types

3. Discover how a program evaluates arithmetic expressions

4. Learn about assignment and declaration statements of variables and constants

4

Page 5: Chap 2 c++

C++ : THE

FUNDAMENTALS

BASIC PROGRAMMING

ELEMENTS AND CONCEPTS

5

Page 6: Chap 2 c++

// Program: Display greetings

// Author(s): your name

// Date: 02/24/2014

#include <iostream>

#include <string>

using namespace std;

int main() {

cout << "Hello world!" << endl;

return 0;

}

A FIRST PROGRAM -

GREETING.CPP

Preprocessor

directives

Insertion

statement Ends executions

of main() which ends

program

Comments

Function

Function

named

main()

indicates

start of

program

Provides simple access

6

Page 7: Chap 2 c++

GREETING OUTPUT

7

Page 8: Chap 2 c++

COMMENTS

Allow prose or commentary to be included in program

Importance

• Programs are read far more often than they are written

• Programs need to be understood so that they can be maintained

C++ has two conventions for comments

• // single line comment (preferred)

• /* long comment */ (save for debugging)

Typical uses

• Identify program and who wrote it

• Record when program was written

• Add descriptions of modifications

8

Page 9: Chap 2 c++

PREPROCESSOR DIRECTIVES

The first program example (Hello World) contains the following lines at the

beginning of the program:

#include <iostream>

#include <string>

These lines will appear at the beginning of almost all our programs that uses the iostream library to perform input or output commands like (cout, cin) and the manipulator endl.

The first two lines that start with ‘#’ are called preprocessor directives. The preprocessor is a program that runs before the compiler. Its job is to handle directives that control what source code the compiler sees as input.

The include directive instructs the preprocessor to copy the contents of the specified file into the program.

The two files included, iostream and string, contain the output facilities that the program will use.

The left and right angle brackets surround the filenames indicates that these files are system files that can be found in a special system directory.

9

Page 10: Chap 2 c++

STANDARD NAMESPACE

The first program example (Hello World) contains the

following line:

using namespace std;

These line indicates that the program will be using objects

that are named in a special region called std.

This special region contains the names of many predefined

objects and commands in C++, such as ‘cout’, which will

be mentioned in our code.

This line will appear at the beginning of almost all our

codes.

Allows you to use cout and endl without the prefix std::

10

Page 11: Chap 2 c++

USING NAMESPACE CONTD.

If we do not use the statement ‘using namespace std;’ at the beginning

of the program, then we need to insert “std::” before every command like

cout, cin, endl … etc, which will be a tedious thing to do (see the following

example).

// Program: Display greetings

// Author(s): your name here

// Date: 02/24/2014

#include <iostream>

#include <string>

int main()

{

std::cout << "Hello world!" << std::endl;

return 0;

}

11

Page 12: Chap 2 c++

OTHER STATEMENTS

Int main ()

{

cout << "Hello world!" << endl;

return 0;

}

‘int main ()’ is the heading of the function main.

The first left brace ‘{‘ after ‘int main ()’ indicates the beginning of the (body) of

the function main.

The right brace ‘}’ (at the last line of the program) matches the first left brace

and marks the end of the body of the function main.

The last statement ‘return 0’ returns the value 0 to the operating system and

terminates the program execution.

The manipulator ‘endl’ stands for end line and it basically sends the cursor to

the next line.

‘<<‘ these double less than signs are called insertion operators. In this

example they insert the text “Hello World!” into the cout (output) stream and

also insert an end line.

12

Page 13: Chap 2 c++

Definitions

Extraction

Definition with

initialization

EXAMPLE 1: AREA.CPP

#include <iostream>

using namespace std;

int main() {

// Extract length and width

cout << "Rectangle dimensions: ";

float Length;

float Width;

cin >> Length >> Width;

// Compute and insert the area

float Area = Length * Width;

cout << "Area = " << Area << " = Length "

<< Length << " * Width " << Width << endl;

return 0;

}

13

Page 14: Chap 2 c++

VISUAL C++ IDE WITH

AREA.CPP

14

Page 15: Chap 2 c++

AREA.CPP OUTPUT

15

Page 16: Chap 2 c++

INPUT AND OUTPUT COMMANDS

cout << "Rectangle dimensions: ";

cin >> Length >> Width

cout <<“Area = “<<Area << “ = Length “

<< Length << “ * Width “ << Width <<endl;

The command cout – pronounced c-out is used to send data to the console window (command prompt) so that the user can see it.

‘<<‘ these double less than signs are called insertion operators. In this example they insert the text “Rectangle dimensions: ”, “Area =“, “Length “ into the cout (output) stream and also insert an end line.

The command cin – pronounced c–in uses the input stream to take input from the console and put it into the already defined variable. Hence c-in is always preceded by a definition statement (note float Length, float Width).

‘>>‘ these double greater than signs are called extraction operators. In this example they take the input values for the variables Length and Width.

Notice the opposite directions of the insertion and extraction operators indicating the opposite directions of data flow.

16

Page 17: Chap 2 c++

EXAMPLE

17

Page 18: Chap 2 c++

EXAMPLE

18

Page 19: Chap 2 c++

C++ TOKENS

The smallest individual unit of a program written in any language is called a token.

C++ tokens are divided into special symbols, word symbols, and identifiers:

I. Special Symbols

+ - * / . ; ? , <= != == >=

N.B. the first four are mathematical operators, punctuation marks like , and ; are used in C++ to separate items in a list and end a statement respectively.

II. Word Symbols (Reserved Words)

Int, float, double, char, const, void, return

(only a short list, there are more reserved words in C++, refer to the full list from books).

19

Page 20: Chap 2 c++

C++ TOKENS

III. Identifiers

A third category of tokens is identifiers.

Identifiers are names of things that appear in programs, such as

variables, constants, and functions.

Some identifiers are predefined, others are defined by the user

All identifiers must obey C++’s rules for identifiers

• A C++ identifiers consist only of letters, digits, and the underscore

character (_), and must begin with a letter or underscore,

• C++ is case sensitive – uppercase and lowercase letters are

considered different letters. Hence the identifier X is not the same

as the identifier x.

20

Page 21: Chap 2 c++

EXAMPLES OF

ILLEGAL IDENTIFIERS

Illegal Identifier Description

Employee salary There can be no space

between employee and

salary

Hello! The exclamation mark can

not be used in an identifier

one+two The symbol + cannot be

used in an identifier

2nd An identifier cannot begin

with a digit

21

Page 22: Chap 2 c++

IDENTIFIERS CONTD.

Identifiers should be

• Short enough to be reasonable to type (single word is norm)

• Standard abbreviations are fine

• Long enough to be understandable

• When using multiple word identifiers capitalize the first letter of each word

Examples

• Min

• Temperature

• CameraAngle

• CurrentNbrPoints

22

Page 23: Chap 2 c++

FUNDAMENTAL C++

OBJECTS

C++ has a large number of fundamental or built-in object types

The fundamental object types fall into one of three categories

• Integer objects

• Floating-point objects

• Character objects

1 1.28345

Z 5

P 3.14

23

Page 24: Chap 2 c++

C++ DATA TYPES

Integral- is a data type that deals with integers, or numbers without a

decimal part

Integral data types are further classified into nine categories:

• char, short, int, long, bool, unsigned char, unsigned short, unsigned int,

and unsigned long

Why are there so many categories of the same data type?

Every data type has a different set of values associated with it.

Example:

• The char data type is used to represent integers between -128 and 127

• The int data type is used to represent integers between -2147483648

and 2147483647

• The data type short is used to represent integer between -32768 and

32767

24

Page 25: Chap 2 c++

SIMPLE DATA TYPE

Since every data type has a different set of values associated with it, the

choice of data types depends on how big a number your program needs to

deal with

N.B. in the early days of programming computers and main memory was

expensive and as a result programmers had to optimize the use of memory.

Nowadays memory constraints may still be a concern for programs written

for applications such as wristwatch

In this course we focus on the integral variables int, bool and char

The logical data type bool has only two values: true and false

Logical (Boolean) expressions will be discussed latter in the course. For now

note that bool, true, and false are reserved words in C++

Data

Type

Values Storage

(in bytes)

Int -2147483648 (=-231) to 2147483647 (=231 – 1) 4

bool true and false 1

char 128 (=-27) to 127 (=27 - 1) 1

25

Page 26: Chap 2 c++

int Data Types

Integers in C++, as in mathematics, are number such as

the following

-6345, -67, 0 83, 38761, 763

Note the following two rules

• Positive integers do not need a + sign in front of them

• No commas are used within an integer. Recall that in C++,

commas are used to separate items in a list. So 36,456 would

be interpreted as two integers: 36 and 456.

26

Page 27: Chap 2 c++

char Data Types

The data type char is the smallest integral data type.

In addition to dealing with small numbers (-128 to 127), the char data

type is used to represent characters – letters, digits and special

symbols

Therefore the char data type can represent every key in your

keyboard

When using the char data type you enclose each character

represented within single quotation marks

‘A’, ‘a’, ‘0’, ‘*’, ‘+’, ‘$’, ‘&’, ‘ ‘

N.B. a blank space is a character and is written as ‘ ‘, with a space

between single quotation marks.

The data type char allows only one symbol to be placed between the

single quotation marks. 27

Page 28: Chap 2 c++

Floating-Point Data Types

C++ provides the floating-point data type to represent real or decimal numbers (e.g. 75.924, 0.27, 0.0000453, -1.482)

In the C++ floating-point notation, the letter E stands for the exponent

(e.g. -0.18 in C++ floating-point representation will be -1.800000E-1)

C++ provides three floating-point object types (that differ in set of

values)

• float

• double

• Long double

float represent any real number between -3.4E+38 and 3.4E+38. Memory allocated for float data type is 4 bytes

double represent any real number between -1.7E+308 and 1.7E+308. Memory allocated for double data types is 8 bytes

If you are dealing with decimal numbers, for the most part you need the float type; if you need accuracy to more than six or seven decimal place, you can use the double data type.

28

Page 29: Chap 2 c++

EXAMPLES

char Response;

int MinElement;

float Score;

float Temperature;

int i;

int n;

char c;

float x;

Objects are uninitialized with

this definition form

(Value of a object is

whatever is in its

assigned memory location)

29

Page 30: Chap 2 c++

SIMPLE ARITHMETIC CPP

30

Page 31: Chap 2 c++

SIMPLE ARITHMETIC CPP

31

Page 32: Chap 2 c++

ARITHMETIC

OPERATORS

Common

• Addition +

• Subtraction -

• Multiplication *

• Division /

• Mod %

Write m*x + b

not mx + b

32

Page 33: Chap 2 c++

INTEGER DIVISION

Integer division produces an integer result

• Truncates the result

Examples

• 3 / 2 evaluates to 1

• 4 / 6 evaluates to 0

• 10 / 3 evaluates to 3

33

Page 34: Chap 2 c++

MOD

Produces the remainder of the division

Examples

• 5 % 2 evaluates to 1

• 12 % 4 evaluates to 0

• 4 % 5 evaluates to 4

34

Page 35: Chap 2 c++

INTEGRAL EXPRESSIONS CPP

35

Page 36: Chap 2 c++

FLOATING-POINT EXPRESSIONS CPP

36

Page 37: Chap 2 c++

EVALUATING MIXED

EXPRESSIONS

Rules when evaluating a mixed expression:

1. If the operator has the same type of operands (that is, either both integers or both floating-point number)the operator is evaluated according to the type of the operands. Integer operands thus yield in integer results; floating-point numbers yield a floating-point number.

2. If the operator has both types of operands (i.e. one is an integer and the other is a floating-point number), then during calculation the integer is changed to a floating-point number with the decimal part zero, and the result will be a floating point number.

3. The entire expression is evaluated according to the precedence of operators.

37

Page 38: Chap 2 c++

MIXED EXPRESSIONS CPP

38

Page 39: Chap 2 c++

OPERATORS AND

PRECEDENCE

Consider m*x + b which of the following is it equivalent to

(m * x) + b

m * (x + b)

Operator precedence tells how to evaluate expressions

Standard precedence order

() Evaluate first, if nested innermost done first

* / % Evaluate second. If there are several, then evaluate from left-to-right

+ - Evaluate third. If there are several, then evaluate from left-to-right

39

Page 40: Chap 2 c++

OPERATOR

PRECEDENCE

Examples

20 - 4 / 5 * 2 + 3 * 5 % 4

(4 / 5)

((4 / 5) * 2)

((4 / 5) * 2) (3 * 5)

((4 / 5) * 2) ((3 * 5) % 4)

(20 -((4 / 5) * 2)) ((3 * 5) % 4)

(20 -((4 / 5) * 2)) + ((3 * 5) % 4)

40

Page 41: Chap 2 c++

String TYPE

So far we have seen simple data types consisting of numbers and characters

When a character value is more than one it is called a string

The string data type handles values such as a person’s name in C++ programming

In C++ strings are enclosed in double quotation marks (not in single quotation marks, as are the char data types)

A string containing no character is called a null or empty string

Examples:

• “William Jacob”

• “Mickey”

• “”

N.B. Every character in a string has a relative position in the string. The position of the first character is 0, the position of the second character is 1, and so on.

The length of a string is the number of characters in it

(e.g. the string “William Jacob” has a string length of 13) 41

Page 42: Chap 2 c++

DEFINING AND INITIALIZING

VARIABLES AND CONSTANTS

Data must be loaded into main memory before it can be manipulated during

program execution

Storing data in the computer’s memory involves two steps:

• Instruct the computer to allocate memory

• Include statement in the program to put data into the allocated memory

When you instruct the computer to allocate memory, you tell it not only what

names you use for each memory location, but also what type of data to store

in those memory locations

To allocate memory, we use C++’s declaration statements

When an object is defined using the basic form, the memory allotted to it

contains random information

You could also specify the desired value at the time of definition

42

Page 43: Chap 2 c++

VARIABLE & CONSTANT

DECLARATIONS

All variables must be declared before they are used.

The syntax for variable declarations is as follows

SYNTAX for variable declaration

• Type_Name Variable_Name_1, Variable_Name_2, … ;

Examples:

• int count, numberOfDragons, numberOfTrolls;

• double distance;

• const double Rate;

43

Page 44: Chap 2 c++

ASSIGNMENT STATEMENTS

The most direct way to change the value of a variable is to use an

assignment statement

In an assignment statement, first the expression on the right-hand side of the

equal sign is evaluated and then the variable on the left-hand side of the

equal sign is set equal to this value

SYNTAX of assignment statement

• Variable = Expression;

In C++, = is called the assignment operator.

Examples:

• distance = velocity * time;

• x = 10;

• num = num + 2; (N.B. this statement means “evaluate whatever value

is in num, add 2 to it, and assign the new value to the memory location

num.”)

44

Page 45: Chap 2 c++

INITIALIZING VARIABLES IN

DECLARATIONS

You can initialize a variable (that is, give it a value) at the time that you

declare the variable

SYNTAX of initializing a variable in declarations

• For single variable

Type_Name Variable_Name = Expression;

• For more than one number of variables of the same data type

Type_Name Variable_Name_1 = Expression_for_Value_1,

Variable_Name_2 = Expression_for_Value_2, …;

Examples:

• double distance = 999.99;

• int x = 10;

• int count = 0, limit = 10, fudgeFactor = 2;

45

Page 46: Chap 2 c++

EXAMPLES

int FahrenheitFreezing = 32;

char FinalGrade = 'A';

cout << "Slope of line: ";

float m;

cin >> m;

cout << "Intercept: ";

float b;

cin >> b;

cout << "X value of interest: ";

float x;

cin >> x;

float y = (m * x) + b;

46

Page 47: Chap 2 c++

ASSIGNMENT COMPATIBILITY

As a general rule, you can not store a value of one type in a variable of another

For example, most compilers will object to the following:

int intVariable;

intVariable = 2.99;

*** The problem is a type mismatch

However assigning int values to double variables is possible (i.e. it is ok to assign a value of an integer type to a variable of a floating-point type)

Example:

double doubleVariable;

doubleVariable = 2;

The value of a constant once assigned cannot be changed. For example the following syntax will create an error:

const int K = 3;

K = 10;

47

Page 48: Chap 2 c++

EXAMPLE CPP

48

Page 49: Chap 2 c++

NEXT CHAPTER

Learn how to debug syntax errors

Explore how to properly structure a program, including

using comments to document a program

How to solve and create a logical expression

How to use operators AND and OR

49