CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

72
CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC

Transcript of CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Page 1: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

CSIS 113A

Introduction To C++

Glenn Stevenson CSIS 113A MSJC

Page 2: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Overview Of A Computer

Glenn Stevenson CSIS 113A MSJC

CPU

Memory

Disk

I/ODevices

The Hardware

Page 3: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Memory

Glenn Stevenson CSIS 113A MSJC

The Memory

• Memory is addressed by byte

• In our Windows machines 1 byte = 8 bits

• Each bit can be 0 or 1

• Memory can hold

• Program instructions

• Data

10010110

10111101

1101111110100101110111100101000011000110

00110101

00101101

000001002003

004005006007008

Max

00110010

Page 4: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Memory II

Glenn Stevenson CSIS 113A MSJC

The Memory

Program Instructions

Data

• Memory is split into space for program instructions and for data

• Data space is usually further subdivided

• Static/constant

• Stack• Heap

Page 5: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

CPU And Memory

Glenn Stevenson CSIS 113A MSJC

The CPU Program Counter

Instruction register

Other Registers

Other Registers

Other Registers

...

ALU

Memory

• In our Windows machines these registers are 32 bits wide

Page 6: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

The OS

Glenn Stevenson CSIS 113A MSJC

Hardware

OperatingSystem

Drivers

Applications

• Operating System

• Windows• Linux

• Applications• Editor• Compiler• The

programs we will write

= Software

APIs

Page 7: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Developing C++ Programs

Glenn Stevenson CSIS 113A MSJC

• Steps to develop a program– Write C++ instructions, store in source-code file– The following two steps are usually automated

• Use compiler to turn source into object code• Use linker to create executable

– Use a debugger to examine and test program

• Standalone tools vs. an IDE– Integrated Development Environment combines

tools– You should know how to use individual tools

Page 8: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Compile, Link, Execute

Glenn Stevenson CSIS 113A MSJC

SourceSourceCodeCode

SourceSourceCodeCode PreprocessorPreprocessorPreprocessorPreprocessor CompilerCompilerCompilerCompiler

CommentsComments(discarded(discarded))CommentsComments(discarded(discarded))

ObjectObjectCodeCode

ObjectObjectCodeCode

LinkerLinkerLinkerLinker

.exe.exe.exe.exe

Page 9: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Comments• Way to leave notes in your code

– Ignored by compiler• You should use them liberally

• 2 types– Single line //

• Everything after the double slash is a comment up to the end of the line

– Multi-line /* */• /* everything between • Is a comment */

Glenn Stevenson CSIS 113A MSJC

Page 10: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Required for homework• All assignments must have comments at

the top of each page!

Glenn Stevenson CSIS 113A MSJC

• Failure to add comments to your assignments can result in a 0 grade

/*Name: Glenn StevensonSID#: 1234567Date: todays dateLab #: 1Description: you can simply copy and paste from the assignment descript itself

*/

Page 11: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Functions & main

• C++ is typically a cooperating group of functions– Functions

• Like a small program within a large program– Used to perform a specific task

• main – function where your program begins– Your program must have a main function

• Programs need a place to start• Program will not link without a main function

Glenn Stevenson CSIS 113A MSJC

Page 12: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Anatomy of main

• C++ is a case Sensitive language

• Function Header– First line of function

• Function Body– Code between opening and

closing braces• All blocks have an opening

and a closing brace

• Return Statement– What this function returns

• Where does in return to?

Glenn Stevenson CSIS 113A MSJC

Page 13: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Statements / Blocks

• Statements– Any valid line of C++ code

• Statements are terminated by a semicolon– Can span multiple lines compiler looks for ; as a marker

» Compiler generates an error when a statement is not terminated by a semicolon

• Blocks– Any code that has an opening & closing brace

• Not terminated by a semicolon– Function main has opening and closing brace

» Function body then is a block of code

Glenn Stevenson CSIS 113A MSJC

Page 14: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Our First Program!

Glenn Stevenson CSIS 113A MSJC

// myfirst.cpp - A simple C++ program

