Introduction to C++ Programming

70
©2011, Regis University 1 Introduction to C++ Programming

description

Introduction to C++ Programming. Introduction. The C++ language will be used as a tool to learn about programming You will learn how to write structured C++ programs Object-oriented aspects of C++ (objects, templates, etc) will NOT be covered until CS432. C++ Programming Concepts. - PowerPoint PPT Presentation

Transcript of Introduction to C++ Programming

Page 1: Introduction to C++ Programming

©2011, Regis University 1

Introduction to C++

Programming

Page 2: Introduction to C++ Programming

2

Introduction The C++ language will be used as a

tool to learn about programming

You will learn how to write structured C++ programs

Object-oriented aspects of C++ (objects, templates, etc) will NOT be covered until CS432

Page 3: Introduction to C++ Programming

3

C++ Programming Concepts

To write a C++ program, we need:

Text editor

C++ compiler

Bloodshed Dev-C++ contains an editor and a compiler in one

This is known as an IDE (Integrated Development Environment)

Page 4: Introduction to C++ Programming

4

Running C++ Programs

Use an editor to create/edit C++ code in a text file C++ filenames ended with extension .cpp

Compile and link the C++ file

Execute the executable file created

If find bugs or errors, go back to the first step and correct them and try again.

Page 5: Introduction to C++ Programming

5

A Simple C++ program: #include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!"; return 0;}

(Each line is explained on the following slides)

Page 6: Introduction to C++ Programming

6

A Simple C++ program:

Tells compiler to include code from the iostream library for use of input and output routines.

#include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!"; return 0;}

Page 7: Introduction to C++ Programming

7

A Simple C++ program:

Tells compiler to use a standard environment.(The first 2 lines must appear in ALL your programs)

#include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!"; return 0;}

Page 8: Introduction to C++ Programming

8

A Simple C++ program:

Comment for the programmer – lines beginning with "//" are ignored by the compiler

#include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!"; return 0;}

Page 9: Introduction to C++ Programming

9

A Simple C++ program:

C++ programs are built using functions. A C++ program must contain at least one function, called main. This is the main function “header”.

NoteYour text uses:

void main()

but our compiler requires:

int main()

and the return of an integer.

#include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!"; return 0;}

Page 10: Introduction to C++ Programming

10

A Simple C++ program:

Left curly brace marks beginning andright curly brace marks end of the main function

#include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!"; return 0;}

Page 11: Introduction to C++ Programming

11

A Simple C++ program:

cout displays output, in this case, Hello World! to the monitor

#include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!"; return 0;}

Page 12: Introduction to C++ Programming

12

A Simple C++ program:

return tells the program to exit from the main

function. By default, returning 0 implies success.

#include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!"; return 0;}

Page 13: Introduction to C++ Programming

13

A Simple C++ program:Sample Run

When the program is executed, this is the output:

Page 14: Introduction to C++ Programming

14

Identifiers Identifiers are the words that a programmer

uses to name things in a program

An identifier can be made up of letters, digits, and the underscore character

An identifier cannot begin with a digit

C++ is case sensitive, therefore num and Num are different identifiers

Keywords CANNOT be identifiers (see next slide)

Page 15: Introduction to C++ Programming

15

Keywords

C++ keywords (do NOT use as Identifiers) :

asm auto bool break casecatch char class const const_castcontinue default delete do doubledynamic-cast else enum explicit externFALSE float for friend gotoif int long mutable namespacenew operator private register returnShort signed sizeof static static-caststruct switch template this throwtry TRUE typedef typeid typenameunion unsigned using virtual voidvolatile wchar_t while

Page 16: Introduction to C++ Programming

16

Data

You can store each piece of program data as: a Constant

or a Variable

You will assign an identifier (name) to: each constant each variable

Page 17: Introduction to C++ Programming

17

Each piece of data stored in a program must also have a type. Three basic C++ data types are:

int - whole numbers // No commas or leading zeros in number

double - numbers with fractional parts// Has a decimal point

char - a single ASCII character // Enclosed in single quotes

Data Types

Page 18: Introduction to C++ Programming

18

Variables Variables are containers used to hold

input data intermediate data output data

in your program (think of them as named chunks of memory)

A variable will occupy a number of bytes in Main Memory

The number of bytes allocated to a variable depends on the type of data that will be stored in it (e.g. numbers, characters, etc.)

Page 19: Introduction to C++ Programming

19

Declaring Variables Declaring a variable will: -

define its type - reserve a memory cell for it - give the memory cell a name (an identifier)

Format: type variable-list;

Examples:char initial; int num, count; double gpa;

Page 20: Introduction to C++ Programming

20

Variables in Memory

int numStudents; …

int average, max;

data typevariable name(s)

double total; …

9200920092049204

92089208921292129216921692209220922492249228922892329232

numStudents:

average: max:

