Lecture Ppt 9

download Lecture Ppt 9

of 43

Transcript of Lecture Ppt 9

  • 8/2/2019 Lecture Ppt 9

    1/43

  • 8/2/2019 Lecture Ppt 9

    2/43

    Conditional Statements (Overview ofConditions)

    Introduction to Conditional Statements if a Condition is True

    Using the Logical Not

    ifelse The Ternary Operator (?:)

  • 8/2/2019 Lecture Ppt 9

    3/43

    When programming, you will ask the computerto check various kinds of situations and to actaccordingly. The computer performs variouscomparisons of various kinds of statements.These statements come either from you or fromthe computer itself, while it is processinginternal assignments.

    Lets imagine you are writing an employmentapplication and one question would be, "Doyou consider yourself a hot-temperedindividual?" The source file of such a programwould look like this:

  • 8/2/2019 Lecture Ppt 9

    4/43

    #include using namespace std;

    int main() { char Answer;

    cout > Answer;

    system(pause); }

  • 8/2/2019 Lecture Ppt 9

    5/43

    Some of the answers a user would type are y, yes, Y,Yes, YES, n, N, no, No, NO, I dont know, Sometimes,Why are you asking?, and What do you mean? Thevariety of these different answers means that you

    should pay attention to how you structure yourprograms, you should be clear to the users. A better version of the line that asks the question

    would be: cout

  • 8/2/2019 Lecture Ppt 9

    6/43

    There are three entities thatparticipate on a trafficlight: the lights, the humanbeings who interact withthe light, and the law. The

    road provides a platformon which thesecomponents cometogether.

    The Traffic Light

    The Drivers

    The Law

  • 8/2/2019 Lecture Ppt 9

    7/43

    The most independent of the three entities is thetraffic light. It does not think, therefore it does notmake mistakes.

    A driver who proceeds through a red light can get a

    ticket depending on one of two circumstances:either a police officer caught him hand-in-the-basket or a special camera took a picture. Worse, ifan accident happens, this becomes another story.

    At one moment in the day, the timer is set at the

    beginning or is reset and the light is green: T = 0. Sincethe timer is working fine, it starts counting the seconds1, 2, 3, 4, 45. The light will stay green from T = 0 to T= 45. When the timer reaches 45, the timer is reset to 0and starts counting from 0 until it reaches 5;meanwhile, Color = Yellow.

  • 8/2/2019 Lecture Ppt 9

    8/43

    In C++, comparisons are made from astatement. Examples of statements are:

    "You are 12 years old" "It is raining outside"

    You live in Sydney"

  • 8/2/2019 Lecture Ppt 9

    9/43

    When a driver comes to a traffic light,the first thing he does is to examine the

    light's color. There are two values thedriver would put together: The currentlight of the traffic and the desired light ofthe traffic.

  • 8/2/2019 Lecture Ppt 9

    10/43

    The comparison using the if statement isused to check whether a condition is

    true or false. The syntax to use it is: if(Condition)Statement;

    If the Condition is true, then the compiler

    would execute the Statement. Thecompiler ignores anything else:

  • 8/2/2019 Lecture Ppt 9

    11/43

  • 8/2/2019 Lecture Ppt 9

    12/43

    If the statement to execute is (very) short,you can write it on the same line with the

    condition that is being checked. Consider a program that is asking a user

    to answer Yes or No to a question suchas "Are you ready to provide your creditcard number?". A source file of such aprogram could look like this:

  • 8/2/2019 Lecture Ppt 9

    13/43

    #include

    using namespace std;

    int main()

    {

    char Answer;

    // Request the availability of a credit card from the user

    cout > Answer;

    // Since the user is ready, let's process the credit card transaction

    if(Answer == '1') cout

  • 8/2/2019 Lecture Ppt 9

    14/43

    #include using namespace std;

    int main() { char Answer; char CreditCardNumber[40];

    // Request the availability of a credit card from the user cout > Answer;

    // Since the user is ready, let's process the credit card transaction if(Answer == '1') { cout CreditCardNumber; }

    cout

  • 8/2/2019 Lecture Ppt 9

    15/43

    When a driver comes to a light that he expects tobe green, we saw that he would use a statementsuch as, "The light is green". If in fact the light is

    green, we saw that the statement would lead to atrue result. If the light is not green, the "The light isgreen" statement produces a false result.

  • 8/2/2019 Lecture Ppt 9

    16/43

    As you may realize already, in Boolean algebra, the result ofperforming a comparison depends on how the Condition isformulated. If the driver is approaching a light that he isexpecting to display any color other than green, he wouldstart from a statement such as "The light is not green". If the

    light IS NOT green, the expression "The light is not green" is true(very important). This is illustrated in the following table:

  • 8/2/2019 Lecture Ppt 9

    17/43

    The "The light is not green" statement is expressed in Booleanalgebra as Not the light is green. Instead of writing Not thelight is green", in C++, using the logical Not operator , youwould formulate the statement as, !"The light is green".Therefore, if P means The light is green, you can express the

    negativity of P as !P. The Boolean table produced is:

  • 8/2/2019 Lecture Ppt 9

    18/43

    When a statement is true, its Boolean value is equivalent to anon-zero integer such as 1. Otherwise, if a statementproduces a false result, it is given a 0 value. Therefore, ourtable would be:

  • 8/2/2019 Lecture Ppt 9

    19/43

    The if condition is used to check onepossibility and ignore anything else. Usually,other conditions should be considered. In

    this case, you can use more than one ifstatement. For example, on a program thatasks a user to answer Yes or No, althoughthe positive answer is the most expected, it

    is important to offer an alternate statementin case the user provides another answer.Here is an example:

  • 8/2/2019 Lecture Ppt 9

    20/43

    #include using namespace std;

    int main()

    {

    char Answer;

    cout > Answer;

    if( Answer == 'y' ) // First Condition

    {

    cout

  • 8/2/2019 Lecture Ppt 9

    21/43

    The problem with the above program is that the second if isnot an alternative to the first, it is just another condition thatthe program has to check and execute after executing thefirst. On that program, if the user provides y as the answer tothe question, the compiler would execute the content of its

    statement and the compiler would execute thesecond if condition.

    You can also ask the compiler to check a condition; if thatcondition is true, the compiler will execute the intendedstatement. Otherwise, the compiler would execute alternate

    statement. This is performed using the syntax: if(Condition)Statement1;

    elseStatement2;

  • 8/2/2019 Lecture Ppt 9

    22/43

  • 8/2/2019 Lecture Ppt 9

    23/43

    #include using namespace std;

    int main() { char Answer;

    cout > Answer;

    if( Answer == 'y' ) // One answer { cout

  • 8/2/2019 Lecture Ppt 9

    24/43

    The conditional operator behaves like asimple ifelse statement. Its syntax is:

    Condition ? Statement1 : Statement2;

    The compiler would first test the Condition. Ifthe Condition is true, then it wouldexecuteStatement1, otherwise it wouldexecute Statement2. When you requesttwo numbers from the user and would liketo compare them, the following programwould do find out which one of bothnumbers is higher. The comparison isperformed using the conditional operator:

  • 8/2/2019 Lecture Ppt 9

    25/43

    #include

    using namespace std;

    int main()

    {

    int Number;

    signed Num1, Num2, Max;

    cout > Num1 >> Num2;

    Max = (Num1 < Num2) ? Num2 : Num1;

    cout

  • 8/2/2019 Lecture Ppt 9

    26/43

    Conditional Statements: ifelse if and

    ifelse ifelse

    The switch Statement Counting and Looping

    The while Statement

    The do...while Statement The for Statement

  • 8/2/2019 Lecture Ppt 9

    27/43

    The previous conditional formula isused to execute one of two

    alternatives. Sometimes, your programwill need to check many more thanthat. The syntax for such a situation is:

    if(Condition1)Statement1;else if(Condition2)Statement2;

  • 8/2/2019 Lecture Ppt 9

    28/43

    if(Condition1)Statement1;

    else if(Condition2)

    Statement2;elseStatement-n;

    if(Condition1)Statement1;

    else if(Condition2)Statement2;

    else if(Condition3)Statement3;

    elseStatement-n;

  • 8/2/2019 Lecture Ppt 9

    29/43

    #include using namespace std;

    int main() { char Answer;

    cout > Answer;

    if( Answer == 'y' ) // Unique Condition { cout

  • 8/2/2019 Lecture Ppt 9

    30/43

    When defining an expression whose result would lead to a specificprogram execution, the switch statement considers that result andexecutes a statement based on the possible outcome of thatexpression, this possible outcome is called a case. The differentoutcomes are listed in the body of the switch statement and each casehas its own execution, if necessary. The body of a switch statement is

    delimited from an opening to a closing curly brackets: { to }. Thesyntax of the switch statement is:

    switch(Expression){

    caseChoice1:Statement1;

    break;

    caseChoice2:Statement2; break;

    caseChoice-n: Statement-n;

    }

  • 8/2/2019 Lecture Ppt 9

    31/43

    #include using namespace std;

    int main() { int Number;

    cout > Number;

    switch (Number) { case 1: cout

  • 8/2/2019 Lecture Ppt 9

    32/43

    When establishing the possible outcomesthat the switch statement should consider,at times there will be other possibilities other

    than those listed and you will be likely toconsider them. This special case is handledby the default keyword. The default casewould be considered if none of the listed

    cases matches the supplied answer. Thesyntax of the switch statement thatconsiders the default case would be:

  • 8/2/2019 Lecture Ppt 9

    33/43

    switch(Expression){

    caseChoice1:Statement1;

    break;

    caseChoice2:Statement2;

    break;

    caseChoice-n:Statement-n;

    break;

    default:Other-Possibility;

    }

  • 8/2/2019 Lecture Ppt 9

    34/43

    The C++ language provides a set ofcontrol statements that allows you to

    conditionally control data input andoutput. These controls are referred to asloops.

  • 8/2/2019 Lecture Ppt 9

    35/43

    The C++ language provides a set ofcontrol statements that allows you toconditionally control data input and

    output. These controls are referred to asloops.

    The while statement examines orevaluates a condition. The syntax ofthe while statement is:

    while(Condition)Statement;

  • 8/2/2019 Lecture Ppt 9

    36/43

  • 8/2/2019 Lecture Ppt 9

    37/43

    #include using namespace std;

    int main() {

    int Number;// = 0;

    while( Number

  • 8/2/2019 Lecture Ppt 9

    38/43

    The while statement examines or evaluates acondition. The syntax of the while statement is:

    while(Condition)Statement;

  • 8/2/2019 Lecture Ppt 9

    39/43

    The dowhile condition executes a Statement first. After thefirst execution of theStatement, it examines the Condition. Ifthe Condition is true, then it executes theStatement again. Itwill keep executing the Statement AS LONG AS

    the Condition is true. Once the Condition becomes false, thelooping (the execution of the Statement) would stop.

    If the Statement is a short one, such as made of one line,simply write it after the do keyword. Like the if and the whilestatements, the Condition being checked must be included

    between parentheses. The whole dowhile statement mustend with a semicolon.

    Another version of the counting program seen previouslywould be:

  • 8/2/2019 Lecture Ppt 9

    40/43

    #include

    using namespace std;

    int main() {

    int Number = 0;

    do

    cout

  • 8/2/2019 Lecture Ppt 9

    41/43

    #include

    using namespace std;

    int main()

    { char SittingDown;

    cout SittingDown;

    }

    while( !(SittingDown == 'y') );

    cout

  • 8/2/2019 Lecture Ppt 9

    42/43

    The for statement is typically used to count a number of items. At its regularstructure, it is divided in three parts. The first section specifies the starting pointfor the count. The second section sets the counting limit. The last sectiondetermines the counting frequency. The syntax of the for statement is:

    for( Start;End;Frequency)Statement;

    #include

    using namespace std;

    int main()

    {

    for(int Count = 0; Count

  • 8/2/2019 Lecture Ppt 9

    43/43

    The C++ compiler recognizes that a variable declared as the counter of a forloop is available only in that for loop. This means the scope of the countingvariable is confined only to the for loop. This allows different for loops to usethe same counter variable. Here is an example

    #include

    using namespace std;

    int main()

    {

    for(int Count = 0; Count