sahar mosleh california state university san marcospage 1 introduction to c++

97
Sahar Mosleh California State University San Marcos Page 1 Introduction to C++

Upload: lenard-mckinney

Post on 03-Jan-2016

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 1

Introduction to

C++

Page 2: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 2

Our first C++ program:

#include <iostream>

using namespace std;

// This is the “Hello World!” program int main ()

int main(){ cout<<“Hello World!”;}

Page 3: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 3

Like other languages, C++ program

• Consists of a series of statements as defined by the language syntax

• Running a C++ program is a complex process as computers are not able to do anything directly with C++ code

• Must go through the compilation process

Page 4: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 4

Source Program (Hello World)

Preprocessor

Compilation of Source Program

Object Program (Hello World!)

• This compilation process effectively translates a C++ program into a form your computer can understand.

• Machine language• Differs depending on what kind of machine you use.

Compilation Process

Page 5: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 5

• The compilation process requires a program called a compiler

• We will use C++ compiler in Unix for this course

Page 6: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 6

Comments

#include <iostream> using namespace std;

// This line is a comment int main () {

cout<< “Hello World!”; }

Page 7: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 7

Comments

#include <iostream> using namespace std;

// This line is a comment // This line is also a comment

int main () {

cout<< “Hello World!”;

}

Page 8: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 8

Comments

#include <iostream> using namespace std;

/* Comments can look like this too!*/

int main () {

cout<< “Hello World!”; }

Page 9: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 9

Comments

#include <iostream>using namespace std;

/* Comments of this sort can span many

lines */ int main () // another comment

{cout<< “Hello World!”;

}

Page 10: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 10

Comments

#include <iostream>using namespace std;

/* Comments of this sort can span many lines*/

int /* a funny place for a comment */ main (){

cout<< “Hello World!”;}

Page 11: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 11

Comments

• Are ignored by the compiler.

• Are for the exclusive benefit of the programmer.

• Used to describe code that otherwise might be misinterpreted.

• Also used for other relevant information such as your name, student number, course and assignment number, and so on.

Page 12: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 12

Terminologies

Page 13: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 13

What Are Valid Instructions?• In your algorithm, what are the things you can tell a computer

to do?

• That depends on the primitive commands that the computer can understand.

• "Make coffee" is not one of them but "Add 4 and 3" is.

• A program will usually have the following form:

• Section for taking INPUT data• Section for PROCESSING it• Section for OUTPUTTing results

• What you can say in these sections depends heavily on the concept of VARIABLES which we will cover next.

Page 14: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 14

Variables

• Every data item used by your program must be stored in a box in the memory. These boxes in the memory are variables.

• A box can only contain one item at a time, but the box content can be changed again and again.

• e.g. INPUT : two numbers • Need 2 boxes to store the inputs.

• Num1• Num2

• Usually, the result of computation is also stored in a box until it is further modified or given out as the OUTPUT.

• e.g. OUTPUT: sum of the 2 numbers• Need 1 box to store the sum.

• Sum

Page 15: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 15

• Almost every instruction in your program will have to deal with these boxes, for example:

• Take data from the user and put it in a box

• Copy data from one box to another

• Perform calculation on a box.

• Use box contents and place the result in a box.

• Display the box content on the screen.

• Box manipulation commands are the primitive commands you have to work with in developing any algorithm.

Page 16: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 16

• e.g. Instructions to the computer:• 1) Take data from the user and put it in Num1.• 2) Take data from the user and put it in Num2.• 3) Sum gets the result of Num1 + Num2.• 4) Display what's in Sum.

• Although you don't want to develop your high-level algorithm with these primitive commands in mind, you should start thinking about the "boxes", and how they will be used, as you get closer to the programming language level.

• Thus, another way to think of "adding details" is "start thinking in terms of boxes.

Page 17: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 17

Variable Declarations• Before a variable (box) can be used in your instructions, you

have to list it for the Instruction Follower (Computer).

• This is similar to the way Ingredients are listed at the top of a recipe.

• Why?? The computer has to be able to:• 1. reserve the boxes in its memory, labeled with appropriate

names.• 2. make sure no bad data will go into the boxes by knowing

what types of data can go into them.• So, a variable declaration has two components:

• 1. the name of the box• 2. the type of the contents allowed

• e.g. Variable Num1 will contain an integer. Variable Gender will contain a character.