total:

Memory

The value stored in a variable is initially garbage, and changes as the program runs.

Page 21: Introduction to C++ Programming

21

Constants A constant is similar to a variable, except that

its value is set by the programmer and CANNOT change The compiler will issue an error if you try to

modify a constant

Why use constants? Gives names to otherwise unclear literal values Facilitates easier changes to the code Prevents inadvertent errors

Page 22: Introduction to C++ Programming

22

Declaring Constants Declaring a constant will:

- define its type and reserve a memory cell for it- give the memory cell a name (an identifier)- store a value in the memory cell

Since the value is set by the programmer, the value must be known when the program is written

Format: const type constant-name = value;

Examples:const double PI = 3.14; const int AGE = 33; const char YES = 'Y';

Page 23: Introduction to C++ Programming

23

Constants in Memory

The value stored in a constant CANNOT change as the program runs.

const int DOZEN = 12; …

const double PI = 3.14;

data type

constant name constant

value

6200620062046204

62086208621262126216621662206220622462246228622862326232

DOZEN:

PI:

Memory

12

3.14

Page 24: Introduction to C++ Programming

24

Declaring Constants/Variables

Declare constants and variables at the top of the main function

Use good identifiers to make code "Self-Documenting"

Follow the identifier rules:

Should begin with a letter, followed by letters, digits and underscores

Are case-sensitive. Standard conventions are: Variable identifiers should begin with a lowercase letter

Constants identifiers should be ALL uppercase

Page 25: Introduction to C++ Programming

25

Constants/Variables Example

#include <iostream>using namespace std;int main(){ const char INITIAL = ‘P’; int num; :

Constant INITIAL and variable num are declared at the top of the main function

Page 26: Introduction to C++ Programming

26

Comments

There are two types of C++ comments:

Single-line comments use //…// This comment runs to the end of the current line

Multi-lines comments use /* … */ /* This comment runs to the ending

symbol, even onto new lines */

Comments are ignored by the compiler.

Page 27: Introduction to C++ Programming

27

Function Statements

Function statements are located between the function’s curly braces ''{" and "}"

Statements are separated by semicolons (;)

Statements can take up more than one line

Extra blanks are ignored - used for readability

Page 28: Introduction to C++ Programming

28

Assignment Statements

An assignment statement changes the value of a variable

The assignment operator is the = sign

int count, num;char ltr;

count = 0;num = 55;ltr = ‘A’;

The value on the right is stored in the variable on the left Any value that was in the variable is overwritten

Memory

num: 55ltr:

count:

A

0

Page 29: Introduction to C++ Programming

29

Assignment Statements

You can declare a variable and assign an initial value to it at the same time:

int count = 0;int max = 50;

This is called “initializing” a variable

Memory

count:

50max:

0

You can only assign a value to a variable that is compatible with the variable's declared type

Page 30: Introduction to C++ Programming

30

Arithmetic Expressions

An expression is a combination of operators and operands

Arithmetic expressions compute numeric results using arithmetic operators:

Addition + Subtraction -Multiplication *Division /Remainder %

Page 31: Introduction to C++ Programming

31

Operator Results

Arithmetic operators can be used with any numeric type

An operand is a number or variable used by the operator

Result of an operator depends on the types of operands If both operands are int, the result is int If one or both operands are double, the result is

double

Page 32: Introduction to C++ Programming

32

Division and Remainder If both operands to the division operator (/) are

integers, the result is an integer (the fractional part is discarded)

The modulus operator (%) returns the remainder after dividing the second operand into the first (both operands must be integers)

8 / 12 equals?

14 / 3 equals? 4

0

14 % 3 equals?

8 % 12 equals?

2

8

Page 33: Introduction to C++ Programming

33

Operator Precedence Operators can be combined into complex

expressions: result = total + count / max - offset;

Precedence rules (same as default math rules)

Parenthesis are done first

Division, multiplication and modulus are done second (left to right)

Addition and subtraction are done last (left to right)

Page 34: Introduction to C++ Programming

34

Assignment Revisited You can consider assignment as another operator,

with a lower precedence than the arithmetic operators

First the expression on the right hand side of the = operator is evaluated, in

precedence order

Then the result is stored in thevariable on the left hand side

answer = sum / 4 + MAX * lowest;14 3 2

Page 35: Introduction to C++ Programming

35

Memory

count: 8

Assignment Revisited The right and left hand sides of an assignment

statement can contain the same variable

First, 20 is added to theoriginal value of count

Then the result is stored back into count(overwriting the original value)

count = count + 20; 28

count = 8;

Page 36: Introduction to C++ Programming

36

Spacing

Use spacing to make arithmetic assignment statements more readable!

Which is easier to read?

ans=num1+num2*num3;or

ans = num1 + num2 * num3;

Page 37: Introduction to C++ Programming

37