#include <iostream> // Preprocessor statement using namespace std; // Make cout visibleint main() // Function header{ cout << "Hi, my name is Glenn Stevenson"; cout << "\n"; return 0;}

// myfirst.cpp - A simple C++ program

#include <iostream> // Preprocessor statement using namespace std; // Make cout visibleint main() // Function header{ cout << "Hi, my name is Glenn Stevenson"; cout << "\n"; return 0;}

Page 15: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Ananlyizing myFirst.cpp

• #include <iostream>– Has definitions input and output streams

• C++ has much functionality included

• using namespace std;– Use built functionality from standard library

• int main()– Function header of main followed by the body of main (code

between the baces)• cout << “Hi my name is Glenn Stevenson”;

– cout puts information to screen • cout << “\n”;

– Moves the cursor to the next line on the console window• Called an escape character, more about that later

Glenn Stevenson CSIS 113A MSJC

Page 16: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

What is wrong with this code?

Glenn Stevenson CSIS 113A MSJC

// myfirst.cpp - A simple C++ program

#include <iostream> // Preprocessor statement using namespace std; // Make cout visibleint Main(); // Function header{ cout << "Hi, my name is Glenn Stevenson"; cout << "\n"; return 0;};

// myfirst.cpp - A simple C++ program

#include <iostream> // Preprocessor statement using namespace std; // Make cout visibleint Main(); // Function header{ cout << "Hi, my name is Glenn Stevenson"; cout << "\n"; return 0;};

Page 17: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

The preprocessor

• Separate program called CPP [C Pre-Processor]– Massages source code before giving it to compiler– Preprocessor instructions are called directives – Preprocessor directives all begin with #

• The #include <iostream> directive says– "Send the declarations and definitions in the iostream

header to the compiler at this point"– What is a "header"?

• "Family" of declarations and definitions• Normally stored in a file (or translation unit as it is called in C+

+), but doesn't have to be

Glenn Stevenson CSIS 113A MSJC

Page 18: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

The Preprocessor II

Glenn Stevenson CSIS 113A MSJC

#include <iostream> // Preprocessor statement #include <iostream> // Preprocessor statement

SourceSourceCodeCode

SourceSourceCodeCode PreprocessorPreprocessorPreprocessorPreprocessor CompilerCompilerCompilerCompiler

ObjectObjectCodeCode

ObjectObjectCodeCode

HeaderHeaderHeaderHeader

Page 19: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

The Preprocessor III

• Traditional [C-style] headers all end in .h• Standard C++ headers:

– Don't have ".h" suffix– Don't necessarily refer to file names– Older [pre-IS0] compilers won't support

• Under Turbo C++, for instance, you write:– #include <iostream.h>– And don’t get namespace functionality

• Do not use the C-style headers– C++ Style Guide 7.1.1

Glenn Stevenson CSIS 113A MSJC

Page 20: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

The Standard Headers

• 51 headers available in Standard C++– 18 ANSI C Standard library headers

• Available in traditional and new styles• <stdio.h> and <cstdio>

– 13 Standard Template Library [STL] headers• Collections and algorithms [generic programming]

– 9 Input/Output [I/0] stream headers– String, exception, memory management, and

various data structure classes not in the STL

Glenn Stevenson CSIS 113A MSJC

Page 21: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Namespaces

• A namespace defines a region where names are valid– In C, all function names are "global"– Headers combine functions into "families"– Namespaces combine families into "neighborhoods"

• All Standard C++ library functions and objects are in the std namespace– C library functions also in std with new headers

• Some older compilers have not fully implemented this

Glenn Stevenson CSIS 113A MSJC

using namespace std; // Make cout visibleusing namespace std; // Make cout visible

Page 22: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Namespaces II

• To use a function in a namespace – Prefix it with namespace and :: [scope

resolution]

• Example: using the standard sqrt() function– #include <cmath> // In std namespace

double ans = std::sqrt(5.25);

• In this class, you'll often import entire std namespace– "Import" with using namespace declaration

Glenn Stevenson CSIS 113A MSJC

Page 23: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Literals • Called literals because they are values that are

