Programming for Engineers 1

download Programming for Engineers 1

of 27

Transcript of Programming for Engineers 1

  • 8/19/2019 Programming for Engineers 1

    1/69

    Programming for EngineersIntroduction to C (Revision) -Control Structures

    Source:Deitel & Deitel. C How To Program.

    Seventh Edition. Pearson Education, Inc. 2013 .

  • 8/19/2019 Programming for Engineers 1

    2/69

    Do not remove this notice.

    Copyright Notice

    COMMONWEALTH OF AUSTRALIACopyright Regulations 1969

    WARNING

    This material has been produced and communicated to you by or onbehalf of the University of South Australia pursuant to Part VB of the

    Copyright Act 1968 (the Act ).

    The material in this communication may be subject to copyright under the Act. Any further reproduction or communication of this material by you

    may be the subject of copyright protection under the Act.

    Do not remove this notice.

  • 8/19/2019 Programming for Engineers 1

    3/69

    Required Reading

    C How to Program, Deitel & DeitelChapter 3:

    Structured Program Development in C3.1 - 3.7, 3.11, 3.12

    Chapter 4:

    C Program Control4.1 – 4.8, 4.10 – 4.12

  • 8/19/2019 Programming for Engineers 1

    4/69

    Random Number GenerationRandom Number Generation

    To generate random numbers (pseudo-random) usethe C Standard Library function called rand().To access the rand() function from the standardlibrary include the following preprocessor directive atthe top of your program:

    #include

    stdlib - contains functions to convert numbers totext and text to numbers, memory allocation, randomnumbers, and other utility functions.

  • 8/19/2019 Programming for Engineers 1

    5/69

    Random Number GenerationRandom Number Generation

    i = rand();

    Generates an integer value between 0 andRAND_MAX (=32767)

    To generate an integer between 1 and n :1 + ( rand() % n )rand() % n returns a number between 0 and n – 1add 1 to make the number between 1 and n.

    To generate an integer between 1 and 10 use:1 + (rand() % 10)

  • 8/19/2019 Programming for Engineers 1

    6/69

    C FunctionsRandom Number Generation

    /* Fig. 5.7: Deitel & Deitel (Modified)Deitel & Deitel. C How To Program. Fifth Edition.Pearson Education, Inc. 2007.

    */#include int main(){

    int i;for (i = 1; i

  • 8/19/2019 Programming for Engineers 1

    7/69

    Random Number GenerationRandom Number Generation

    Computers are not capable of generating truly random numbers. If you run your

    program several times you will notice that the list of numbers generated (and theactions your program takes based on these values) is the same each time.Numbers are not really random – generated from a seed.To change the sequence, you can change the seed. For example:

    unsigned int seed = 12345;srand(seed);

    This seed value gives the random number generator a new starting point.This will generate a different sequence of numbers, however, will still generatethe same sequence every time the program is run.For a different sequence of numbers each run, use the time function whichreturns the time of the day in seconds.

    You only need to do this once at the start of your program .

    #include

    srand(time( NULL ));

  • 8/19/2019 Programming for Engineers 1

    8/69

    Random Number GenerationBlackjack is a popular card game where the goal is to beat the dealer by

    having the higher hand which does not exceed 21. The card game

    translates well into a dice game. Instead of a deck of 52 cards, we will usetwo 11 sided dice in order to have the higher total, or “hand” which does notexceed 21. We implement parts of the game in this lecture.

    Write a program that:Simulates the rolling of two 11-sided dice (the face value on the dieare 1 – 11). Use the rand() function.

    randomNo = 1 + (rand() % 11);

    That is, generate two random numbers between 1-11 and storethem in variables called playerDie1 and playerDie2 .

    Calculate the die total and store in variable called playerTotal .

    Display them to the screen in the following format:Player's hand is: 1 + 4 = 5

  • 8/19/2019 Programming for Engineers 1

    9/69

    Random Number Generation Answer…

    #include #include

    int main() {

    int playerDie1;int playerDie2;

    int playerTotal;

    /* Roll player's hand */playerDie1 = 1 + (rand()%11);playerDie2 = 1 + (rand()%11);

    /* Work out current hand total */playerTotal = playerDie1 + playerDie2;

    /* Display player hand to the screen */printf("\n\nPlayer's hand is: %d + %d = %d", playerDie1, playerDie2, playerTotal);

    return 0;}

  • 8/19/2019 Programming for Engineers 1

    10/69

    Control StructuresControl Structures

    Programs can be written using three control structures(Bohn and Jacopini):

    SequenceStatements are executed one after the other in order.

    Selection (making decisions)C has 3 types of selection structures:

    ifif/elseswitch

    Repetition (doing the same thing over and over)C has 3 types of repetition structures:

    whiledo/while

    for

    statement1;

    statement2;

    statement3;

  • 8/19/2019 Programming for Engineers 1

    11/69

    Equality and Relational OperatorsSelection and repetition structures require comparisons to work (based on alogical condition).

    Equality & Relational operators make those comparisons.Logical operators allow us to combine the comparisons.Equality & Relational Operators

    Used to make decisionsUsed in expressions where a true/false result is required.

    Example of use:if (x == 0) while (x = is greater than or equal to

  • 8/19/2019 Programming for Engineers 1

    12/69

    Logical OperatorsLogical Operators ( && || ! ) – combine comparisons

    Used when either one, or both, of two (or more) conditions mustbe satisfied.

    if (it is 1.00 and I am hungry)have lunch

    x >= 0 && x

  • 8/19/2019 Programming for Engineers 1

    13/69

    Logical Operators! (not) negates the value of the operand. That is, converts true tofalse, and false to true.

    && (and) requires both a and b to be true for the whole expressionto be true. Otherwise, the value of the expression is false.|| (or) requires one of a or b to be true for the whole expression tobe true. The expression is false only when neither a nor b is true.Truth Table. Logical Operators.

    The result of a logical expression is always true or false.True = any non-zero value. False = 0. The following code adds 1 toage if age is not equal to 0.

    if (age)

    age++;

    a b a && b a || b !a0 0 0 0 10 1 0 1 11 0 0 1 01 1 1 1 0

  • 8/19/2019 Programming for Engineers 1

    14/69

    Logical OperatorsCan also store the result of an expression.For example:

    int x = 5;int y = 1;int z = 5;

    int res;

    res = x < y;res = x == z;res = y < x && z < y;res = y < x || y == z;

  • 8/19/2019 Programming for Engineers 1

    15/69

    Logical OperatorsShort Circuit Evaluation

    When evaluating:

    result = cond1 && cond2;If cond1 is false result must be false so cond2 is not

    evaluated.

    Similarly, with:result = cond1 || cond2;

    If cond1 is true result must be true so cond2 is notevaluated.

  • 8/19/2019 Programming for Engineers 1

    16/69

    Conditional OperatorConditional Operator

    Ternary operator. Has the general form:condition ? value1 : value2

    If the condition is true the expression returns value1 , elsereturns value2 .

    z = x > y ? x : y;

    This is equivalent to the statement:

    if (x > y)z = x;

    elsez = y;

  • 8/19/2019 Programming for Engineers 1

    17/69

    Selection StructuresMaking decisions

    So far, we have seen programs that all start at the top and

    execute each statement in order until the end is reached.Execute different sections of code depending on the values ofdata as the program runs.Greater flexibility and therefore more powerful.Let‘s look at ways a program can control the path of execution…

  • 8/19/2019 Programming for Engineers 1

    18/69

    Selection StructuresThe if Selection Structure

    A simple if statement has the following form:

    if (boolean expression) true block

    True

    False

    Next statement

    StatementsCondition

  • 8/19/2019 Programming for Engineers 1

    19/69

    Selection Structures

    If the expression (boolean expression) is true, the statement(s) in

    the true block are executed.If the expression is false, the program jumps immediately to thestatement following the true block.

    If the expression is true execute the statement in the true block.

    if (age >= 18) printf("You can vote");

  • 8/19/2019 Programming for Engineers 1

    20/69

    Selection StructuresCompound Statements

    Statement can be a single statement or a compound statement.Compound statements must be enclosed within { and }.

    if (speed >= 65){

    fine = 10 * (speed - 60);printf("Fine %d", fine);

    }else

    printf("No fine."); IMPORTANT!Indent the statements that are controlled by the condition.

    { Statement }

  • 8/19/2019 Programming for Engineers 1

    21/69

    Selection StructuresThe if/else Selection Structure

    Allows us to execute one set of statements if theexpression is true and a different set if the expression isfalse. An if/else statement has the following form:

    if (boolean expression)true block

    elseelse block

    True

    Next statement

    StatementsStatements

    ConditionFalse

  • 8/19/2019 Programming for Engineers 1

    22/69

    Selection StructuresThe if/else Selection Structure

    For Example:

    if (mark >= 50)printf("Passed");

    else printf("Failed");

  • 8/19/2019 Programming for Engineers 1

    23/69

    Selection StructuresCombining comparisons

    AND operator evaluates true only if both conditions are true - true

    only if temperature is greater than zero and less than 40.

    if (temperature > 0 && temperature < 40)printf("Normal temperature");

    elseprintf("Extreme temperature");

    OR operator evaluates false only if both conditions are false - true ifeither of the conditions are true, that is, if it is raining or highUV.

    raining = 1;highUV = 1;if (raining || highUV)

    printf("Take an umbrella!");

  • 8/19/2019 Programming for Engineers 1

    24/69

    Selection StructuresNested if Statements

    Used to achieve multiple tests.Find the smallest of 3 integers.

    int num1, num2, num3, min;if (num1 < num2)

    if (num1 < num3)

    min = num1;else

    min = num3;else

    if (num2 < num3)min = num2;

    elsemin = num3;

    printf("Minimum: %d", min);

  • 8/19/2019 Programming for Engineers 1

    25/69

    Selection StructuresNesting if statements may be difficult to read.Use linearly nested if statements to test against manyvalues.

    if (mark >= 85)printf ("HD");

    else if (mark >= 75)printf ("D");

    else if (mark >= 65)printf ("C");

    else if (mark >= 55)printf ("P1");

    else if (mark >= 50)printf ("P2");else if (mark >= 40)

    printf ("F1");else

    printf ("F2");

  • 8/19/2019 Programming for Engineers 1

    26/69

    Selection StructuresLet‘s revisit our ‗Blackjack‘ program…

    Include code that checks the player‘s hand for 21(Blackjack) on the first roll.

    If the player has Blackjack, display ‗ Blackjack! PlayerWins! ‘ to the screen.

    Otherwise, if the player does not have Blackjack, display ‗ Playout player's hand… ‘ to the screen.

  • 8/19/2019 Programming for Engineers 1

    27/69

    Selection Structures Answer…

    #include #include

    int main() {int playerDie1;int playerDie2;int playerTotal;

    /* Roll player's hand */playerDie1 = 1 + (rand()%11);

    playerDie2 = 1 + (rand()%11);

    /* Work out current hand total */playerTotal = playerDie1 + playerDie2;

    /* Display player hand to the screen */printf("\n\nPlayer's hand is: %d + %d = %d", playerDie1, playerDie2, playerTotal);

    if (playerTotal == 21) {printf("Blackjack! Player wins!");

    }else {

    printf("Play out player's hand...");}

    return 0;}

  • 8/19/2019 Programming for Engineers 1

    28/69

    Selection StructuresThe switch Selection Structure

    = 1 = 2 = 3 = 4

    st1; st2; st3; st4;

    break;break; break; break;

    x = ?

  • 8/19/2019 Programming for Engineers 1

    29/69

    Selection StructuresThe switch Selection Structure

    The syntax for switch is:

    switch(expression){case label 1 : body 1

    case label 2 : body 2:case label n : body ndefault : default body

    }

  • 8/19/2019 Programming for Engineers 1

    30/69

    Selection StructuresThe switch Selection Structure

    char idChar;

    int aCount= 0, bCcount = 0, cCount = 0;switch (idChar){

    case 'A':aCount = aCount + 1;break;

    case 'B':bCount = bCount + 1;break;

    case 'C':cCount = cCount + 1;break;

    default: /* Optional */printf("Error");

    }Omitting break would cause the next action to be executed.

  • 8/19/2019 Programming for Engineers 1

    31/69

    Control StructuresLoops are used when you need to repeat a setof instructions multiple times.C supports three different types of loops:

    for loopwhile loop

    do/while loopfor loop

    Good choice when you know how many times youneed to repeat the loop.

    while loopGood choice when you need to keep repeating theinstructions until a criteria is met.

  • 8/19/2019 Programming for Engineers 1

    32/69

    Control Structures: while loopThe while repetition structure.

    A while loop has the following form:

    while ( boolean expression ) {statements

    }

    As long as the boolen expression is true, the while block isexecuted.

    If the boolean expression is or becomes false, the loopterminates.Reuse common code by returning to a point in the program andexecuting a block of code as many times as we need.The program will loop back until the condition on the while line is

    false. Each pass is called an iteration.

  • 8/19/2019 Programming for Engineers 1

    33/69

    Control Structures: while loop An example:

    int a = 0;

    while (a < 10) {printf("%d\n", a);a = a + 1;

    }

    l l

  • 8/19/2019 Programming for Engineers 1

    34/69

    Control Structures: while loopStatements in the loop body are executed as long as theboolean expression is true.

    A while statement is usually preceded by initialisation. A statement within the loop must eventually change thecondition.

    int a = 0;

    while (a < 10) {printf("%d\n", a);a = a + 1;

    }

    C l S l

  • 8/19/2019 Programming for Engineers 1

    35/69

    Control Structures: while loop

    What is the output produced by the following code?

    int a = 0; /* initialise loop control */while (a < 3) { /* test loop control */

    printf("going loopy %d\n", a);a = a + 1; /* update loop control */

    }

    printf("yee ha!");

    C l S h l l

  • 8/19/2019 Programming for Engineers 1

    36/69

    Control Structures: while loop

    What is the output produced by the following code?

    int a = 3;

    while (a >= 0) {printf("In while loop %d\n", a);a -= 1; a = a – 1;

    }

    printf("The end!");

    C l S hil l

  • 8/19/2019 Programming for Engineers 1

    37/69

    Control Structures: while loop An example – while loop:

    To compute the sum of the first 100 integers:1 + 2 + 3 + … + 100

    int sum = 0;int number = 1;

    while (number

  • 8/19/2019 Programming for Engineers 1

    38/69

    Processing Input A while loop is commonly used to process input. Use a while loop to repeat a set of commands until

    a condition is met.When reading input, your loops should take thefollowing form (algorithm).

    prompt user for data /* initialise loop control */read data

    WHILE (value read in is OK) /* test loop control */perform the processing

    prompt user for data /* update loop control */read data

    P i I

  • 8/19/2019 Programming for Engineers 1

    39/69

    Processing Input An example (read and sum numbers until the user enters a negativenumber):#include

    int main(){

    int no;int total = 0;

    /* initialise loop control */ printf("Please enter a number (-1 to quit): ");

    scanf("%d", &no);

    /* test loop control */ while (no >= 0) {

    printf("Number is: %d\n", no);total = total + no;

    /* update loop control */ printf("Please enter a number ( -1 to quit): ");

    scanf("%d", &no);

    }

    printf("\nSum of all numbers entered is: %d\n\n", total);

    return 0;}

    P i I

  • 8/19/2019 Programming for Engineers 1

    40/69

    Processing Input An example (read and display menu commands until the user enters'q' to quit):#include

    int main(){

    char choice;

    /* initialise loop control */ printf("Please enter [a, b, c or q to quit]: ");

    scanf("%c", &choice);

    /* test loop control */ while (choice != 'q') {

    printf("Choice entered was: %c\n", choice);

    /* update loop control */

    printf("Please enter [a, b, c or q to quit]: ");scanf(" %c", &choice);

    }

    printf("\nThanks - we\'re done here!\n\n");

    return 0;

    }

    P i I

  • 8/19/2019 Programming for Engineers 1

    41/69

    Processing InputLet‘s revisit our ‗Blackjack‘ program… now let‘s include code to play

    out the player‘s hand…

    Prompt for and read whether the player would like to hit (‗h‘) or stand(‗s‘). Implement a loop which continues to simulate one die beingrolled until the user enters stand (‗s‘). Display the value of die 1, die 2 and the total roll value as seen

    below:Player's hand is: 6 + 7 = 13

    Play out player's hand...

    Please enter h or s (h = Hit, s = Stand): hPlayer's hand is: 13 + 5 = 18

    Please enter h or s (h = Hit, s = Stand): s

    Thanks for playing!

    P i I

  • 8/19/2019 Programming for Engineers 1

    42/69

    Processing InputLet‘s revisit our ‗Blackjack‘ program…

    It does not make sense to continue rolling when the player busts(exceeds 21).Modify the loop developed in the previous stage so that it also stopslooping if the player busts (exceeds 21).

    Player's hand is: 9 + 5 = 14

    Play out player's hand...

    Please enter h or s (h = Hit, s = Stand): hPlayer's hand is: 14 + 1 = 15

    Please enter h or s (h = Hit, s = Stand): hPlayer's hand is: 15 + 10 = 25

    Player busts!

    Thanks for playing!

    P i I t

  • 8/19/2019 Programming for Engineers 1

    43/69

    Processing Input Answer…

    #include #include

    int main() {

    int playerDie1;int playerDie2;int playerTotal;char play;

    /* Roll player's hand */playerDie1 = 1 + (rand()%11);playerDie2 = 1 + (rand()%11);

    /* Work out current hand total */playerTotal = playerDie1 + playerDie2;

    /* Display player hand to the screen */printf("\n\nPlayer's hand is: %d + %d = %d", playerDie1, playerDie2, playerTotal);

    :::

    P i I t

  • 8/19/2019 Programming for Engineers 1

    44/69

    Processing Input:if (playerTotal == 21) {

    printf("Blackjack! Player wins!");}else {

    printf("Play out player's hand...");

    printf("\nPlease enter h or s (h = Hit, s = Stand): ");scanf(" %c", &play);

    while (playerTotal < 21 && play == 'h') {

    /* Roll again (one die only) */

    playerDie1 = 1 + (rand()%11);

    /* Display the player's hand to the screen */ printf("Player's hand is: %d + %d = %d\n", playerTotal, playerDie1, (playerTotal+playerDie1));

    playerTotal = playerTotal + playerDie1;

    /* Prompt again only if player has not busted (i.e. hand total has not exceeded 21). */if (playerTotal < 21) {

    printf("\nPlease enter h or s (h = Hit, s = Stand): ");

    scanf(" %c", &play);}

    }}

    printf("\nThanks for playing!\n");

    return 0;

    }

    P i g I t

  • 8/19/2019 Programming for Engineers 1

    45/69

    Processing Input A note on reading characters (please keep this in mind whenundertaking practical and assignment work) :

    The scanf function behaves differently when the %c format specifier isused from when the %d conversion specifier is used. When the %d conversion specifier is used, white space characters (blanks, tabs ornewlines, etc) are skipped until an integer is found. However, when the%c conversion specifier is used, white space is not skipped, the nextcharacter, white space or not, is read.

    You may find that this causes your loops to 'skip' the prompt and notprovide you with an opportunity to enter a character at the prompt.To fix this, leave a space before the %c as seen in the following scanf statement.

    scanf(" %c", &response);

    P i g I t

  • 8/19/2019 Programming for Engineers 1

    46/69

    Processing Input A note on reading characters… continued…

    #include

    int main() {char playAgain = 'y';

    while (playAgain == 'y') {

    printf("\n\nDo stuff... : )\n\n");

    /* space before %c skips white-space characterssuch as newline */

    printf("Play again [y|n]? ");scanf( " %c" , &playAgain);

    }

    return 0;

    }

    Processing Input

  • 8/19/2019 Programming for Engineers 1

    47/69

    Processing Input Another common use for a while loop is error checking of user input. A program that generates a random number between 1-10, asks the user to guess thenumber.

    int main() {int randomNo; /* Random number 1 - 10 */int guess; /* User's guess */

    /* Generate a random number 1 - 10 */randomNo = 1 + (rand() % 10);printf("\nRandom number is: %d\n", randomNo);

    /* Prompt for and read user's guess */

    printf("\nPlease enter your guess: ");scanf("%d", &guess);

    /* check to confirm that guess is in correct range – test loop control */ while (guess < 1 || guess > 10) {

    printf("Input must be between 1 - 10 inclusive.\n");

    /* update loop control */ printf("\nPlease enter your guess: ");

    scanf("%d", &guess);}

    /* Determine whether user guessed correctly */if (guess == randomNo)

    printf("\nWell done - you guessed it!\n");else

    printf("\nToo bad - better luck next time!\n");

    return 0;}

    Processing Input

  • 8/19/2019 Programming for Engineers 1

    48/69

    Processing Input Another common use for a while loop is error checking of user input. A program that reads and displays menu commands until the user enters 'q' to quit.

    printf("Please enter [a, b, c or q to quit]: ");scanf("%c", &choice);

    /* check to confirm that user enters either 'a', 'b', 'c' or 'q' */ while (choice != 'a' && choice != 'b' && choice != 'c' && choice != 'q') {

    printf("\nInput must be a, b, c or q to quit!\nPlease try again...\n\n");

    printf("Please enter [a, b, c or q to quit]: ");scanf(" %c", &choice);

    }

    while (choice != 'q') {printf("Choice entered was: %c\n", choice);

    printf("Please enter [a, b, c or q to quit]: ");scanf(" %c", &choice);

    /* check to confirm that user enters either 'a', 'b', 'c' or 'q' */ while (choice != 'a' && choice != 'b' && choice != 'c' && choice != 'q') {

    printf("\nInput must be a, b, c or q to quit!\nPlease try again...\n\n");

    printf("Please enter [a, b, c or q to quit]: ");scanf(" %c", &choice);

    }

    }printf("\nThanks - we\'re done here!\n\n");return 0;

    }

    Control Structures: do/while loop

  • 8/19/2019 Programming for Engineers 1

    49/69

    Control Structures: do/while loopThe do /while repetition structure

    The condition is tested after the loop so the statements are

    executed at least once (whereas a while loop can be a 'zerotrip').

    int product = 1;int number = 2;

    do { product *= number; number += 2;

    } while (product

  • 8/19/2019 Programming for Engineers 1

    50/69

    Control Structures: for loopUse a for loop when a variable runs from a starting to an endingvalue with a constant increment or decrement.

    The loop executes a known or fixed number of times.The header of a for loop usually contains:

    An initialisation statement of the loop control.Executed before the condition is evaluated (or the bodyexecuted).

    A boolean expression.Evaluated before the loop body is executed.

    A increment or decrement statement.Updates the loop control, executed after the loop body.

    The variable should be int , not float not double.

    Control Structures: for loop

  • 8/19/2019 Programming for Engineers 1

    51/69

    Control Structures: for loopThe for repetition structure.

    Use a for loop when number of iterations is known in advance.

    A for loop has the following form:

    for (initialise; boolean expression; increment){statements

    }

    As long as the boolen expression is true, the for block isexecuted.If the boolean expression is or becomes false, the loopterminates.

    Control Structures: for loop

  • 8/19/2019 Programming for Engineers 1

    52/69

    Control Structures: for loop An example:

    int a;

    for (a = 0; a < 10; a++) {printf("%d\n", a);

    }

    Control Structures: for loop

  • 8/19/2019 Programming for Engineers 1

    53/69

    Control Structures: for loop

    What is the output produced by the following code?

    int a;

    for (a = 0; a < 3; a++) {printf("going loopy %d\n", a);}

    printf("yee ha!");

    Control Structures: for loop

  • 8/19/2019 Programming for Engineers 1

    54/69

    Control Structures: for loop

    What is the output produced by the following code?

    int a;

    for (a = 3; a >= 0; a--) {printf("In for loop %d\n", a);}

    printf("The end!");

    Control Structures: for loop

  • 8/19/2019 Programming for Engineers 1

    55/69

    Control Structures: for loopIn most cases, the for statement can be represented withan equivalent while statement:

    An example – for loop: To compute the sum of the first 100 integers:1 + 2 + 3 + … + 100

    int sum = 0;int number;

    for (number = 1; number

  • 8/19/2019 Programming for Engineers 1

    56/69

    Control Structures: for loopDesign:

    Use for loops if you know exactly how many times a loop needs toexecute.

    int main() {int i;int years;

    printf("How many years? ");scanf("%d", &years);

    for (i = 0; i < years; i++) {

    printf("In the years loop!\n");}return 0;

    }

    Use while loops if you don‘t know how many times a loop needs toexecute.

    int main() {char playAgain = 'y';

    while (playAgain == 'y') {printf("In the play again loop!\n");

    printf("Play Again? ");scanf(" %c", &playAgain);

    }return 0;

    }

    Control Structures: for loop

  • 8/19/2019 Programming for Engineers 1

    57/69

    Control Structures: for loopWrite a program that asks the user to enter a numberbetween 1 and 10. Use a for loop to display a line

    containing that number of adjacent asterisks.For example, if your program reads the number seven, itshould print *******

    Control Structures

  • 8/19/2019 Programming for Engineers 1

    58/69

    Control Structures

    EndIntroduction to C (revision) –

    Control Structures

  • 8/19/2019 Programming for Engineers 1

    59/69

    Looking forward to C++...

    Deitel & Deitel. C How to Program. Fifth Edition. Pearson Education, Inc. 2007.

    Chapter 18: C++ as a Better C; Introducing Object Technology18.1 – 18.11

    Chapter 19: Introduction to Classes and Objects19.1 – 19.11

    Chapter 20: Classes: A Deeper Look, Part 1

    20.1 – 20.8Chapter 21: Classes: A Deeper Look, Part 2

    21.6

    Introduction to C++

  • 8/19/2019 Programming for Engineers 1

    60/69

    Introduction to C++

    Developed by Bjarne Stroustrup at Bell Laboratories.The name C++ includes C‘s increment operator(++) toindicate that C++ is an enhanced version of C.Provides object-oriented programming capabilities.

    C++ standard document – ―Programming languages—C++‖ - ISO/IEC 14882-2011

    Can use a C++ compiler to compile C programs.

    C++ Program: Adding Two Integers

  • 8/19/2019 Programming for Engineers 1

    61/69

    // Addition Program: Deitel & Deitel; C How to Program// Deitel & Deitel. C How To Program. Fifth Edition. Pearson Education, Inc. 2007 .

    #include using namespace std;

    int main() {

    int number1;

    cout > number1;

    // declaration int number2;int sum;

    cout > number2;sum = number1 + number2;cout

  • 8/19/2019 Programming for Engineers 1

    62/69

    Comments

    C++ allows 2 types of comment delimiters:The C delimiters (/* and */).The C++ double slash (//) which provides a commentfrom the double slash to the end of the current line.

    The C++ Preprocessor

    The preprocessor directive:

    #include Include contents of input/output stream header file.Allows the use of cout and cin

    The Main Function

  • 8/19/2019 Programming for Engineers 1

    63/69

    The Main Function

    As in C, programs must have exactly one mainfunction.

    int main ()

    In C, return-value-type is not necessary.In C++, return-value-type is necessary for allfunctions.If not specified, the compiler will generate anerror.

    Identifiers

  • 8/19/2019 Programming for Engineers 1

    64/69

    Identifiers

    C++ identifiers are the same as in C.

    Defining VariablesC++ definitions are the same as in C.However,

    In C, variable definitions must be before executablestatements.In C++, variable definitions placed almost anywhere insidea block.

    Keywords

  • 8/19/2019 Programming for Engineers 1

    65/69

    KeywordsC++ keywords

    Keywords common to the C and C++ programming languages

    auto break case char constcontinue default do double else

    enum extern float for goto

    if int long register return

    short signed sizeof static struct

    switch typedef union unsigned void

    volatile while

    C++ keywords

    C++-only keywords

    and and eq asm bitand bitorbool catch class compl const cast

    delete dynamic cast explicit export false

    friend inline mutable namespace new

    not not eq operator or or eq

    private protected public reinterpret cast static cast

    template this throw true try

    typeid typename using virtual wchar t

    xor xor eq

    (C) Copyright 1992-2007 by Deitel & Associates, Inc. and Pearson Education, Inc. All Rights Reserved.

    Basic Data Types

  • 8/19/2019 Programming for Engineers 1

    66/69

    Basic Data Types

    The basic data types common to C & C++ are:char - an 8-bit characterint - an integerfloat - single precision floating pointdouble - double precision floating point

    C++ only basic data types:wchar_t - a wide (16 bit) characterbool - boolean

    - evaluates to the constants true orfalse .

    Operators

  • 8/19/2019 Programming for Engineers 1

    67/69

    Operators

    C++ operators are the same as in C.

    C does not have a boolean data type.FALSE is represented by zeroTRUE is represented by any non-zero integer.

    Relational, logical and conditional operators evaluate to TRUE(non-zero integer) or FALSE (zero).

    C++ has a bool data type which evaluates to the

    constants true or false (keywords).Can be initialised using integers, a non-zero value will convert totrue and a zero integer will convert to false .Relational, logical and conditional operators evaluate to true orfalse .

    Operators continued…

  • 8/19/2019 Programming for Engineers 1

    68/69

    Operators continued…

    Scope Resolution Operator (::)

    Unique to C++.Provides access to variables that otherwise would bemasked within the current scope. For example:

    int num = 100;class AccumulateNum{

    int num;public:

    void setNum(int);void printNum();

    };

    void AccumulateNum::printNum(){

    cout

  • 8/19/2019 Programming for Engineers 1

    69/69

    Control Structures

    C++ control structures are the same as in C.

    C++ allows declarations mixed with statements.Define a control variable in the for loop. E.g:

    for ( int i = 0 ; i < 100; i++){ // i exists in this block}// i is unknown

    Control variable can be used only in the body of thefor structure.Control variable value is unknown outside the forbody