Arithmetic Equivalencies

Mathmatical Formulas: c = a2 + b2

num = 1 x(x+y)

C++ Equivalent Expressions: c = (a * a) + (b * b);

num = 1 / ( x * (x + y));

Page 38: Introduction to C++ Programming

38

Compound Assignment Operators

Compound assignment operators are operators which provide a shortcut when adding, subtracting, multiplying, or dividing a number to/by itself.

Operators: += -= *= /= %=

A op= B is the same as A = A op B

A += B A = A + B

A -= B A = A - B

A *= B A = A * B

A /= B A = A / B

A %= B A = A % B

Page 39: Introduction to C++ Programming

39

Increment/Decrement Operators

The increment operator (++) adds one to the value of the variable. The decrement operator (--) subtracts one from the value of the variable.

x++;++x; // both increase x by 1

x--;--x; // both decrease x by 1

When used alone with one variable, the following three statements are equivalent:

x++;++x;x = x + 1;

Page 40: Introduction to C++ Programming

40

Increment/Decrement Operators

When used within an expression, however, the placement matters.

++ (pre-increment operator) when the ++ is placed on the left-hand side of a variable (++x).

Variable is incremented BEFORE the rest of expression is evaluated:

A = ++B * Num; is equivalent to: B = B + 1;A = B

* Num;

Page 41: Introduction to C++ Programming

41

Increment/Decrement Operators

-- (pre-decrement operator)When the -- is placed on the left-hand side of a variable (--x).

Variable is decremented BEFORE the rest of expression is evaluated: 

A = --B * Num; is equivalent to: B = B - 1;A = B * Num;

Page 42: Introduction to C++ Programming

42

Increment/Decrement Operators

++ (post-increment operator) when the ++ is placed on the right-hand side of a variable (x++).

Variable is incremented AFTER the rest of expression is evaluated:

A = B++ * Num; is equivalent to A = B * Num;B = B + 1;

Page 43: Introduction to C++ Programming

43

Increment/Decrement Operators

-- (post-decrement operator) when the -- is placed on the right-hand side of a variable (x--).

Variable is decremented AFTER the rest of expression is evaluated: 

A = B-- * Num; is equivalent to A = B * Num;

B = B - 1;

Page 44: Introduction to C++ Programming

44

Input/Output (I/O) We use two input/output statements

one for output (cout)

one for input (cin)

In any program that uses these statements, you must have the following lines at the very beginning of the code:

#include <iostream>using namespace std;

Page 45: Introduction to C++ Programming

45

Output Statement

cout – writes output to the monitor

Format:cout << field1 << field2 << ... << fieldN;

A field can be: - a string of characters (text) in double quotes

- a variable- endl (end line/new line)

Page 46: Introduction to C++ Programming

46

Output Example

Example Code:cout << "Hello" << endl; sum = 10; cout << "Sum is " << sum << endl; cout << "Enter a number:";

Resulting Output:

HelloSum is 10 Enter a number:

Page 47: Introduction to C++ Programming

47

Input Statement

cin - gets input from the keyboard (typed in by the user)

Format:cin >> field;

Here the field must be a variable name

Page 48: Introduction to C++ Programming

48

Example: cout << "Enter pay amount: "; cin >> pay;

Resulting Output: Enter pay amount: 9.50

cin stores the number typed at keyboard (9.50) into the variable pay in memory

Input Example

Memory

pay: 9.50

Page 49: Introduction to C++ Programming

49

I/O Stream: Output

Escape sequences:

\" to display a double quote

\t to display a tab

\\ to display a backslash

\a to cause computer to beep

Page 50: Introduction to C++ Programming

50

I/O Stream: Output Formatting:

Must include iomanip library to use functions: setprecision(n) - sets number of decimal places

displayed setw(n) - sets width of output

Example:float num = 4.557;cout << setprecision(1) << setw(5) << num;Result: displays 4.6 with two leading spaces 4.6

Page 51: Introduction to C++ Programming

51

Variables during Program Execution (1/8)

The next seven slides will walk you through the execution of the program below:

#include <iostream>using namespace std;

int main(){ int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; return 0;}

Page 52: Introduction to C++ Programming

52

Variables during Program Execution (2/8)

During Compile Time:

#include <iostream>using namespace std;

int main(){ int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; return 0;}

Allocate 2 bytes of main memory for each int variable, and assign names num1 and num2

Executable Program

Main Memorynum2

num1

Page 53: Introduction to C++ Programming

53

Variables during Program Execution (3/8)

Allocate 4 bytes of main memory for

the double variable and assign name

avg

Executable Program

yyyy

num1

num2

avg

During Compile Time:

#include <iostream>using namespace std;

int main(){ int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; return 0;}

Page 54: Introduction to C++ Programming

54

Variables during Program Execution (4/8)

Main Memory

Executable Program