literally stated– 1 // integer literal – whole number– 2.2 // floating point literal– .3 // floating point literal– 'h‘ // single character literal– "Hello“ // string literal

• Don’t confuse single characters for strings!– This is not legal ‘hello’ and– ‘h’ is different from “h”

Glenn Stevenson CSIS 113A MSJC

Page 24: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

C++ Output

• I/O is supplied as part of the standard library– Definitions found in the <iostream> header– Standard I/O is represented as a stream– cout uses the stream extraction operator

• << notice that it points at cout!

– Can use many insertion operators to separate types• Cout << “hello my lucky number is “ << 7 << endl;

– endl does the same thing as “\n”» Moves cursor to next line on console window

Glenn Stevenson CSIS 113A MSJC

cout << "Hi, my name is Glenn Stevenson"; cout << "Hi, my name is Glenn Stevenson";

Page 25: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Changing Numbers With cout

• You can output numbers in many formats– Send format type to cout– Hexadecimal – Base 16

• cout << hex << 16 << endl;– Outputs 10 because 10 is 16 in hex

– Octal – Base 8• cout << oct << 9 << endl;

– Outputs 10 because 9 is 10 in octal

– Decimal – Base 10• cout << dec << 10 << endl;

– Outputs 10

– Will output desired format until changed or program ends

Glenn Stevenson CSIS 113A MSJC

Page 26: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

What is a stream?

• Streams are abstract information flows– Data flows into your program from a source– Your program processes the data– Information flows out of your program to a sink

• Sending info to a sink is called writing• Getting info from a source is called reading

Glenn Stevenson CSIS 113A MSJC

SinkSource Data Data Data

Stream

14OOP01.WMF Figure 14-1 Sources, streams and sinks

Page 27: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Standard streams

• C++ initially creates at least 3 stream objects– Also known as standard input, output, and error– cin : input connected to the keyboard– cout : output connected to the monitor– cerr : output connected to the monitor

Glenn Stevenson CSIS 113A MSJC

Standard InputYour

Program

Standard Output

Standard Error

Keyboardor

File

Monitoror

File

Monitor

14OOP03.WMF Figure 14-3 Standard input, standard output, standard erro

Page 28: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Formatting your code

• C++ is a free-form language– Interchangably use spaces, tabs and newlines

A.int main() { cout << "Hi"; return 0; }B.int

main ( ) {cout <<"Hi" ;

return 0 ; }

Glenn Stevenson CSIS 113A MSJC

Page 29: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Formatting II

• Cannot use whitespace between parts of a token– A token is one or more characters with a single

meaning• /*, */, <<, // are all tokens• Keywords like int and return are tokens

– Here are some uses of illegal whitespace with tokensin t main( ) { cout < < "Hi" ; ret urn 0; }

– You cannot put a literal newline in a stringcout << “This is illegal”;cout << “But this ”

“is legal!”;

Glenn Stevenson CSIS 113A MSJC

Page 30: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Code Formatting III

• Must use whitespace to separate some tokens– cout<<"Hello there"; // Not required– intmain(){return0;} // Spaces needed

int main(){return 0;} // OKint main(){return(0);} // OK

Glenn Stevenson CSIS 113A MSJC

Page 31: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Values & Variables

• Values are discrete quantities of data– Here are some values:

• 1, 3.1459, “Glenn”, D, true

– Values represent different kinds of things• In programming, this is called a value's type• integers, real, text [strings], characters, Boolean

• Variables are:– Named storage locations that hold values– Every variable holds a value of a certain type

• The type defines the legal operations and the required memory to store it (size)

Glenn Stevenson CSIS 113A MSJC

Page 32: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Declaring Variables

• C++ has two statements devoted to variables– Declaration statements and assignment statements

• A declaration statement specifies:– The name of memory location– The kind of thing (type) stored at the location

int fleas;

– This creates an integer variable named fleas• The compiler sets aside memory to store an int

– The amount of memory for an int is implementation dependent

• Makes sure that you use variable appropriately• Cannot store a string in fleas, for instance

