dive into c++ lesson 1: introduction by jordan moldow & stephan boyer hssp 2011

27
Dive into C++ Dive into C++ Lesson 1: Lesson 1: Introduction Introduction By Jordan Moldow & Stephan Boyer By Jordan Moldow & Stephan Boyer HSSP 2011 HSSP 2011

Upload: arnold-rodgers

Post on 12-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Dive into C++Dive into C++Lesson 1: IntroductionLesson 1: Introduction

By Jordan Moldow & Stephan BoyerBy Jordan Moldow & Stephan Boyer

HSSP 2011HSSP 2011

Page 2: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

ProgrammingProgramming

• A program is “a sequence of coded A program is “a sequence of coded instructions for a computer”instructions for a computer”

• Programming is the coding of these Programming is the coding of these instructions by humansinstructions by humans

• ““The purpose of programming is to The purpose of programming is to create a program that exhibits a create a program that exhibits a certain desired behavior.”certain desired behavior.”

• Programming is “writing the source Programming is “writing the source code of computer programs”code of computer programs”

Page 3: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

General Programming StepsGeneral Programming Steps1.1. Pick programming languagePick programming language

2.2. Write “source code” in text fileWrite “source code” in text file• Source code is understandable by Source code is understandable by

humans [who know the language]humans [who know the language]• Each language has different code Each language has different code

syntaxsyntax

3.3. A “compiler” translates source into A “compiler” translates source into binary / machine code that is binary / machine code that is understandable by computersunderstandable by computers

4.4. Computer executes codeComputer executes code

Page 4: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Writing C++ ProgramsWriting C++ Programs

• Code can be written and saved using Code can be written and saved using special programming environments – file special programming environments – file type is .cpptype is .cpp

• Code can also be written in a normal text Code can also be written in a normal text editoreditor• *nix: vim, emacs, gedit, NOT OpenOffice*nix: vim, emacs, gedit, NOT OpenOffice• Windows: Notepad, Notepad++, NOT WordWindows: Notepad, Notepad++, NOT Word

• In this guide, all code is written in the In this guide, all code is written in the Courier NewCourier New font, and output is font, and output is boldedbolded

• Compiler outputs your code to an Compiler outputs your code to an executable executable • .out on a *nix system.out on a *nix system• .exe on a Windows system.exe on a Windows system

Page 5: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Using the Command LineUsing the Command Line

• Also known as the shell or terminalAlso known as the shell or terminal• Interface with the computerInterface with the computer• Default “path” in *nix is the home Default “path” in *nix is the home

folderfolder• Create new subdirectories with Create new subdirectories with mkdirmkdir• Change the path with Change the path with cdcd

• When you specify files, computer When you specify files, computer checks the path for the fileschecks the path for the files

Page 6: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Hello World! Your First Program!Hello World! Your First Program!• A programming tradition – your A programming tradition – your

first program simply outputs the first program simply outputs the text text Hello World!Hello World!

• ““Output” means to write text on Output” means to write text on the screenthe screen

• Copy the code for hello.cppCopy the code for hello.cpp• Compile and run the programCompile and run the program

Page 7: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Compiling and RunningCompiling and Running

• Make sure the file is in pathMake sure the file is in path• If not, use If not, use cd cd to switchto switch

• g++ <filename>.cppg++ <filename>.cpp• By default, executable is named a.out (in By default, executable is named a.out (in

*nix)*nix)• Two ways to change this:Two ways to change this:

• rename the file: rename the file: mv a.out <filename>mv a.out <filename>• g++ <filename>.cpp –o <filename>g++ <filename>.cpp –o <filename>

• To run: To run: ./<filename>./<filename>

Page 8: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Outline of a basic C programOutline of a basic C program/*/*Name: Name: Program: Program: Language: C++Language: C++Description of Program: Description of Program: */*/

#include <iostream>#include <iostream>using namespace std;using namespace std;int main() {int main() {/* some code here *//* some code here */return 0;return 0;

}}

Page 9: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

CommentsComments

• /*/* starts a comment starts a comment• */*/ ends a comment ends a comment

• text inside a comment is not compiledtext inside a comment is not compiled

• add comments to your source code so others add comments to your source code so others can understand your programcan understand your program

• comments can be inserted anywhere (except in comments can be inserted anywhere (except in the middle of a “word”)the middle of a “word”)

Page 10: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

