66
1 3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ Programming in C++ z A C++ program is a collection of one or more functions (or procedures) z Functions (in C++ program) are very much like functions in mathematics z A function is like a black box z There must be a function called main( ) in every executable C++ program z Execution always begins with the first statement in the function main( ) Any other functions in your program are sub-programs and are not executed until they are called (either from main() or from functions called by main()) 2 3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ Structure of main() function

3. The Nuts and Bolts of C++ Programming in C++lnx01.ee.polyu.edu.hk/~eewlchan/ENG2002/Ch3.pdf · 2015. 8. 26. · 1 3. The Nuts and Bolts of C++ Computer Programming Programming

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

  • 1

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Programming in C++A C++ program is a collection of one or more functions (or procedures)Functions (in C++ program) are very much like functions in mathematicsA function is like a black boxThere must be a function called main( ) in every executable C++ programExecution always begins with the first statement in the function main( )– Any other functions in your program are sub-programs

    and are not executed until they are called (either from main() or from functions called by main())

    2

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Structure of main() function

  • 3

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include

    int main(){

    std::cout

  • 5

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Preprocessor#include • When compiling a file, we need to obtain the definitions of

    some terms in the program codes • These definitions are recorded in some header files• These files are shipped with the compiler or other resources• #include tells the compiler where to find the header files

    and insert this file to that location of the programe.g. #include tells the compiler it should

    get the file iostream through the default pathe.g. #include "myfile" tells the compiler it should get

    the file myfile in the current folder.

    6

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Program Codes

    int main(){

    std::cout

  • 7

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    main()Call main()

    Return 0

    Means everything fine on executing main()as it is the last statement

    • The main() function is the beginning point of a program• When executing a program, the operating system will first

    call the main() function of this program• If the above main() function executes successfully, it

    should return an integer 0 to the operating system

    8

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    int main(){

    std::cout

  • 9

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • std::cout and std::endl means that we are referring to the cout and endl of the std namespace

    • The std namespace is defined in iostream• Namespace – A new feature of C++

    • Design to help programmers develop new software components without generating naming conflicts

    • Naming conflict – A name in a program that may be used for different purpose by different people•cout and endl are not a part of C++, people can use

    these two names for any purpose; not necessarily referring to standard output and newline.

    Namespaces

    Folders and files concept in XP

    10

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include

    namespace myns {int cout=0; //Integer variable

    } //No semi-colon

    int main(){

    std::cout

  • 11

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include

    namespace myns {int cout=0;

    }

    int main(){

    std::cout

  • 13

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int main(){

    cout

  • 15

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Comments• A program needs to be well commented to explain the

    important points of the program• Adding comments in the program will not affect the

    program execution but only improve readability• Comments can be added in two ways:#include using namespace std;int main(){/* Text between these two marks are comments*/

    cout

  • 17

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Exercise 3.1aa. Build the program in p.13. Note the output on the console.b. Add one statement to the program which will show your

    name and age in a single sentence. The name should be shown as a character string. The age should be shown as an integer.

    c. Use the comment symbols /* and */ to comment the statements from line 5 to line 9 (inclusive). Is there any change to the results output?

    18

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Function

    main is a functionWhat is a function?

    – A collection of C++ statements to carry out a specific task!

    You can have more functions in your program!How to declare a function ?

    – A proper name – must be unique – Return type– The function body

  • 19

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Example of a function

    int main(){/* Text between these two marks are comments*/

    cout

  • 21

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++ Function Definition

    ReturnDataType FunctionName ( Parameter List ){

    Statement(s)...

    }

    int Cube ( int n ) header{

    bodyreturn n * n * n ;

    }

    22

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • Although a single main() function is enough for any C++ program, it’s a bad habit to do everything by a single function

    • C++ allows nesting of functions to facilitate "divide and conquer" of jobs

    • The function main() can call other functions to help it complete a task

    • When a function is called, the program branches off from the normal program flow

    • When the function returns, the program goes back to where it left before.

    More on Functions

  • 23

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;//function DemonstrationFunction()// show a useful messagevoid DemonstrationFunction(){

    cout

  • 25

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int main(){

    cout

  • 27

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Function prototype

    void DemonstrationFunction(){

    cout

  • 29

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Function with input parameters

    int Add (int x, int y){ cout

  • 31

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Exercise 3.1ba. Build the program in the last slide. Note the output on the

    console.b. Modify main() to calculate the square of c. Add one more

    function called Square() to achieve this. The Square()function will take the square of the parameter that is passed to it. It will return the result in the form of an integer back to the calling function.

    32

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Variables – Variable names (identifiers) correspond to locations in the

    computer's memory– Every variable has a name, a type, a size and a value– Whenever a new value is placed into a variable, it replaces (and

    destroys) the previous value. (Destructive write)– Reading variables from memory does not change them

    Variable Concepts

    36443int

    45i4 bytes

    addressvaluevariable datatype size

    int i = 45;

  • 33

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • A variable is actually a place to store information in a computer• It is a location (or series of locations) in the memory

    • The name of a variable can be considered as a label of that piece of memory

    0000 0001 0010 0011 0100 0101 0110 0111 1000 1001AddressMemory

    Variables char a int b short int c bool d

    10 0A 21 3A 51 44 20 00

    Variables and Memory

    One address for one byte, i.e. 8 bits.

    in hex

    in bin

    34

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • In memory, all data are groups of ‘1’ and ‘0’, byte by byte• Depending on how we interpret the data, different types of

    variables can be identified in the memory

    Size of Variables

    Typeboolunsigned short intshort intunsigned long intlong intunsigned intintchar floatdouble

    Size1 byte2 bytes2 bytes4 bytes4 bytes4 bytes4 bytes1 byte4 bytes8 bytes

    Valuestrue or false (1 or 0)0 to 65,535 (216 - 1)-32,768 to 32,7670 to 4,294,967,295 (232 - 1)-2,147,483,648 to 2,147,483,6470 to 4,294,967,295-2,147,483,648 to 2,147,483,647256 character values(+/-)1.40x10-45 to (+/-)3.40x1038(+/-)4.94x10-324 to (+/-)1.80x10308

    unsigned long long 8 bytes 0 to (264 - 1)long long 8 bytes -263 to (263 - 1)

  • 35

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • Before we use a variable, we need to declare its type so that the compiler can reserve suitable memory space for it

    • Variables are declared in this way:

    • It defines myVariable to be an integer. Hence 4 byteswill be reserved for its storage in memory

    • The name of the variable is case sensitive, hencemyVariable is NOT the same as myvariable

    Declaring Variables

    int myVariable;

    36

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Variable Declarations

    type v1,v2,v3, …, vnExample:

    int count;int j;float k;double area;char c;short int x;long int y;unsigned int z;int a1;

  • 37

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • We can declare one or more variables of the same kind at once

    • It defines myVar1, myVar2, yourVar1, yourVar2 are all integers

    • Some names are keywords of the C++ language that cannot be used as variable namese.g. return, while, for, if, etc.

    • We can even initialize the value of the variables when making the declaration

    Declaring Variables

    int myVar1, myVar2, yourVar1, yourVar2;

    int myVar1 = 10, myVar2(10), yourVar1, yourVar2 = 5;Does an uninitialized variable have a value?

    38

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Variable InitializationIf a variable is not initialized, the value of variable may be either 0 or garbage depending on the storage class of the variable.

    int count = 5; // int count(5);double length = 1.23;char c = ‘A’; // char c; c =‘A’;int i = 1, j, k = 5;char c1 = ‘B’, c2 = 66;float x = 1.23, y = 0.1;

  • 39

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int main(){ unsigned short int smallNumber;

    smallNumber = 65535; // 1111 1111 1111 1111 = 65535cout

  • 41

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int main(){ // ASCII code of '5' is 53

    char c = 53, d = '5'; // They are the sameint e = 53;cout

  • 43

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Special Printing Characters• C++ compiler recognizes some special characters for

    output formatting• Start with an escape character \ (e.g. \n means new line)

    Character\n\t\b\"\'\a\\

    What it Meansnew linetabbackspacedouble quotesingle quotebellbackslash

    escape sequence

    //using goto, not recommended

    #include using namespace std;

    int main(){int i = 0; char c = i;

    beg: // label for goto

    cout

  • 45

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Floating-point numbersFloating-point number (real number): zero or any positive or negativenumber containing a decimal point

    Examples: +10.625 5.0 -6.2No special characters are allowed

    Three floating-point data types in C++:– float (single precision) 7 significant digits 1.2F– double (double precision) 15 significant digits 1.2– long double (same as double for Visual C++) 1.2L

    46

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Exponential Notation

    Floating point numbers can be written in exponential notation, where e or E stands for exponent

    6.25E-4

    10-3

    10-4

  • //Comparing int, double and float

    #include using namespace std;

    int main (){

    cout.precision(20);

    cout

  • 49

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • A symbolic constant can be defined in two ways1. Old way - use the preprocessor command #define

    • No type needs to be defined for studentPerClass• Preprocessor just replaces the word studentPerClass with 87 whenever it is found in the

    source program2. A better way - use the keyword const

    • Variable studentPerClass now has a fixed value 87• It has a type now. This feature helps the compiler to

    debug the program.

    Defining Symbolic Constants

    #define studentPerClass 87

    const int studentPerClass = 87;

    50

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Why do we need Constants?

    • Help debugging the programCompiler will automatically check if a constant is modified by the program later (and reports it if modified.)

    • Improve readabilityGive the value a more meaningful name e.g. rather than writing 360, can use degreeInACircle

    • Easy modificationIf a constant really needs to be changed, we only need to change a single line in the source program.

  • 51

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int main(){ const int totalStudentNumber = 87;

    // Student no. must < 87int num;cout > num;if (num > totalStudentNumber)

    cout

  • 53

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int main(){ const int Sunday = 0;

    const int Monday = 1;const int Tuesday = 2;const int Wednesday = 3;const int Thursday = 4;const int Friday = 5;const int Saturday = 6;int choice;cout > choice;if (choice == Sunday || choice == Saturday)

    cout

  • 55

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • A C++ program comprises a number of functions • A function comprises a number of statements• A statement can be as simple as

    • It can be as complicated as

    • A statement must end with a semicolon ;• In a statement, space carries nearly no information

    Statements

    x = a + b;

    if (choice == Sunday || choice == Saturday)cout

  • 57

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Operators• An expression often comprises one of more operators• The assignment operator '=' assigns a value to a variable

    or constant, e.g. x = 39;• Several mathematical operators are provided by C++• Let a be 3, b be 4 and x is declared as an integer,

    Operators Meaning+ Add- Subtract* Multiply/ Divide % modulus

    remainder

    Examplesx = a + b; // x = 7x = a - b; // x = -1x = a * b; // x = 12x = a / b; // x = 0 (why?)x = a % b; // x = 3 (why?)

    3 modulo 4 is 3

    Any expression can be an operand

    58

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Binary Operator (two operands)+ (addition) - (subtraction) * (multiplication)/ (division) % (modulus, remainder) (no ** )

    Unary Operator (single operands)- (no + ) Example:

    int i=1, j=2, k=3, x;x=i+2*j-22/k;x=-1+j;x=1+-j;x=+i+j;x=22%k;

    float f=1.5, g=0.5, y;y=2.5*f+4.0*g;

    Exercise: Try -5%3 -5%-3 5%-3

    (hint: -5/3=-1 -5/-3=1 5/-3=-1 and R=x-y*i)

    – Mixed data types will be discussed later

    Arithmetic Operators

    (x=1 + 4 -7 = -2)(x= 1)(x= -1)(x=3)(x= 1, remainder)(y=5.75)

    Ans: -2 -2 2

  • 59

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Mixed Type Arithmetic

    Rule #1char, short → intfloat → double

    Rule #2 (double ← long ← unsigned ← int)– If either operand is double, the other is converted to double, and

    the result is double– Otherwise, if either operand is long, the other is converted tolong, and the result is long

    – Otherwise, if either operand is unsigned, the other is converted to unsigned, and the result is unsigned

    – Otherwise, the operand must be int

    60

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Mixed Type ArithmeticAssign real to int– Cut off fractional part of real

    Assign int value to real– Put decimal point at end, converts method of storage to

    exponential binary formModify with cast operators– Change type of expression– Keyword static_castexpression– Old form: (type) expression

    1.1 + 3/4 == 1.1 + 0 == 1.11.1 + (double)3 /4 == 1.1 + static_cast(3) /4 == 1.85

  • 61

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Integer and Floating Point Divisions#include using namespace std;void intDiv(int x, int y){ int z = x/y;

    cout

  • 63

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • Mathematical operations are basically performed from left to right

    • It follows the normal mathematical precedence that multiplication / division first and addition / subtraction next

    • Hence

    • To change the precedence, we can use parentheses

    • Parentheses can be nested as in normal arithmetic

    Precedence and Parentheses

    x = 5 + 3 * 8; // x = 29 since we evaluate 3 * 8 first

    x = (5 + 3) * 8; // x = 64 since we evaluate 5 + 3 first

    x = 5 * ((3 + 2) + 3 * 2); // x = 5 * (5 + 6) = 55

    64

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Rules of Operator Precedence

    1. Parentheses are applied first. If an expression contains nested parentheses, the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (that is, not nested), they are evaluated left to right.

    2. Unary plus (+) and minus (-) are applied next. If an expression contains several unary plus and minus operators, these operators are applied from right to left.

    3. Multiplication (*), division (/) and remainder (%) are applied next. If an expression contains several multiplication, division and remainder operations, these operators are applied from left to right.

    4. Addition (+) and subtraction (-) are applied next. If an expression contains several addition and subtraction operations, these operators are applied from left to right.

    5. Assignment (=) is applied last. This operator has the lowest precedence so far. If an expression contains several assignment operators, these operators are applied from right to left.

    Figure 3.15 Rules of operator precedence. • Precedence is the order in which operators are applied• Redundant parentheses make expressions easier to read

  • 65

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Relational Operators• Besides arithmetic operations, we can also perform

    relational operations with C++• A number of relational operators are defined in C++• Each relational operator returns a bool result (true or

    false)

    Operators Meaning== Equals!= Not Equals> Greater than>= Greater than

    or equals< Less than 50; // return true100 >= 50; // return true

    100 < 50; // return false100 =– Result is a integer: 1 means true

    0 means false– Declare logical type variable and constants using bool– No space between the operatorsExample:

    5 == 35 != 35 > 35 < 35 >= 35 <>=

  • 67

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • Relational operators are often used with if statement• The if statement provides branching of the program

    execution depending on the conditions

    int bigNumber = 10, smallNumber = 5;bool bigger = bigNumber > smallNumber; //bigger = trueif (bigger){ doSomeThing();}

    Applications of Relational Operators

    Or you can simply write:

    if (bigNumber > smallNumber){ doSomeThing();}

    Or you can simply write:

    if (bigNumber > smallNumber){ doSomeThing();}

    68

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Logical Operators• Logical operators do logical operations for bool variables• Each logical operation returns a bool result (true or false)

    Operators Meaning&& AND|| OR! NOT

    Examplesexpression1 && expression2expression1 || expression2!expression

    int bigNum = 10, smallNum = 5;if (bigNum < 10 && smallNum > 0){ doSomeThing();} Would doSomeThing()

    be called???Would doSomeThing()

    be called??? NO

  • 69

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    int bigNum = 10, smallNum = 5;if ((bigNum < 10 && smallNum > 0) || bigNum > smallNum){ doSomeThing();} Would doSomeThing()

    be called???Would doSomeThing()

    be called???

    int bigNum = 10, smallNum = 5;if (!(bigNum > smallNum)){ doSomeThing();} Would doSomeThing()

    be called???Would doSomeThing()

    be called???

    F T

    YES

    NO

    70

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Logical (Boolean) OperatorsBinary Operators

    && (and) || (OR)

    Unary Operator! (not)

    Operand should be int– Use float, result may be affected by round off error

    nonzero (true) zero (false)

    Result is int1 (true) 0 (false)

    – Express connected by && or || are evaluated from left to right, and evaluation stops as soon as the truth or falsehood of the result is known. i.e. ‘expr1 && expr2’ is not equal to ‘expr2 && expr1’. This is called short-circuit evaluation.

    – ‘inward == 0’ normally be written as ‘!inward’Example:

    3 < 7 < 53 < 7 && 7 < 5

    Example:

    Expression Result5||35||05&&35&&0i&&j (if i=0, j=0)i&&j+1 (if i=5, j=0)!5!0!i (if i=5)

    111001010

    (3 < 7) < 5 1 < 5 1

    1 && 0 0

  • 71

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int main(){ int a, b, c;

    cout > a;cin >> b;cin >> c;if (c = (a+b));{ cout

  • 73

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    The if / else Selection StructureCompound statement:

    – Set of statements within a pair of braces– Example:

    if ( grade >= 60 ) cout

  • 75

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Using braces with if … else#include using namespace std;int main(){

    int x;cout > x;cout = 10)if (x > 100)

    cout

  • 77

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Multiple-Selection Structure: switchswitch

    – Useful when a variable or expression is tested for all the values it can assume and different actions are taken

    Format– Series of case labels and an optional

    default caseswitch ( value ){

    case 1:Actions; break;

    case 2:Actions; break;

    default:actions

    }– break; exits from structure

    truecase 1

    case 2

    false

    case n

    case 1 break

    false

    false

    true case 2 break

    true case n break

    action(s)

    action(s)

    action(s)

    defaultaction(s)

    78

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    switch

    if (burger == 1) { unit_price = 8.5;

    }else if (burger == 2) {

    unit_price = 12;}else if (burger == 3){

    unit_price = 15.3;}else {

    cout

  • 79

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++switch … case … break

    #include using namespace std;int main(){ unsigned short int number;

    cout > number;switch (number){ case 0: cout

  • 81

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Looping• Many programming problems are solved by repeatedly

    acting on the same data• The method for achieving repeated execution is by looping• C++ provides many approaches to implement looping

    •if … goto // old way, strongly NOT recommended•while loop // use when the testing parameters are

    // complicated•do-while loop // use when the repeated part is

    // expected to be executed at least once•for loop // use when the testing parameters are

    // simple

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    int count ;

    count = 4; // initialize loop variable

    while (count > 0) // test expression{

    cout

  • 83

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    while Loops

    #include using namespace std;int main(){

    int counter = 0; //initialize counterwhile (counter 0 && small < MAXSMALL){

    if (small % 5000 == 0)cout

  • 85

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    The do/while repetition structure – Similar to the while structure– do/while is a “post-test” condition. The body of the loop is

    performed at least once.All actions are performed at least once

    – Format:do {

    statement;} while ( condition );

    Example: Prints the integers from 1 to 10.(letting counter = 1):

    do {cout

  • 87

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    for loops syntaxfor ( initialization ; loopContinuationTest ; increment )

    statementExample: Prints the integers from one to tenfor ( counter = 1; counter

  • 89

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Different varieties of for loops#include using namespace std;int main(){ for (int i=0, j=0; i

  • 91

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    continue and break• Keywords continue and break allow one to change the

    program flow during looping• Should be used with caution since it will make the program

    hard to understand owing to the sudden change of direction#include using namespace std;int main(){ int counter;

    for (counter=0; counter

  • 93

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    while (expr) {statement…continue;statement…

    }

    continue Statement

    do {statement

    …continue;statement…

    } while(expr)skip

    skip

    for (expr1; expr2; expr3) {statement…continue;statement…

    }

    skip

    94

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    while (expr) {statement;…if (expr)break;

    statements;}statement;…

    break Statementswitch (i) {

    case 1:statement_1;

    case 2:statement_2;

    case 3:statement_3;

    break;case 4:

    statement_4;}

    statements;for (expr1; expr2; expr3) {

    statement…if (expr)

    break;statements;

    }statements;

  • 3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    initialize outer loopwhile ( outer loop condition ){ . . .

    initialize inner loopwhile ( inner loop condition ){

    inner loop processing and update} // end inner loop. . .

    } // end outer loop

    Nested Loop

    95

    96

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Nested for loops#include using namespace std;int main(){ int rows, columns;

    char theChar;cout > rows;cout > columns;cout > theChar;for (int i=0; i

  • 97

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Value of i, jValue of i, j

    for (int i=0; i

  • 99

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Exercise 3.4

    For the program on p. 96a. Build the project and note the result. b. Try to rewrite the program using nested while

    loops instead of the nested for loops. Which program is more complicated?

    100

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Functions - Revisit• A function is, in effect, a subprogram that can act on

    data and return a value• When the name of the function is encountered in the

    program, the function is called• When the function returns, execution resumes on the

    next line of the calling function

    Callingfunc(){ Statements;

    funcA();Statements;funcB();Statements;

    }

    funcA(){ Statements;

    return;} funcB()

    { Statements;return;

    }

    Return value is void

    input

    output

  • 101

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Function Body

    unsigned short int FindArea (int length, int width)

    return type function nametype of input parameters

    name of input parameters

    { // Opening braceStatements;

    return (return_value);

    } // Closing brace

    return value

    102

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Why do we need functions?• Functions help us shorten our program by

    re-using the program codes #include using namespace std;void floatDiv(int x, int y){ float a = (float)x;

    float b = static_cast(y);float c = a/b;cout

  • 103

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • The same program will be much longer without function

    • Can be even longer if the same operation is done in other part of the program

    int main(){ int w = 7, x = 5, y = 3, z = 2;float a, b, c;a = (float)w;b = static_cast(x);float c = a/b;cout

  • 105

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Declaring Functions• In C++, anything that is not a part of the C++ language

    needs to be declared• However, a function need NOT be separately declared if

    it is placed before the functions that will call it #include using namespace std;void DemoFunction(){ cout

  • 107

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • Functions are usually declared by either one of the two ways:• Write the prototype of the function at the beginning

    of the file in which the function is used• Put the prototype of the function into a header file

    and include it in the file in which the function is used

    Function PrototypeFunction Prototype

    unsigned short int FindArea(int, int);

    return type function name type of input parameters

    108

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Declaring Functions#include using namespace std;int Area(int length, int width); // function prototypeint main(){ int lengthOfYard;

    int widthOfYard;int areaOfYard;cout > widthOfYard;cout > lengthOfYard;areaOfYard = Area(lengthOfYard,widthOfYard);cout

  • 109

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include #include "area.h" // function prototypeusing namespace std;int main(){ :

    areaOfYard = Area(lengthOfYard,widthOfYard);:return 0;

    }

    int Area(int yardLength, int yardWidth){ return yardLength * yardWidth;}

    int Area(int length, int width); // function prototype

    Assume the file area.h has the following statement and is at the same folder as main()Assume the file area.h has the following statement and is at the same folder as main()

    It is equivalent to place the content of area.h to here

    It is equivalent to place the content of area.h to here

    110

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Function Prototypes in Header file• Advantage: if a particular set of function prototypes is

    often used in different programs, we need not declare them every time they are needed

    • E.g. iostreamContains prototypes of many functions that are related to the manipulation of I/O streamIs needed in most programs that need I/O like cout, cin, etc.Should be included at the beginning of most programs; otherwise, we need to type all prototypesin every program.

    In different .cpp filesOne line of #include

    Vs many lines

  • 111

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Exercise 3.51) For the program on p.102, add the function prototype

    such that we can place the function floatDiv() aftermain().

    2) Modify the program you've developed in 1) as follows:• Remove the function prototype• Prepare a file named floatDiv.h that contains

    just one statement: the function prototype of floatDiv()

    • Store the file floatDiv.h in the same folder as your C++ file

    • Include this header file at the beginning of the program as the example in p.109

    • Achieve the same result as 1).

    112

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    • In C++, there are 3 types of variables that a function may make use of:• Passed parameters and return parameter(s)

    The links between the called function and the calling function

    • Local variable Visible only within a functionFor temporary local storage

    • Global variable Visible to all functions in the programAn old and dangerous way to communicate between functions

    Where do variables locate in your machine?

  • 113

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Variable ScopeLocal variables: variables declared within a functionSuch variables have local scope; they can be used only within the function in which they are declaredGlobal variables: variables declared outside any functionSuch variables have global scope; they can be used by all functions that occur after their declaration

    114

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Variable Scope

    The three storage areas created by a C++ Program.

    Global variable

    Local variable

    Local variable

  • 115

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Local Variables#include using namespace std;

    float Convert(float); //function prototypeint main(){ float TempFer;

    float TempCel = 10;TempFer = 100;TempCel = Convert(TempFer);cout

  • 117

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;float Convert(float);int main(){ float TempFer;

    float Cel = 10;TempFer = 100;Cel=Convert(TempFer);cout

  • 119

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Parameter Passing - by ValueVariables a and x use different memory cells.

    differentcopies

    120

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    samecopy

    Parameter Passing - by ReferenceVariables a and x share the same memory cell.

  • 121

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Global Variables#include using namespace std;int Convert(float); //function prototype changedfloat Cel; // Global variableint main(){ float TempFer;

    cout > TempFer;Convert(TempFer); //No need to collect the return valuecout

  • 123

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Default Parameters• Calling function should pass parameters of exactly the same

    types as those defined in the prototype of the called functionlong myFunction(int); //function prototypeIt means that any function that calls myFunction()should pass an integer to it

    • The only exception is if the function prototype has a default valuelong myFunction(int x=50); //default valueIf the calling function does not provide a parameter, 50 will be automatically used :myFunction( ); myFunction(50);

    124

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int volumeCube(int, int width = 25, int height = 1);int main(){ int length = 100, width = 50, height = 2, volume;

    volume = volumeCube(length, width, height);cout

  • 125

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Overloading Functions• C++ allows overloading of function, i.e. create more than

    one function with the same namee.g. int myFunction (int, int);

    int myFunction (long, long);long myFunction (long);

    When a function calls myFunction(), the compiler checks the number and type of the passed parameters to determine which function should be called

    • Function overloading is also called polymorphism• Poly means many, morph means form

    •A polymorphic function is many-formed

    3 different functions

    Differ by just the return type is NOT allowed

    126

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int intDouble(int);float floatDouble(float);int main(){ int myInt = 6500, doubledInt;

    float myFloat = 0.65, doubledFloat;doubledInt = intDouble(myInt);doubledFloat = floatDouble(myFloat);cout

  • 127

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    #include using namespace std;int Double(int);float Double(float);int main(){ int myInt = 6500, doubledInt;

    float myFloat = 0.65, doubledFloat;doubledInt = Double(myInt);doubledFloat = Double(myFloat);cout

  • 129

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Recursive FunctionExample: factorials: 5! = 5 * 4 * 3 * 2 * 1

    5! = 5 * 4!4! = 4 * 3! …

    – Can compute factorials recursively – Solve base case (1! = 0! = 1) then plug in

    2! = 2 * 1! = 2 * 1 = 2;3! = 3 * 2! = 3 * 2 = 6;

    long factorial(int n){

    if (n == 0)return 1;

    elsereturn n * factorial(n-1);

    }

    ⎩⎨⎧

    >=

    −=

    00

    )!1(

    1!

    nn

    nnn

    130

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Exercise 3.6avoid myFunc(){ int x = 8;

    cout

  • 131

    3. The Nuts and Bolts of C++

    Computer Programming3. The Nuts and Bolts of C++

    Exercise 3.6bA for loop is used instead as follows:

    void myFunc(){

    int x = 8;cout