Glenn Stevenson CSIS 113A MSJC

Page 33: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Variable Definition I

• I like to think of the compiler taking a box of the correct size for the type of variable (a variable can be from 1 to n bytes in size), and writing the name, type of variable and its address on the outside.– The box will hold the value of the variable when it’s

used.• The boxes are then stacked away in storage

Glenn Stevenson CSIS 113A MSJC

Name: iType: intAddress: 5000

Name: chType: charAddress: 5004

Name: rType: doubleAddress: 5005

4 byte box 1 byte box 8 byte box

Page 34: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Variable Definition II

Glenn Stevenson CSIS 113A MSJC

5000 …x

5001 …5002 …5003 …

5004 … ch

5005 …

r5006 …5007 … …

x int 5000ch char 5004r double 5005

x int 5000ch char 5004r double 5005

Page 35: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

LValues

• An LValue is nothing more than something that is to the left of the equal sign. – Since values get assigned from right to left, the

lvalue must alway be a variable . • This means that you cannot do something like this:

Glenn Stevenson CSIS 113A MSJC

int x = 30;25 = x; //Can’t Do this

Page 36: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Variable Naming Rules • Variable names can consist of letters,

numbers, and the underscore but cannot begin with a number.

• They can also not be a C++ keyword like if, else, for, etc.

• Variable names cannot contain a space character.

Glenn Stevenson CSIS 113A MSJC

int my Var; // This is not validint myVar; // This is valid

Page 37: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Naming Conventions• Naming conventions have changed over the

years it used to be that if you had a variable name that had two words in it you would separate the words with an underscore. – int my_int_variable;

• Later people starting capitalizing every word. – int MyIntVariable;

• Currently, the convention is to capitalize from the second word on:– int myIntVariable;

Glenn Stevenson CSIS 113A MSJC

Page 38: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Number Types

• C++ has several number types in two categories– Integral

• Counting numbers – Signed – Unsigned

– Floating-point• Real numbers (numbers with a fractional part)

Glenn Stevenson CSIS 113A MSJC

Page 39: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Numeric Type Sizes

Name Bytes Range Digitsshort (also called short int)

2 -32,767 to +32,767 N/A

int 4 -2,147,483,647 to +2,147,483,647

N/A

long (also called long int)

4 -2,147,483,647 to +2,147,483,647

N/A

float 4 10-38 to 10+38 7

double 8 10-308 to 10+308 Approximately 15

long double 10 10-4932 to 10+4932 Approximately 19

char 1 All ASCII Characters N/A

bool 1 true, false N/A

Glenn Stevenson CSIS 113A MSJC

Page 40: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Losing Precision• Copying values from one type of a variable

to another type can force a loss of data.

Glenn Stevenson CSIS 113A MSJC

double d = 33.456;int x;x = d;

• x holds an integer value and the code is attempting to store double in it. – These are different size buckets!

• the double will get truncated to an integer– The value stored in x is 33.

Page 41: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Losing Precision II

• You can put smaller values into bigger buckets because they will fit: .

Glenn Stevenson CSIS 113A MSJC

double d;int x = 30;d = x; //This is fine, no loss of data

• You may actually want to store a large value in a small bucket. – You can do this without the compiler

complaining by casting the value. – Future topic

Page 42: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers

• Unsigned (positive) binary integers– Converting a binary number to decimal

• Each binary digit represents a power of 2• Just like decimal digits represent power of 10

– So what is 10110101 binary in decimal?• 27 26 25 24 23 22 21 20

128 64 32 16 8 4 2 1 •• 1 0 1 1 0 1 0

1•

128 0 32 16 0 4 0 1

• = 181

Glenn Stevenson CSIS 113A MSJC

Page 43: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers II

• So what’s 0x608bfa05 in decimal?• 5 x 160 = 5 x 1 = 5

0 x 161 = 0 x 16 = 0A x 162 = 10 x 256 = 2,560F x 163 = 15 x 4096 = 61,440B x 164 = 11 x 65536 = 720,8968 x 165 = 8 x 1048576 = 8,388,6080 x 166 = 0 x 16777216 = 06 x 167 = 6 x 268435456 =1,610,612,736