Page 18: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 18

Variable Names

• In most programming languages, the variable name cannot contain blank spaces.

• e.g. myName is Ok in C++• my_Name is Ok in C++• my Name is not Ok in C++

• The name should describe the purpose of the variable.

Page 19: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 19

Variable Types

• Content types found in most programming languages are• integer (for e.g. -1, 0, 1, 2, 3 ...)• real number (for e.g. 23.45, 0.345)• character (for e.g. 'A', 'a', 'B')• string (for e.g. "Happy Birthday")

• Thus, a type defines the set of values which can go into a variable.

Page 20: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 20

First Set of Primitive Commands

• We will write our algorithms in restricted English for now.

• But you must obey the following grammar rules carefully.

• Note that < > are placeholders to be replaced by actual items.

• First, always state at the top of your algorithm,

Page 21: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 21

• Instructions to the computer:

• For Variable Declarations:• Variable <name> will contain a <type>.• e.g. Variable Num1 will contain an integer.

• For INPUTs:• Take data from the user and put it in <name>.• e.g. Take data from the user and put it in Num1.

Page 22: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 22

• For Processing:

• <name> gets the result of <equation using box names and/or numbers>.

• e.g. Num2 gets the result of Num1 * 5 + 4.

• Add <number> to <name>.• e.g. Add 5 to Num1.

• Subtract <number> from <name>.• e.g. Subtract 1 from Num2.

Page 23: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 23

• For Outputs:

• Display what's in <name>.

• e.g. Display what's in Num2.

• Also, make sure every instruction has a step number in front of it.

• e.g. •1) Take data from the user and put it in Num1.•2) .....

• Now, let's practice.

Page 24: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 24

• Ex1: Ask the user to enter the base and the height of a triangle. Find the area of the triangle and print it on the screen for the user.

• INPUTS: the base and height of a triangle • OUTPUT: area of the triangle• Give the high level algorithm:• Give the low level algorithm using the language defined

above:

Page 25: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 25

• Abstract Form of the algorithm:

• Input:• Get base and height

• Process:• Find the area

• Output:• Print the area on the screen

Page 26: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 26

• More detail format:

• Input:• Create two boxes called base and height• Get the values of base and height• Store them in base and height boxes

• Process:• Create another box called area• Multiply base by height and divide it by 2 • Store the result in area box

• Output:• Print the content of the box called area on the

screen

Page 27: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 27

• Another example:

• Find the average of the marks for the 5 courses taken by a student last year

Page 28: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 28

Constants vs. Variables

Sets of Values

Functions

Page 29: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 29

Review

• You may use characters, digits and underscore in a variable name.

• Make sure you do not use blanks in variable names.

• No value is erased from a box until another value is placed in there.

• * WE ARE STILL WORKING WITH ALGORITHMS • * WE ARE NOT USING C++ YET.

Page 30: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 30

Constant vs. Variables

• Constants are values directly written in your algorithm, not referred to by a variable name:

• Given Add 10 to Num.• 10 is a constant.• Num is a variable.

• Thus, an equation can consist of constants and/or variables.• e.g. Num gets the result of 3 * A / B.• *Inter:* What is wrong with 30 gets the result of A / B

Page 31: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 31

Sets of Values

• The concept of SETS will come up again and again in computer science.

• For this course, we can think of the variable type as further restricted by the “acceptable set of values.”

• This does not mean that the computer will automatically check acceptable values for you.)

Page 32: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 32

• For example:

• Variable Age will contain an integer.• The set of acceptable ages = {1, 2, .......... 120}

• Another example:

• Variable HwScore will contain an integer.• The set of acceptable scores = {0, 1, ........ 100}

Page 33: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 33

• Another example:

• Variable Grade will contain a character.

• The set of acceptable grades = {'A', 'B', 'C', 'D', 'E', 'F'}

• The above examples showed sets which have finite number of elements and the elements can be counted as "1st one", "2nd one" etc.

• How about this example?

• Variable Area will contain a real number.

• The set of acceptable areas = { ????? }

• In this case, you cannot really list the elements and count them. In fact, there are infinite number of elements.

• You could write this, for example, as { x | 0 < x <= 200} • This says any area x must be between 0 and 200(inclusive).

*Inter:* How would you describe a set of acceptable values for GPA?

*

Page 34: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 34