yyyy

kkkk

5

avg

num1

num2During Execution Time:

#include <iostream>using namespace std;

int main(){ int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; return 0;}

Store the integer 5 (000000000000010

1) in location allocated to num2

Page 55: Introduction to C++ Programming

55

Variables during Program Execution (5/8)

Main Memory

Executable Program

yyyy

kkkk

5

7

avg

num1

num2

Store the integer 7 (000000000000011

1) in location allocated to num1

During Execution Time:

#include <iostream>using namespace std;

int main(){ int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; return 0;}

Page 56: Introduction to C++ Programming

56

Variables during Program Execution (6/8)

Main Memory

Executable Program

yyyy

kkkk

5

7

6.0avg

num1

num2

Read contents of bytes allocated to num1 and num2 from Main Memory. Add the values and divide by 2. End result will be written into the bytes allocated to the variable avg

During Execution Time:

#include <iostream>using namespace std;

int main(){ int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; return 0;}

Page 57: Introduction to C++ Programming

57

Variables during Program Execution (7/8)

Main Memory

ScreenExecutable Program

yyyy

kkkk

5

7

6.0

Avg is 6.0

avg

num1

num2

Send the text “Avg is” to the screen.Then read the value of avg from Main Memory and send that value to the screen.

During Execution Time:

#include <iostream>using namespace std;

int main(){ int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; return 0;}

Page 58: Introduction to C++ Programming

58

Variables during Program Execution (8/8)

Main Memory

Executable Program

yyyy

kkkk

5

7

6.0avg

num1

num2

Program exits main function and terminates.

During Execution Time:

#include <iostream>using namespace std;

int main(){ int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; return 0;}

ScreenAvg is 6.0

Page 59: Introduction to C++ Programming

59

Age Program Description

Write a program to: compute and display a

person’s age given their year of birth as

input

Page 60: Introduction to C++ Programming

60

Age Program Design What are the program inputs?

Year of Birth needs a variable What are the program outputs?

Age needs a variable Are there any known values the programmer will

set? Current year needs a constant

How do we calculate the output value? Age = Current Year – Year of Birth formula

Page 61: Introduction to C++ Programming

61

Algorithm Pseudocode:

Prompt for user’s year of birth Read in user’s year of birth Compute user’s age Display user’s age

Page 62: Introduction to C++ Programming

62

Age Program Code#include <iostream>using namespace std;

int main() { const int NOW_YR = 2006; int birthYr, age;

cout << "Enter year of birth: "; cin >> birthYr; age = NOW_YR - birthYr; cout << "Age after this year's birthday is "; cout << age; return 0;}

(Explanation on following slides)

Page 63: Introduction to C++ Programming

63

Age Program Explanation

const int NOW_YR = 2006; /* defines a constant NOW_YR and stores value 2006 into it */

2006

1962 birthYr: age:

cout << "Enter year of birth: ";// displays prompt to the screen

int birthYr, age;// defines two integer variables, birthYr and age

cin >> birthYr;/* reads the year entered by the user

and stores it into variable birthYr */

Screen:Enter year of birth: 1962

Memory

NOW_YR:

Page 64: Introduction to C++ Programming

64

Age Program Explanationage = NOW_YR - birthYr;

/* calculates age by subtracting

birthYr from NOW_YR*/

2006Memory

NOW_YR:

1962 birthYr: age:

Screen:Enter year of birth: 1962

cout << age;// displays value stored in variable age on same line as

message

cout << "Age after this year's birthday is ";// displays text message

44

Age after this year’s birthday is 44

Page 65: Introduction to C++ Programming

65

Running Programs on your C++ Compiler

If you type the programs shown in this slide presentation into your compiler and execute them, there will be a problem:

The DOS input/output screen will disappear before you have a chance to read your results (it will look like nothing happened).

The next slides will show you how to make the DOS screen stay open.

Page 66: Introduction to C++ Programming

66

Keeping the DOS screen open

Add the following lines to EVERY C++ program file that you create:

At the BOTTOM of the file, just BEFORE the "return 0;" statement, add:

cout << endl << endl;system("PAUSE");

Page 67: Introduction to C++ Programming

67

ExampleThe original simple program from slide #4 becomes:

#include <iostream>using namespace std;

//Displays greeting int main(){ cout << "Hello World!";

cout << endl << endl; system("PAUSE"); return 0;}

Page 68: Introduction to C++ Programming

68

Example Output

And the program output becomes:

Page 69: Introduction to C++ Programming

69

Exercise

Type the Hello World code from the previous 2 slides into your compiler.

Compile and run the code.

Page 70: Introduction to C++ Programming

70

Template FileYou can create a template file to use whenever you start a

new program, that looks like this: #include <iostream>using namespace std;

int main(){ //insert program code here

cout << endl << endl; system("PAUSE"); return 0;}