1,619,786,245• So 01100000100010111111101000000101

= 014042775005 = 0x608bfa05 = 1,619,786,245

Glenn Stevenson CSIS 113A MSJC

Page 44: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers III

• Converting a decimal number to binary– Find largest power of 2 and subtract; repeat– Example: Decimal 89 as binary

• Largest power of 2 is 64 : 0100-0000• Subtract 64 from 89 = 25• Find next power of 2 [16] : 0101-0000• Subtract 16 from 25 = 9• Find next power of 2 [8] : 0101-1000• Subtract 8 from 9 = 1• Find next power of 2 [1] : 0101-1001• = 0x59

Glenn Stevenson CSIS 113A MSJC

Page 45: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Number IV

• A way with a lot less work – convert to hex first– Find the largest power of 16 and subtract the multiples– Example: Decimal 89 as binary

• Largest power of 16 is 16: 0x50• Subtract 5 * 16 from 89 = 9• Next smallest power of 16 is 1: 0x59• Subtract 9 * 1 from 9 = 0• Convert hex to binary by inspection

– = 0101 1001

Glenn Stevenson CSIS 113A MSJC

Page 46: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers V

• An easier way to convert– In Windows there is a calculator application (usually in the

accessories group)• Make certain that the scientific option is selected under the view

menu• Use the Hex, Oct, Dec and Bin radio buttons to convert numbers

• You’re probably now wondering why do I need to know this stuff???– C++, like it predecessor C, can do low-level programming

• You can “bit-twiddle” which is frequently necessary when dealing with hardware and systems programming

– When examining memory the addresses and values are normally displayed in hex

Glenn Stevenson CSIS 113A MSJC

Page 47: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers VI

• How can signed binary integers be stored?– One scheme is called sign-magnitude method– Give up a bit to represent sign (0 = positive)– Remaining bits represent magnitude– 1011 - 0101

= - (32 + 16 + 4 + 1) = -53

– Not generally used because of the two-zeros problem

– 0000-0000 = +0 1000-0000 = -0

Glenn Stevenson CSIS 113A MSJC

Page 48: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers VII

• One’s complement– MSB [most-significant-bit] is used for sign bit– If it is set, then one's complement is used to calculate

the magnitude of negative number– One’s complement:

• Reverse every bit (0 1 and 1 0)– Also called complement

• Interpret result as an unsigned number• Place minus sign in front of answer

– Still results in two zeros• 0000 – 0000 = +0• 1111 – 1111 = -0

Glenn Stevenson CSIS 113A MSJC

Page 49: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers VII

• Two's complement results in one zero– MSB [most-significant-bit] is used for sign bit– If it is set, then two's complement is used to

calculate the magnitude of negative number– Two's complement:

