Вы находитесь на странице: 1из 113

Introduction to C++

Computer Science I

Quote...

Language is the only instrument of science.

Samuel Johnson

Q: What is C++

C++ is a compiled, object-oriented language It is the successor to C, a procedural language

(the ++ is called the successor operator in C++)

C was derived from a language called B which was in turn derived from BCPL C was developed in the 1970s by Dennis Ritchie of AT&T Bell Labs C++ was developed in the early 1980s by Bjarne Stroustrup of AT&T Bell Labs. Most of C is a subset of C++

Object-Oriented Programming
First-class objects - atomic types in C
int, float, char have:
values sets of operations that can be applied to them

how represented irrelevant to how they are manipulated

Other objects - structures in C


cannot be printed do not have operations associated with them (at least, not directly)

Object-Oriented Idea
Make all objects, whether C-defined or userdefined, first-class objects For C++ structures (called classes) allow:
functions to be associated with the class only allow certain functions to access the internals of the class allow the user to re-define existing functions (for example, input and output) to work on class

Classes of Objects in C++


Classes
similar to structures in C (in fact, you can can still use the struct definition) have fields corresponding to fields of a structure in C (similar to variables) have fields corresponding to functions in C (functions that can be applied to that structure) some fields are accessible by everyone, some not (data hiding) some fields shared by the entire class

Instances of Classes in C++


A class in C++ is like a type in C Variables created of a particular class are instances of that class Variables have values for fields of the class Class example: Student
has name, id, gpa, etc. fields that store values has functions, changeGPA, addCredits, that can be applied to instances of that class

Instance examples: John Doe, Jane Doe


each with their own values for the fields of the class

Comments in C++
Can use C form of comments /* A Comment */ Can also use // form:
when // encountered, remainder of line ignored works only on that line