• Rule:* In this course, for every variable you use in your algorithm, determine the acceptable set of values and write it down.

• e.g.• Variable Age will contain an integer. // {0, 1, ...., 120}• Variable Sum will contain an integer. // {0, 1, ...., 240}• Variable Num will contain an integer. // {x | x is any integer}

• Why should we do this?• Allow you to think in more depth about the data and results.• Can later help make your algorithm force the user to enter only

acceptable values from the keyboard.• Can be referenced during debugging.

Page 35: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 35

Functions• Given a value, a function returns you a value.

• e.g. abs(-2) returns 2.• e.g. ceil(3.4) returns 4.• e.g. floor(3.9) returns 3.

• Notice that parentheses surround the given value.

• There are many pre-defined functions in a programming language.

• For example, abs, ceil, floor are available in C++.• The set of values you can give to a function is called the

Domain.• The set of values you can get back from a function is called

the Range.• e.g.

•The Domain of abs is integers.•The Range of abs is positive integers.

• You should be aware of the Domain and the Range of each function you use.

Page 36: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 36

Terminology

• When you use a function, you "call" it. e.g. call abs. When you give it a value, you "pass" it.

• e.g. call abs passing it -3. When it gives you a computed value, it is “returned.”

• e.g. abs(-3) returns 3.

Page 37: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 37

Calling a function

• How do you call a function?

• Write its name, and then the value to be passed in parentheses. e.g. abs (-3)

• You may pass a variable to a function.

• This means the function will take the value contained in the variable and use it to compute a new value.

• e.g. abs (Num)

• Where can I call it in my algorithm?• Any place where a constant can be used.

• e.g. We can store it ( ex: Result = abs (Num) * 3).• e.g. We can use it (ex: xyz = xyz + abs (Num) ).• e.g. We can display it (ex: print abs (Num).

• The expression abs (Num) stands for the value returned.• Thus, if Num contained -3, then abs (Num) stands for 3.

Page 38: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 38

• There are functions which get non-numeric values and/or return non-numeric values such as those involved in the ASCII code conversion.

• e.g. int('A') returns 65.• char(65) returns ‘A’

• You can add more functions to the programming language by defining them yourself. We will cover this later.

Page 39: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 39

Lines and Statements

Syntax and

Semantics

Page 40: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 40

#include <iostream>using namespace std

- is a request that source file iostream, that is a standard routine written in visual C++ can be used by the programmers.

- Again, handled by the preprocessor- Contains code to handle, among other things, simple

input and output.- Your “Hello World!” program will turnout, in reality,

to be quite large once all the library code has been inserted.

Page 41: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 41

{…}

- Logical blocks of code are referred to as blocks and are delimited by an open and close brace.

- In case of “Hello World!”, {…} delimit the beginning and ending of executable C++ code.

- You will be seeing a lot of {…}- They are very important

Page 42: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 42

cout <<“Hello World!”;

- cout is a special variable that refers to the default output device.

- In our case, the default output device is the screen.

- Defined in iostream file.

Page 43: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 43

cout << “Hello World!”;

- << is called the insert operator.

- Sends the character string “Hello World!” to the screen.

- Character strings are delimited by double quotation marks.

- C++ statements are terminated by a semicolon.

Page 44: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 44

- C++ programs can be very complex, but are based upon a small number of principles that are rigorously adhered to.

- Understand the principles and you will understand C++ and programming better.

Page 45: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 45

Lines and Statements

- “Statements” in C++ are not related to the lines in the source file on which they are written. “white-space” (blanks, tabs and linefeeds) are ignored!

- For example for code:cout << “This is some output ”;cout << “and some more output”;

- The output is:This is some output and some more output

Page 46: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 46

Lines and Statements

On code:

cout << “This is some output ”;cout <<“and some more output.”;

The output is:This is some output and some more output.

Page 47: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 47

Lines and Statements

• The only place that white-space matters inside double quotes “…”

• For example on code:cout << “This is some output”;

• The output is: This is some output.

Page 48: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 48

Writing a Program

- Several steps

- Understand the problem- Solve the problem yourself- Tell the computer how to do it- Find and fix any errors- Which is the most important thing to learn?- What takes the most practice?- How can you tell the computer what to do when you

don’t know yourself?

Page 49: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 49

Writing a Program

- You will find “telling the computer what to do” (i.e., writing C++) difficult at first.

- Lots of typing mistakes and syntax errors, like learning any language.

- In the long run, what are we teaching you is (very formal) problem solving.

- This is the hard part

- Sitting and typing away in front of the machine won’t do you any good if you don’t know what you’re doing!

Page 50: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 50

Writing a Program

- Know what you’re doing first!

- Construct a step by step solution you can write out without worrying about the computer at all!

- E.g., calculating x to the power of y

- Take x; multiply it by itself over and over; count the number of times as you do this until the number is equal to y.

Page 51: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 51

Writing a Program

- Now that I have that solution, I can implement it as a computer program in any language I like!

- Independent of any details of language or machine! I can use this any time.

- An Algorithm - a finite series of statements that describe how to solve a problem.

- Algorithms are independent of computer programs and computers.

Page 52: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 52

C++: Syntax and Semantics

Syntax:

- Rules governing how valid instructions are written.

- Defines what is a valid program

- Syntactically correct program will compile correctly

- No guarantee it will run correctly

For example:cout >> “This is bad!”// syntactically incorrect: compiler error.

Page 53: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 53

C++: Syntax and Semantics

Semantics:

- Rules which determine the meaning of a syntactically correct program.

- What the computer is expected to do when it runs your program.

- A syntactically correct program may not do what we want.

- It always does exactly what you programmed it to do.

Page 54: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 54

C++: Syntax and Semantics

- C++ programs consist of a series of functions.

- A function is a piece of code which returns a value.

- We have already seen one special function.- “main” is a function

- takes no arguments- returns nothing (it can return an int)- computer starts to execute at the beginning of function

“main”

Page 55: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 55

- Generally we want multiple lines of output:

#include <iostream>using namespace std;

int main(){ cout<<“This is line 1”<<endl;

cout<<“This is line 2”;cout<<“Is this on line 3?”;

}

- The output from this segment is:This is line 1This is line 2ls this line 3?

Page 56: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 56

- We can put more than one insertion (<<) operator in a single C++ statement

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

cout<<“This is line 1”<<“ and more. ”; cout<<“This is still line 1.”<<endl <<“is this on line 2?”<<endl;

}