#include <iostream>#include <iostream>• The The #include#include statement loads standard statement loads standard

library fileslibrary files• iostreamiostream is a library of input and output is a library of input and output

functionsfunctions

• Right now, you don’t need to know what’s Right now, you don’t need to know what’s involved in the libraryinvolved in the library

• Just make sure to include it in the first Just make sure to include it in the first non-commented line of every programnon-commented line of every program

Page 11: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

using namespace std;using namespace std;• Every pre-defined library object, Every pre-defined library object,

function, or variable you will ever use function, or variable you will ever use is defined inside some namespaceis defined inside some namespace

• Make sure to include this line at the start Make sure to include this line at the start of every programof every program

• We will not cover anything more about We will not cover anything more about namespacesnamespaces

Page 12: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

int main() {}int main() {}The “main function”The “main function”

• Required for any C++ programRequired for any C++ program

• Everything inside the Everything inside the {}{} is executed when the is executed when the program runsprogram runs

• Brackets indicate blocks of codeBrackets indicate blocks of code

• The parenthesis ARE necessaryThe parenthesis ARE necessary

Page 13: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

returnreturn

• In basic C++ programs, this is used In basic C++ programs, this is used to end the programto end the program

• The last line of the main function The last line of the main function should be should be return 0;return 0;

Page 14: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Statements and Semicolons Statements and Semicolons ;;• Programs are made up of statements:Programs are made up of statements:

int main() {int main() {

do_this;do_this;

do_that;do_that;

do_something_else;do_something_else;

return 0;return 0;

}}• Every statement ends with a semicolonEvery statement ends with a semicolon• Every statement performs one (sometimes Every statement performs one (sometimes

more) action(s)more) action(s)

Page 15: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

The The coutcout Object - Part 1 Object - Part 1• Used to output text on the screenUsed to output text on the screen• cout << “Hello World!”; /* outputs cout << “Hello World!”; /* outputs

Hello World!Hello World! */ */• cout << “text”; /* outputs cout << “text”; /* outputs texttext (literally, in this case) */(literally, in this case) */

• Don’t forget the left carrots and quotationDon’t forget the left carrots and quotation marks!marks!– The carrots and the quotation marks don’t show up in The carrots and the quotation marks don’t show up in

the outputthe output– If you want to display quotation marks, use If you want to display quotation marks, use \”\” in your in your

messagemessage• cout << “\”Hello World!\””;cout << “\”Hello World!\””; outputs outputs “Hello World!”“Hello World!”

Page 16: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Line BreaksLine Breaks

• There are two ways to insert line breaks into There are two ways to insert line breaks into your outputyour output

1.1. cout << “text” << endl;cout << “text” << endl;

2.2. cout << “text\n”;cout << “text\n”;• There is a difference between the two that we There is a difference between the two that we

will cover laterwill cover later

Page 17: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

So wait, can C++ do anything So wait, can C++ do anything besides print messages?besides print messages?

• Yes, it can! Yes, it can! • C++ can store and manipulate data C++ can store and manipulate data

using variablesusing variables• Math can be performed on these Math can be performed on these

variablesvariables• Try the variables.cpp programTry the variables.cpp program

Page 18: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

VariablesVariables• Locations in memory for dataLocations in memory for data

• 3 main types of variables: 3 main types of variables: int, char, floatint, char, float

• intint variables: signed whole numbers: variables: signed whole numbers: 1717, ,

-34-34, , 203203, etc., etc.• floatfloat variables are signed decimal numbers: variables are signed decimal numbers: 17.017.0, , -34.34-34.34, , 203.2203.2, etc., etc.

Page 19: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Declaring a VariableDeclaring a Variable• int int namename = = valuevalue ; ;

• This creates a space in memory This creates a space in memory – example, example, int a = 27;int a = 27; creates the variable a with an creates the variable a with an

integer value of 27integer value of 27

• Case sensitivity: Case sensitivity: int varint var and and int Varint Var are are different!different!

• You can name your variable anything you want! You can name your variable anything you want! VarVar, , xx, , elephantelephant, etc., etc.

• But no two variables can have the same nameBut no two variables can have the same name

• All variables are declared at the start of main() - not All variables are declared at the start of main() - not in the middle!in the middle!

• Variables are limited in size – they cannot store Variables are limited in size – they cannot store very large numbersvery large numbers

Page 20: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Variable ManipulationVariable Manipulation