Examples:
void main() { int I; // Variable used in loops char C; // No comment comment

Variable Declarations
In C++, variable declarations are not restricted to the beginnings of blocks (before any code)
you may interleave declarations/statements as needed it is still good style to have declarations first

Example
void main() { int I = 5; printf(Please enter J: ); int J; // Not declared at the start scanf(%d,&J);

Counter Variables in a For Loop


You can declare the variable(s) used in a for loop in the initialization section of the for loop
good when counter used in for loop only exists in for loop (variable is throw-away)

Example
for (int I = 0; I < 5; I++) printf(%d\n,I);

Variable exists only during for loop (goes away when loop ends)

Initializing Global Variables


Not restricted to using constant literal values in initializing global variables, can use any evaluable expression Example:
int rows = 5; int cols = 6; int size = rows * cols; void main() { ...

Initializing Array Elements


When giving a list of initial array values in C++, you can use expressions that have to be evaluated Values calculated at run-time before initialization done Example:
void main() { int n1, n2, n3; int *nptr[] = { &n1, &n2, &n3 };

void*
In C it is legal to cast other pointers to and from a void * In C++ this is an error, to cast you should use an explicit casting command Example:
int N; int *P = &N; void *Q = P; // illegal in C++ void *R = (void *) P; // ok

NULL in C++
C++ does not use the value NULL, instead NULL is always 0 in C++, so we simply use 0 Example:
int *P = 0; // equivalent to // setting P to NULL

Can check for a 0 pointer as if true/false:


if (!P) // P is 0 (NULL) ... else // P is not 0 (non-NULL) ...

Tags and struct


When using struct command in C++ (and for other tagged types), can create type using tag format and not use tag in variable declaration:
struct MyType { int A; float B; }; MyType V;

enum in C++
Enumerated types not directly represented as integers in C++
certain operations that are legal in C do not work in C++

Example:
void main() { enum Color { red, blue, green }; Color c = red; c = blue; c = 1; // Error in C++ ++c; // Error in C++

bool
C has no explicit type for true/false values C++ introduces type bool (later versions of C++)
also adds two new bool literal constants true (1) and false (0)

Other integral types (int, char, etc.) are implicitly converted to bool when appropriate
non-zero values are converted to true zero values are converted to false

bool operations
Operators requiring bool value(s) and producing a bool value:
&& (And), || (Or), ! (Not)

Relational operators (==, !=, <, >, <=, >=) produce bool values Some statements expect expressions that produce bool values:
if (boolean_expression) while (boolean_expression) do while (boolean_expression) for ( ; boolean_expression; )

C++ Program
Consists of

Declarations

Define the use of various identifiers, thus creating the elements used by the program (computer) Or executable statements, representing actions the computer will take on the users behalf

Statements

Identifiers

Names for various entities used in a program; used for... Variables: values that can change frequently Constants: values that never changes Functions: programming units that represents complex operations Parameters: values that change infrequently

Simple C++ Program


#include <iostream.h> int main() { // Declarations // Statements return 0; }

Compiler directive:

Tells the compiler what to do before compiling This one includes source code from another file

Simple C++ Program


#include <iostream.h> int main() { // Declarations // Statements return 0; }

Main function

Simple C++ Program


#include <iostream.h> int main() { // Declarations // Statements return 0; }

Header for main function States

data type for the return value identifier for function list of arguments between parenthesis (none for this function)

Simple C++ Program


#include <iostream.h> int main() { // Declarations // Statements return 0; }

Braces enclose the body of the function They represent the start and end of the function

Simple C++ Program


#include <iostream.h> int main() { // Declarations // Statements return 0; }

Declarations and statements Main body of function (or main part) // represents the start of a comment

Simple C++ Program


#include <iostream.h> int main() { // Declarations // Statements return 0; }

Return statement specifies the value the function returns All (almost) declarations and statements end with a semi-colon ;

Simple C++ Program


#include <iostream.h> int main() { // Declarations // Statements return 0; }

This program doesnt do anything !

Sample C++ Program


#include <iostream.h> void main() { int number; cout << Enter a number << endl; cin >> number; cout << You entered: << number << endl; }

Variable declaration The identifier number is declared as being of data type int, or integer

Sample C++ Program


#include <iostream.h> void main() { int number; cout << Enter a number << endl; cin >> number; cout << You entered: << number << endl; }

cout the output statement for C++ Note the direction of << endl represents an end-of-line

Sample C++ Program


#include <iostream.h> void main() { int number; cout << Enter a number << endl; cin >> number; cout << You entered: << number << endl; }

cin the input statement for C++ Note the direction of >>

Sample C++ Program


#include <iostream.h> void main() { int number; cout << Enter a number << endl; cin >> number; cout << You entered: << number << endl; }

Did you copy this down? You had better, since this will be the first program youll try!

Sample C++ Program


#include <iostream.h> void main() { int number; cout << Enter a number << endl; cin >> number; cout << You entered: << number << endl; }

That mea ns right now!

Assignment

Assignment is an operation that assigns the value of an expression to a variable Ex.


Total = 2 + 3 + 5

First, the expresssion 2 + 3 + 5 is evaluated Then, this value is assigned to the variable Total

Assignment

When a variable is declared, space is allocated in the computers memory for the variable Each data type requires a different number of bytes in memory for storing a variable
int - 2 float - 4 double - 8 char, bool - 1

Assignment

When a variable is assigned a value, the value is placed into the variables memory location
Total

Total = 2 + 3 + 5;

10

Arithmetic Operations

Addition: Subtraction: Multiplication: Division:

2 + 3 5 - 2 10 * 4 12 / 3

Order of Operations

Arithmetic expressions are evaluated according to the following order of operations At each level, operations are evaluated left to right (1) Parenthesis, Functions (2) Multiplication, Division (3) Addition, Subtraction

Parenthesis

Parenthesis are used to alter the order with which operations are evaluated Ex.
4 + 5 * 2 equals 14 (4 + 5) * 2 equals 18

Here we go!

Problem: To determine the average of three numbers Task: Request, from the user, three numbers, compute the average and the three numbers, and print out the original values and the computed average

Do it!
You have 20 minutes!

Computer Science I

Functions

Q: What is a function?

A programming unit Similar to mathematical functions Example:


f(x) = x2 + 5x + 7 For x = 2, f(2) = (2)2 =5(2) + 7 = 21

Q: What is a function?

It has... ... arguments ... a name (identifier) ... a value it returns ... a body int

foo(int x)

{ int result; result = x*x + 5*x + 7; return result; }

Procedural Abstraction

Think Black Box ! When using a function, you only need to be concerned with what it does, not how it does it When writing a function, you need to be concerned with the how

Example: Cube it!


int cubeIt(int x) { int result; result = x*x*x; return result; } int cubeIt(int x) { int result; result = x; result = x*result; result = x*result; return result; }

Pseudocode

Looks like a programming language Has all the structure of a programming language Has a verrrrrry loose syntax

Pseudocode

Example:
function foo (x) result x2 + 5x + 7 return result

Thats it! Sloppy, aint it?

Computer Science I

Decision Statements

Q: What is a decision?

Something that represents a branching point in a solution Outcomes are often dependent on initial conditions

Decisions in Programs

Without decision statements (or other dynamic control structures), programs are static Static programs do exactly the same things each time they are executed Dynamic programs do not

Boolean Algebra

Based on values that are either True or

False

True and False values are often represented by 1s and 0s, respectively

Logical Operations: And


AB
Expression is True iff A and B are both true

T F

T T F

F F F

Logical Operations: Or

AB
Expression is True if either A or B are True Note: Also True when A and B are both True

T F

T T T

F T F

Logical Operations: Exercises


A = True, B = True, C = False 1. A B 2. A C 3. A B C 4. (A B) (A C)

Relational Operations

A A A A

<B >B =B B

AB AB

A A A A A A A A A

less than B greater than B equal to B less than or equal to B not greater than B greater than or equal to B not less than B not equal to B less than or greater than B

Relational Operations:

Exercises

A = 5, B = 3, C = -7 1. A < B 2. A C 3. (A < C) (B < C)

Boolean Operations: C++

AB AB A<B A>B A=B AB AB AB

A A A A A A A A

&& B ||B <B >B ==B >=B <=B <>B

Try this!
Problem: Youd like to go see a movie. The movie costs $8.00, a soda costs $2.50 and a large popcorn costs $4.50. Based on the amount of money in your pocket, determine whether you could... (a) See the movie and buy a soda, (b) See the movie, and buy soda and popcorn, or (c) Stay home

Know?

Movie costs $8.00 Soda costs $2.50 Popcorn costs $4.50 How much money I have in my pocket

Need?

Cost of movie and soda Cost of movie, soda and popcorn Way to select one of the three options (that is, make a decision!)

Do?

Option (a) costs $10.50 Option (b) costs $15.00 Option (c) costs nothing What next?

How about a diagram?

This is called a

Money < $10.50

flowchart
Stay home Money < $15.00

Movie & soda

Movie, soda & popcorn

How about a diagram?

Boxes represent actions


Stay home

Money < $10.50

Money < $15.00

Movie & soda

Movie, soda & popcorn

How about a diagram?

Diamonds represent decision points


Stay home

Money < $10.50

Money < $15.00

Movie & soda

Movie, soda & popcorn

How about a diagram?

Arrows show flow

Money < $10.50

Stay home

Money < $15.00

Movie & soda

Movie, soda & popcorn

How about a diagram?

The arrow at the top tells us there were previous steps The arrow at the bottom tells us there are subsequen t steps

Money < $10.50

Stay home

Money < $15.00

Movie & soda

Movie, soda & popcorn

How would I write this?


Using Pseudocode Wait! What the CENSORED is Pseudocode?

Pseudocode

Looks like a programming language Has all the structure of a programming language Has a verrrrrry loose syntax

Pseudocode

Example:
get x result <- x2 + 5x + 7 print result

Thats it! Sloppy, aint it?

One more time!

Pseudocode...

If (Money < $10.50) then Stay home else If (Money < $15.00) then Movie, soda else Movie, soda, popcorn

How would I write this?

First, we need to decide how to organize our solution Should we hard code the costs of the movie, soda and popcorn into the algorithm? Should we input these values? Lets take another look at that problem!

How would I write this?

The problem statement tells us the individual costs So, lets assume theyre fixed or

constant

No need to ask the user for them

Problem: Youd like to go see a movie. The movie costs $8.00, a soda costs $2.50 and a large popcorn costs $4.50. Based on the amount of money in your pocket, determine whether you could... (a) See the movie and buy a soda, (b) See the movie, and buy soda and popcorn, or (c) Stay home

How would I write this?


Another question: Should we pre-compute the cost of each option? Or, should we let the program do this? Since weve already stated that the item costs are fixed, it would seem logical to precompute the cost of each option

Movie: $8.00 Movie & soda: $10.50 All three: $15.00

How would I write this?

Next, we need to make sure we have a complete algorithm


Input Money If (Money < $10.50) then Display Stay home. else If (Money < $15.00) then Display Go to a movie;buy a soda. else Display Go to a movie; buy a soda and popcorn.

Almost done!

How would I write this?

Determine how we wish to organize our program Do we want one function? Or, should we create a few functions? Lets two functions: One to input Money from the user And a second to determine the outcome

How would I write this?

Heres the prototypes for the functions int getMoney() void showResults(int myMoney)

Program

Okay, now we get to use our algorithm and program design to create a program

Well, what are you waiting for?

Do It!!!

Multiway Branching

If statements can be used for multiway branching That is, choosing one of n mutually exclusive outcomes

But what about n outcomes that are not totally unique?

Multiway Branching

Consider the following problem:

Each year, a local middle school requires students to purchase supplies based on their grade level. 6th graders need pencils and five notebooks. 7th graders also need a calculator. 8th graders add to this a 3-ring binder with loose leaf paper.

Multiway Branching

We could use a nested If statement to handle this, but there is an alternative Whenever we need to represent a decision step, with n possible outcomes, where the outcomes form subsets of each other,

and/or

the outcomes are chosen based upon unique scalar values for a control expression, we can use a Case (switch) structure

Multiway Branching

Case When Grade = 8th 3-ring binder loose leaf paper When Grade = 7th calculator When Grade = 6th pencils 5 notebooks

Multiway Branching
In C++ ... switch (grade){ case 8: cout << 3-ring binder, loose leaf, ; case 7: cout << calculator, ; case 6: cout << 5 notebooks, & pencils. << endl; } When the switch is encountered, control jumps to the matching case statement and continues until either a break is found or the end of the switch

Multiway Branching

Heres an example with a few breaks

cout << Your lunch period comes ; switch (grade) { case 8: cout << first. << endl; break; case 7: cout << second. << endl; break; case 6: cout << third. << endl; } No final break

Exercise:

Create a program that will inform the user which advisor they should go to based on their major code number

Well? Get started!

Computer Science I

Loops

Q: What is a Loop?

A control structure that allows for a sequence of steps to be repeated a certain number of times This sequence of steps is called the body of the loop

Q: What is a Loop?

There are three basic loop structures in programming:


For While Repeat

While loop
Look familiar?
Condition T F

What if you added a change step to the end of the body?

Body

For loop
F

Condition T

Body

While loop
F

Condition T

Body

A while loop is a control structure where the body is repeated as long as the condition is true

While loop
F

Condition T

Body

When the condition is false, the body is bypassed, and flow continues with the next part of the algorithm

Example: Sequential search


F
k 0 found False while (k<size) (found) do if A[k] = target then found True else k = k + 1

(k<size) (found)

if A[k] = target then found True else k = k + 1

Example: Sequential search


F
k = 0; found = False; while ((k<size) && (!found)) if (A[k] == target) found = True; else k = k + 1;

(k<size) (found)

if A[k] = target then found True else k = k + 1

Exercise

Strings are arrays of characters

How would you determine if a string fragment is part of a larger string? (needle in a haystack?)

Computer Science I

Arrays

Q: What is an array?

An array is a data structure consisting of one or more indexed members An array is like a row of mailboxes at the post office Each box is numbered in sequence (indices), and Each box contains the same type of stuff (datatype)

An array could be drawn like

5 6

An array could be drawn like

5 6

Each box is numbered in sequence

An array could be drawn like


Each box has the same datatype

5 6

In pseudocode we use

X[j] Where X is the name of the array (identifier), and j is an index indicating which position in the array we wish to address

An array is declared by
int X[10]; Where int is the common datatype for all elements in the array, X is the name of the array (identifier), and 10 is the size of the array, or how many elements are in the array Indices for a C++ array always begin with 0

Example: Student Grades


// Declare array double stGrades[7]; : // Assign value to array element stGrades[5] = 87; : // Display array element cout << stGrades[3] << endl;

Problem:

Create a program that will ask the user for three (3) numbers, determine the average, and then display the original numbers and the average Hint: You might wish to use a loop as well as an array!

Computer Science I

Strings

What is a string?

A string is a sequence of characters Example: nc9*hNB98B&^v*&G Blank spaces are characters Each character requires one byte of storage in memory Each character is represented by a one byte character code, usually an ASCII code

Strings

A literal is a string bounded by quotation marks

Example:

nc9*hNB 98B&^v*&G Notice the blanks spaces in the sequence - they are characters!

Strings

In C++, we declare string variables as follows

char string_identifier[length];

string_identifier is the name of the

string variable length represents the length of the string, or how many characters are in the sequence

Strings

Example:
void main() { char name[24]; cout << Enter your name: ; cin >> name; cout << Your name is << name << endl; }

Streams
A stream
Is a flow of characters Is an object that represents either on input or an output to a program Can be associated with the keyboard, monitor, or files cout is an output stream

cin is an input stream

How about file I/O?


#include <fstream.h> : ifstream in_stream; ofstream out_stream; :

Where definitions for datatypes ifstream and ofstream are located

Input stream declaration Output stream declaration

How about file I/O?


#include <fstream.h> Associates files : ifstream in_stream; with streams & ofstream out_stream; opens files for : use in_stream.open(infile.txt); out_stream.open(outfile.txt); instream >> number; Stream use outstream << number << endl; instream.close(); outstream.close(); Closes files :

What if a file doesnt exist?


In_stream.open(notthere.txt); If (in_stream.fail()) { cout << Input file opening failed << endl; exit(1); }

How about formatting?


out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2); Set flag: out_stream.width(10); fixed/scientific : showpoint showpos right/left Number of digits

Number of decimal places

More member functions


get() put() eof()

Вам также может понравиться