- The output from this segment is:This is line 1 and more. This is still line 1. is this on line 2?

Page 57: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 57

Other output issues

\n Position the screen cursor to the beginning of the next line

\t Horizontal tab

\a Alert. Sound the system bell

\\ Backslash. Used to print backslash character

\” Double quote. Used to print double quote character

\r Puts the cursor at the beginning of the line

Page 58: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 58

Basic C++ Input

Expressions

The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

Page 59: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 59

Basic C++ Input

- Computers often require input from the program user

- interactively (such as query to the user) from a file

- In C++, we get input in a manner similar to print output

Page 60: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 60

Basic C++ Input

#include<iostream>

using namespace std;

int main()

{

float x;

cout<<“Enter x ”;

cin>>x;

cout<<“The square of x is ”<<x*x <<endl;

}

Page 61: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 61

Basic C++ Input

- cin is the standard input stream

- like cout, it is defined in iostream

- Input to a variable (like x) is accomplished by the extraction operator >>

- Basically, we think of the insertion (<<) and extraction (>>) operators as pointing in the direction that the data is flowing

- Input is flowing from cin to x

Page 62: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 62

Basic C++ Input

- Stream input reads the next item(s) of the desired type from the input stream. For example,

float x,y;

cin>>x; //reads one float into x

cin>>x>>y; //reads a float into x and another float into y

reads floats from the standard input stream

- It does nothing if the next input is not a float, or if something else goes wrong (like an “end-of-life”)

- More on this later...

Page 63: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 63

Basic C++ Input

- C++ input ignores whitespace

- It reads the next item on the input stream, skipping any leading whitespace

- If the C++ statements

char onechar; float onefloat; int oneint;

cin>>onefloat>>oneint; cin>>onechar;

are executed in input

3.14 25

x

- the variables have values

onefloat = 3.14 oneint = 25 onechar = ‘x’

Page 64: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 64

The type bool

- Boolean data & variables can have two possible values: true & false

- Such variables are typically used to represent the state of the computation at a particular time. For example,

- If we are looking for something in a database, we might have a boolean variable “found” which is false until we find what we are looking for

Page 65: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 65

The type bool

- In C++, Boolean variables are of type bool and have possible values as true or false

- bool is a type