• Variables can change their after they’ve been Variables can change their after they’ve been declared values, example:declared values, example:

var1 = 10; /* var1 is now 10 */var1 = 10; /* var1 is now 10 */var2 = 20; /* var2 is now 20 */var2 = 20; /* var2 is now 20 */var3 = var1 + var2; /* var3 is now var3 = var1 + var2; /* var3 is now 30 */30 */

• == is used for assignment. is used for assignment. var1 = 10var1 = 10 gives gives var1var1 a value of 10 and discards the old value. a value of 10 and discards the old value.

• == is called the “assignment operator” is called the “assignment operator”

Page 21: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Mathematical OperatorsMathematical Operators

Addition (+) c = a + b; Subtraction (-) c = a - b;

Negative (-) c = -b; Multiplication (*) c = a * b;

Division (/) c = a / b; Modulus (%) c = a % b;

Parenthesis ( () ) d = (a+b)*c;

Increment (++) ++a; Decrement (--) --a;

Page 22: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

The The coutcout Object - Part 2 Object - Part 2 • The object can also display variable values!The object can also display variable values!

int int1 = 17, int2 = 34;int int1 = 17, int2 = 34;

cout << “text ” << int1 << “ text ” << int2;cout << “text ” << int1 << “ text ” << int2;

Output: Output: text 17 text 34text 17 text 34– cout can display multiple strings at once, by separating the strings by cout can display multiple strings at once, by separating the strings by <<<<

– When variable names are used, the string conversion of the variable is When variable names are used, the string conversion of the variable is displayeddisplayed

– Don’t put variable names inside quotation marks!Don’t put variable names inside quotation marks!

• Strings are displayed in the order they are placed on the lineStrings are displayed in the order they are placed on the line

Page 23: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

The The cincin Object Object• The cin object is the opposite of coutThe cin object is the opposite of cout

• It takes input from the keyboard and stores it in variablesIt takes input from the keyboard and stores it in variables

int int1;int int1;

cout << “Enter an integer: “;cout << “Enter an integer: “;

cin >> int1;cin >> int1;

// if you type an integer and press Enter, it will store // if you type an integer and press Enter, it will store that value in int1that value in int1– cin can take multiple inputs at once, by separating the variables cin can take multiple inputs at once, by separating the variables

by by >>>>

Page 24: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Control FlowControl Flow

• C++ offers a variety of methods that C++ offers a variety of methods that allow the selective use of codeallow the selective use of code

• You can write pieces of code that are You can write pieces of code that are repeated a certain number of times, repeated a certain number of times, or that only runs under certain or that only runs under certain conditionsconditions

• Try running the if.cpp programTry running the if.cpp program

Page 25: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

if(){}, else if(){}, else{}if(){}, else if(){}, else{}

• if(if(expressionexpression){}){} executes its block of code executes its block of code only if the expression is trueonly if the expression is true

• else if(else if(different_expressiondifferent_expression){}){} executes its block of code only if all preceding executes its block of code only if all preceding ifif--expressions and expressions and else ifelse if-expressions were false -expressions were false AND the new expression is trueAND the new expression is true

• else{}else{} works only if all previous works only if all previous ifif-expressions -expressions and and else ifelse if-expressions were false-expressions were false

Page 26: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

ExpressionsExpressions

Equal

a == b

Greater than

a > b

Less than

a < b

Not equal

a != b

Greater or equal

a >= b

Less or equal

a <= b

Page 27: Dive into C++ Lesson 1: Introduction By Jordan Moldow & Stephan Boyer HSSP 2011

Boolean ExpressionsBoolean Expressions

• &&&& is AND and is AND and |||| is OR is OR• A AND B is true only if expressions A and B are both trueA AND B is true only if expressions A and B are both true

• A OR B is true as long as either expression A or expression B (or both) A OR B is true as long as either expression A or expression B (or both) are trueare true

• if (x>=0 && x<=9){ /* code */ }if (x>=0 && x<=9){ /* code */ }• the code is executed only if the code is executed only if xx is greater than or equal to 0 and less than is greater than or equal to 0 and less than

or equal to 9or equal to 9

• else if (x<-1 || x>10){ /* other code */ }else if (x<-1 || x>10){ /* other code */ }• the code is executed only if the previous the code is executed only if the previous ifif-block was skipped, and if -block was skipped, and if xx is either less than -1 or greater than 10 is either less than -1 or greater than 10