• Reverse every bit [simple, or one's complement]• Add one to the result• Interpret result as an unsigned number• Place minus sign in front of answer

Glenn Stevenson CSIS 113A MSJC

Page 50: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers VIII

• Wait a minute, how do I add 1 in binary?– 0 0 1

+0 +1 +10 1 10

– 1 + 1 = 0 carry 1

– So– 1011

+ 11100

Glenn Stevenson CSIS 113A MSJC

Page 51: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers IX

• Wait a minute, how do I add 1 in binary?– 0 0 1

+0 +1 +10 1 10

• 1 + 1 = 0 carry 1

– So– 1011

+ 11100

Glenn Stevenson CSIS 113A MSJC

Page 52: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers X

• Signed binary to decimal examples– 0000-0011 = + 3– MSB is clear - treat as positive unsigned– 1000-0011 = ???– MSB set - negative-perform two's complement

• 1. Reverse all of the bits : 0111-1100• 2. Add one to result : 0111-1101• 3. Interpret result : 64+32+16+8+4+1 = 125• 4. Add minus sign : -125

Glenn Stevenson CSIS 113A MSJC

Page 53: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Binary Numbers XI

• How to convert negative decimal numbers– 1. Convert absolute value to binary– 2. Perform two's complement on result

• Example: convert -59 to binary– 1. Binary magnitude (59)– 0011-1011– 2. Perform two's complement– 1100-0100

+ 1 1100-0101

Glenn Stevenson CSIS 113A MSJC

Page 54: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Integral Number Types

• C++ Built-in Integral types– char, unsigned char, and signed char– short and unsigned short– int and unsigned int (or unsigned)– long, unsigned long

• In this course we will use int primarily– On our 32-bit machines it takes 32-bits or 4 bytes to

store an int– Range

• -2,147,483,648 to 2,147,483,647

– climits header defines limits

Glenn Stevenson CSIS 113A MSJC

Page 55: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

The int data type I

• "Basic" integer is a signed whole number– Size depends upon underlying platform– On 16-bit systems - 16-bit int– Today, almost all systems are 32 bit, tomorrow 64?

• Integer modifiers include:– long [at least 32 bits, never smaller than int]– short [at least 16 bits, never larger than int]– unsigned [only positive numbers]– Use of modifiers implicitly assumes type int

e.g. long x; is equivalent to long int x;– char one byte – may be signed do or unsigned

Glenn Stevenson CSIS 113A MSJC

Page 56: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

int data type II

• How is an int stored in my computer– It depends on your processor

• Intel processors use “Little Endian”– Two byte words stored least significant word first with each word

stored least significant byte first

– So 0x608bfa05 would be stored in memory as 05 fa 8b 60

• Many other processors use “Big Endian”– Words and bytes are stored most significant word and byte first

– So 0x608bfa05 would be stored in memory as 60 8b fa 05

– If you use a memory dump to debug, this is what you will see

Glenn Stevenson CSIS 113A MSJC

Page 57: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

The sizeof operator

• C++ mandates size "relationships"• How can you find actual size of object?

– Use the sizeof operator (note operator - not a function)

– Returns size in "bytes" [usually 8 or 16 bits per byte – implementation dependent]

• cout << "sizeof 123 = " << sizeof 123;cout << "sizeof a = " << sizeof a;

– Parentheses required when using a type-name• cout << "sizeof (int) = " << sizeof (int);

Glenn Stevenson CSIS 113A MSJC

Page 58: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Floating Point Number Types

• C++ Built-in Floating-point types– float– double– long double

• In this course we will primarily use double– On our 32-bit machines it takes 128 bits or 8 bytes to

store a double– Range

• 2.2250738585072014e-308 to 1.7976931348623158e+308– Precision

• 15 digits– cfloat header defines limits

Glenn Stevenson CSIS 113A MSJC

Page 59: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Scientific Notation

• Also sometimes called Exponential Notation• Usually used to express very large or very small numbers

– speed of light in a vacuum = 2.99 x 108 meters/sec – Distance to Alpha Centauri = 5.863 x 1012 miles– Size of a hydrogen atom ≈ 10-10 meters– Mass of an electron = 9.11 x 10-31 kg– Number of atoms in the entire universe ≈ 1080

• Expressed by a sign followed by a single digit followed by a decimal fraction followed by a power of ten– The single digit plus the fraction is called the mantissa– The power of ten is called the exponent

Glenn Stevenson CSIS 113A MSJC

Page 60: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Scientific Notation II

• So 7.3125 (7 5/16) is– 111.0101– We can write this as– 1.110101 x 22– In this case

• the sign is positive• the mantissa is 1.110101• the exponent is 2

Glenn Stevenson CSIS 113A MSJC

Page 61: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Scientific Notation III

• 0.1875 (3/16) is– 0.0011 or

1.1 x 2-3– In this case

• the sign is positive• the mantissa is 1.1• the exponent is -3

Glenn Stevenson CSIS 113A MSJC

Page 62: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Scientific Notation IV

• And -55.25 is– -110111.01 or

-1.1011101 x 25– In this case

• the sign is negative• the mantissa is 1.1011101• the exponent is 5

Glenn Stevenson CSIS 113A MSJC

Page 63: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Scientific Notation V

• What about 1.1?– 1.000110011001100110011001100…– 0.1 cannot be exactly represented as a binary

fraction• This is similar to 1/3 not being able to be exactly

represented as a decimal fraction: 0.333333333333…

• This is referred to as representational error

Glenn Stevenson CSIS 113A MSJC

Page 64: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Scientific Notation VI

• So how do we store these numbers in our computer?– There are several conventions

• Most common is IEEE (Institute of Electrical and Electronics Engineers) standard

– Real*4 sign bit + 8-bit exponent + 23 bit mantissa– Real*8 sign bit + 11-bit exponent + 52 bit mantissa– Real*10 sign bit + 15-bit exponent + 64 bit mantissa

Real*4 Real*8 Real*10

Precision (min) 6 digits 15 digits 18 digits

Max Exponent 38 308 4932

Min Exponent -37 -307 -4931

Glenn Stevenson CSIS 113A MSJC

Page 65: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Arithmetic Operators

Operator Meaning

+ Add

- Subtract

* Multiply

/ Divide

% Modulous

• int x = 3, y = 0;• y = x + 6;• y = x – 2;• y = x * 2• y = 6 / x;• Y = 6 % 3;

Glenn Stevenson CSIS 113A MSJC

10 % 3 results in 1 Because 10 / 3 = 3 with a remainder of 1 12 % 7 results in 5 Because 12 / 7 = 1 with a remainder of 5 20% 5 results in 0 Because 20 / 5 = 4 with a remainder of 0

Page 66: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Shortcut Notation

int x = 4; Equivalent Value

x+=5; x = x + 5 9

x-=1; x = x -1; 3

x*=5; x = x * 5; 20

x/=2 x = x / 2 4

x%=3 x = x % 3 1

Glenn Stevenson CSIS 113A MSJC

Page 67: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Escape Characters• A character pair that you can put into a string to perform an action.

\n Newline

\r Move the cursor back to the beginning of the line

\t Insert a tab

\\ Insert a single backslash

\’ Single quote

/” Double quote

Below are not commonly used

\v Vertical tab

\b backspace

\f Form feed

\? Questions mark

Glenn Stevenson CSIS 113A MSJC

cout<<“hello\n”;

cout<<“hello” << endl;

Page 68: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Constants

• A read only variable– It cannot be changed programmatically

• Example: PI

• Use const keyword– const double PI = 3.14159265 ;

• By convention– const variables should be ALL CAPS

Glenn Stevenson CSIS 113A MSJC

Page 69: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

C Typecasting• Used to intentionally convert numbers

– From one type to another• Can store small value in a larger bucket• Cannot store larger value in smaller bucket

– Possible loss of data

Glenn Stevenson CSIS 113A MSJC

int x = 0;double z = 33.345;x = z; // x now holds 33. Value is truncated & compiler // warning possible compiler error

x = (int) z; //Temporarily converts z to an int. Still truncates but // no error or warning

x = static_cast<int> z ; // c++ cast covered later

Page 70: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Shorthand operators

• Called unary operators– They operate on a single variable!– ++ // increments a variable by one– -- // decrements a variable by one

Glenn Stevenson CSIS 113A MSJC

int x = 3;int y = 2;

x++; // x is now 4y--; // y is now 1

Page 71: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Post & Pre Increment/ Decrement

• Can apply shorthand operators 2 ways– Before variable ++x– After Variable x++– Whats the difference?

• Consider:

Glenn Stevenson CSIS 113A MSJC

int x = 2;int y = 0;y = 1 * x++; // What does y equal here?

y = 1 * ++x; // Now what does y equal

Page 72: CSIS 113A Introduction To C++ Glenn Stevenson CSIS 113A MSJC.

Coding Style

• You should adopt a coding style that makes your code readable. – Typically, you should indent whenever a block

of code starts. and move it back when the block ends.

• How far you indent depends on your preference. – I prefer 3 spaces. Some people like to do a tab, and still

others like 4 spaces. Whatever you decide, be consistent.

Glenn Stevenson CSIS 113A MSJC

Int main(){ cout << “Hello World” << endl; // Notice indent}