- true & false are literals

int main()

{

bool a,b;

a = true; b = false;

cout<<“True is”<<a<<endl;

cout<<“False is”<<b<<endl;

}

Page 66: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 66

The type bool

- The output is:

True is 1

False is 0

- Note that by default, true & false are represented by the integers 0 and 1

- In general, false is represented by 0 and true is represented by any non-zero integer

- This is an example of a coercion

- You generally don’t need to think about this coercion

Page 67: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 67

The type bool

- We can also do I/0 on type bool with “English” names use the “boolalpha” manipulator. For example,

int main()

{

bool a,b;

a = true; b = false;

cout<<boolalpha; //insert manipulator

cout<<“True is”<<a<<endl;

cout<<“False is”<<b<<endl;

}

- The output is:True is true

False is false

Page 68: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 68

Boolean Expressions

- bool values are generally obtained from comparing variables

of other types:

- For example:

float x,y;

bool c;

c = (x<=y) // c is “true” if x is less than or equal to y.

// c is “false” otherwise

Page 69: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 69

Boolean Expressions

- There are a number of basic comparisons that C++ defines between 2 variables or constants:

= = Equal to (note: different from =)

!= Not equal to

> Greater than

< Less than

>= Greater than or Equal to

<= Less than or Equal to

Page 70: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 70

Boolean Expressions

- For type int, the result of such comparisons is relatively clear

- For type float, be careful of round off:

1.333333333333333 = = (4.0/3.0) // ??

- For type char, order consistent with alphabet of same case

‘a’<’z’ true

‘A’<=‘B’ true

‘a’<‘B’ false (!!)

Page 71: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 71

Logical Operators

- In mathematical logic, we combine logical expressions with AND, OR, and NOT to form more complex expressions

- C++ offers these operators as well:

AND is represented by && in C++

OR is represented by || in C++

NOT is represented by ! in C++

Page 72: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 72

Logical Operators

- For bool variables a,b:

a && b true only when a and b are

both true, false otherwise

a || b true when one or more of a and b

are true, false otherwise

!a true when a is false, false

when a is true

Page 73: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 73

Logical Operators

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

float x,y,z;bool c;cout<<“Enter x,y,z:”;cin>>x>>y>>z;c = (x<=y) && (y<=z);cout<<"It is " << boolalpha<<c

<<" that x, y, and z are in ascending order?" << endl;

}

< See: Example 1>

Page 74: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 74

Logical Operators

#include <iostream>

using namespace std;

int main()

{

float x,y,z;

bool c;

cout<<“Enter x,y,z”;

cin>>x>>y>>z;

c=((x<=y) && (y<=z)) || ((x>=y) && (y>=z))

cout<<“It is ” << boolalpha << c << “ that x, y, and z are in ascending or descending order?” << endl;

}

Page 75: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 75

C++ Input from a File

- we can obtain C++ input from a file rather than getting it from the screen:

#include<iostream>#include<fstream> //input or output stream declarationsusing namespace std;

int main() {

float x;ifstream fin; //input stream named finfin.open(“myinputfile.txt”); //attach to file “myinputfile”fin>>x; //get x from input filecout<<“The input is”<<x<<endl;

}

< See: Example 2>

Page 76: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 76

C++ Output from a File

- we can also put C++ output into a file rather than showing it on the the screen:

#include<iostream>#include<fstream> //input/output stream declarationsusing namespace std;int main() {

ofstream fout; //output stream named foutfout.open(“myoutputfile”); //open a file called myoutputfile or

// create the file if it does not exitfout <<“-----------------------------------------------” << endl;fout<< “Name : Joe Anderson” << endl;fout << “Assignment #: 1 ” << endl;fout << “ Date: Oct 20, 2002 ” << endl;fout <<“-----------------------------------------------” << endl;

}

< See: Example 3>

Page 77: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 77

If Statement

and

Flow of Control

Page 78: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 78

Flow Control

- Program statements are executed in a particular order

- Flow of control

- Flow is sequential unless altered by control structures

- Control structures are used to alter the normally sequential flow of control

Page 79: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 79

If

If statement- Based upon a logical expression, segments of code can

be executed or not executed during run-time

if (grade>=80)cout<<“You get an A ”<<endl;

Page 80: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 80

If

- The logical expression is evaluated

- If true, statement that follows is executed

- If false, statement that follows will not be executed

- Regardless, flow will continue with statement following if construct

Page 81: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 81

If else

- If else statement

if (grade>=50) cout<<“You pass - barely!”<<endl;

else cout<<“See you next year!”<<endl;

- Although mutually exclusive, one of the above statements must execute

Page 82: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 82

If else

if (grade>=50)cout<<“You pass - barely!”<<endl;

elsecout<<“Oops…you fail!”<<endl’cout<<“See you next year!”<<endl;

- “See you next year!” is not part of the if construct and will always print

Page 83: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 83

Blocking

Blocks- The if construct requires, in effect, a single statement for

the true & false conditions.

- However, it is possible to bind many statements into one by blocking them

{stmt1; stmt2; stmt3; … ; stmtn;

}

Page 84: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 84

Blocking

So…

if (grade>=50)cout<<“You pass - barely!”<<endl;else {cout<<“Oops…you fail!”<<endl;cout<<“See you next year!”<<endl;}

Page 85: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 85

Blocking

if (grade>=50) { cout<<“You pass - barely!”<<endl; cout<<“Congratulations!”<<endl;}else {

cout<<“Oops…you fail!”<<endl;cout<<“See you next year!”<<endl;

}

Page 86: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 86

Nested ifs

- Many if versus nested ifs

- It is often necessary to have many ifs in order to solve a problem

Page 87: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 87

Nested ifs

if (month = = 1)cout<<“January”;

if (month = = 2)cout<<“February”;

if (month = = 3)cout<<“March”;

- Even if month == 1, program will continue to check if month == 2, 3, 4, 5, …

- Will work, but better to nest the ifs

Page 88: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 88

Nested ifs

if (month = = 1)

cout <<“January”;else

if (month = =2) cout<<“February”;else if (month = = 3) cout<<“March”;

- Will leave nested if construct as soon as one condition is found to be true

Page 89: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 89

Nested ifs

if (month == 1)cout<<“January”;

elseif (month == 2)

cout<<“February”;else

if (month == 3) cout<<“March”;

- Will leave nested if construct as soon as one condition is found to be true

Page 90: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 90

Nested ifs

if (grade>=90)

cout <<“A+”; if (grade>=80)

cout<<“A”; if (grade>=75)

cout<<“B+”;

- If grade == 85, “A”, “B+”, …will print

- Presumable not what is desired

< See: Example 1>

Page 91: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 91

Nested ifs

if (grade>=90)

cout<<“A+”;else if (grade>=80)

cout<<“A”;else if (grade>=75)

cout<<“B+”;

- If grade = = 85, only “A” will print

Page 92: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 92

Nested ifs

if (false) if (true)

cout<<“This will never print!”<<endl; else

cout<<“Goodbye World!”<<endl;

- You might be under the impression that the else binds with the first if, but you’d be wrong

- This code results in nothing

Page 93: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 93

Another Common Trap

int i=25, j=50;

if (i=j) {

cout<<“The if is true”<<endl; cout<<i<<j<<endl;

}else {

cout<<“The if is false”<<endl;cout<<i <<“ ” << j <<endl;

}

< See: Example 2>

This is what will execute Why ?

Page 94: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 94

Trap

- Operators = and == are not the same

- if (i = j) will…

- Assign j to i- They’re now equal

- Determine that i is not 0- As far as if is concerned, if it’s not 0, it’s true!

- Since the If is true it prints out:50 50

Page 95: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 95

Assignment Operator

- The assignment operator is unusual in that it has a value and a side effect

int x=0, y=1;cout<<(x=y)+10;cout<<“ ”<<x<<endl;

- The output is:11 1

- The value of (x=y) is the value of y- The side effect of (x=y) is to assign x to be y- This is an extremely important decision

< See: Example 3>

Do not do this

Page 96: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 96

Assignment Operator

- The assignment operator has lower precedence than any of the other operators that we have seen

- This means that when we execute

x = 3*z+5;

- the expression 3*z+5 is evaluated first and the value is then assigned to x

Page 97: Sahar Mosleh California State University San MarcosPage 1 Introduction to C++

Sahar Mosleh California State University San Marcos Page 97

Assignment Operator

- The assignment operator has lower precedence than any operator we have seen. This means it is executed last

++, --, unary - , ! Highest Precedence*, /, %+, -<, <=, >, >== =, !=&&||= Lowest Precedence