Lesson Number

Creating Expressions

 

Counting and Looping

The while Statement

The C++ language provides a set of control statements that allows you to conditionally control data input and output. These controls are referred to as loops.

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

while(Condition) Statement;

 

To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement. After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep executing the Statement. When or once the Condition becomes false, it exits the loop.

Here is an example:

    int Number = 0;
	
    while( Number <= 12 )
    {
        Console::WriteLine("Number {0}", __box(Number));
        Number++;
    }

To effectively execute a while statement, you should make sure you provide a mechanism for the compiler to get a reference value for the condition, variable, or expression being checked. This is sometimes in the form of a variable being initialized although it could be some other expression. Such a while condition could be illustrated as follows:

An example would be:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int Number = 0;
	
    while( Number <= 12 )
    {
	Console::WriteLine("Number {0}", __box(Number));
         Number++;
    }

    Console::WriteLine();
    return 0;
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10
Number 11
Number 12

Press any key to continue

The do...while Statement

The do…while statement uses the following syntax:

do Statement while (Condition);

The do…while condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (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 while statements, the Condition being checked must be included between parentheses. The whole do…while statement must end with a semicolon.

Another version of the counting program seen previously would be:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int number = 0;
	
    do
        Console::WriteLine("Number {0}", __box(number++));
    while( number <= 12 );

    Console::WriteLine();
    return 0;
}

If the Statement is long and should span more than one line, start it with an opening curly bracket and end it with a closing curly bracket.

The do…while statement can be used to insist on getting a specific value from the user. For example, since our ergonomic program would like the user to sit down for the subsequent exercise, you can modify your program to continue only once she is sitting down. Here is an example on how you would accomplish that:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char sittingDown;
	
    Console::WriteLine("For the next exercise, you need to be sitting down");
    do {
        Console::Write("Are you sitting down now(y/n)? ");
        cin >> sittingDown;
    } while( !(sittingDown == 'y') );
	
    Console::WriteLine("\nWonderful!!!");

    Console::WriteLine();
    return 0;
}
Here is an example of running the program:
For the next exercise, you need to be sitting down
Are you sitting down now(y/n)? g
Are you sitting down now(y/n)? h
Are you sitting down now(y/n)? n
Are you sitting down now(y/n)? y

Wonderful!!!

Press any key to continue

The for Statement

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

for( Start; End; Frequency) Statement;

The Start expression is a variable assigned the starting value. This could be Count = 0;

The End expression sets the criteria for ending the counting. An example would be Count < 24; this means the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting.

The Frequency expression would let the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count.

Here is an example that applies the for statement:

#using <mscorlib.dll>
using namespace System;

int main()
{
    for(int Count = 0; Count <= 12; Count++)
	Console::WriteLine("Number {0}", __box(Count));
    
    Console::WriteLine();
    return 0;
}

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

#using <mscorlib.dll>
using namespace System;

int main()
{
    for(int Count = 0; Count <= 12; Count++)
	Console::WriteLine("Number {0}", __box(Count));
	
    Console::WriteLine();

    for(int Count = 10; Count >= 2; Count--)
	Console::WriteLine("Number {0}", _box(Count));

    Console::WriteLine();
    return 0;
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10
Number 11
Number 12

Number 10
Number 9
Number 8
Number 7
Number 6
Number 5
Number 4
Number 3
Number 2

Press any key to continue

 

Combining Statements

 

Introduction

There are techniques you can use to combine conditional statements when one of them cannot fully implement the desired behavior.

We will continue with our traffic light analogy.

Nesting Conditions

A condition can be created inside of another to write a more effective statement. This is referred to as nesting conditions. Almost any condition can be part of another and multiple conditions can be included inside of others.

As we have learned, different conditional statements are applied in specific circumstances. In some situations, they are interchangeable or one can be applied just like another, which becomes a matter of choice. Statements can be combined to render a better result with each playing an appropriate role.

To continue with our ergonomic program, imagine that you would really like the user to sit down and your program would continue only once she answers that she is sitting down, you can use the do…while statement to wait for the user to sit down; but as the do…while is checking the condition, you can insert an if statement to enforce your request. Here is an example of how you can do it:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char sittingDown;
	
    Console::WriteLine("For the next exercise, you need to be sitting down");
    do {
        Console::Write("Are you sitting down now(y/n)? ");
        cin >> sittingDown;

        if( sittingDown != 'y' )
            Console::WriteLine("\nCould you please sit down for the next exercise?");
    } while( !(sittingDown == 'y') );
	
    Console::WriteLine("\nWonderful!!!");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Are you sitting down now(y/n)? n
Could you please sit down for the next exercise?

Are you sitting down now(y/n)? n
Could you please sit down for the next exercise?

Are you sitting down now(y/n)? y

Wonderful!!!

Press any key to continue...

One of the reasons you would need to nest conditions is because one would lead to another. Sometimes, before checking one condition, another primary condition would have to be met. The ergonomic program we have been simulating so far is asking the user whether she is sitting down. Once the user is sitting down, you would write an exercise she would perform. Depending on her strength, at a certain time, one user will be tired and want to stop while for the same amount of previous exercises, another user would like to continue. Before continuing with a subsequent exercise, you may want to check whether the user would like to continue. Of course, this would be easily done with:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char sittingDown;
	
    Console::WriteLine("For the next exercise, you need to be sitting down");
    do {
        Console::Write("Are you sitting down now(y/n)? ");
        cin >> sittingDown;

        if( sittingDown != 'y' )
            Console::WriteLine("\nCould you please sit down for the next exercise?");
    } while( !(sittingDown == 'y') );
	
    Console::WriteLine("\nWonderful. Now we will continue today's exercise...");
    Console::WriteLine("...End of exercise");

    char wantToContinue;

    Console::Write("\nDo you want to continue(y=Yes/n=No)? ");
    cin >> wantToContinue;

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Are you sitting down now(y/n)? w

Could you please sit down for the next exercise?
Are you sitting down now(y/n)? k

Could you please sit down for the next exercise?
Are you sitting down now(y/n)? y

Wonderful. Now we will continue today's exercise...
...End of exercise

Do you want to continue(y=Yes/n=No)? n

Press any key to continue

If the user answers No, you can stop the program. If she answers Yes, you would need to continue the program with another exercise. Because the user answered Yes, the subsequent exercise would be included in the previous condition because it does not apply for a user who wants to stop. In this case, one “if” could be inserted inside of another. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char sittingDown;
	
    Console::WriteLine("For the next exercise, you need to be sitting down");
    do {
        Console::Write("Are you sitting down now(y/n)? ");
        cin >> sittingDown;

        if( sittingDown != 'y' )
            Console::WriteLine("\nCould you please sit down for the next exercise?");
    } while( !(sittingDown == 'y') );
	
    Console::WriteLine("\nWonderful. Now we will continue today's exercise...");
    Console::WriteLine("...End of exercise");

    char wantToContinue;

    Console::Write("\nDo you want to continue(y=Yes/n=No)? ");
    cin >> wantToContinue;
	
    if(wantToContinue == 'y')
    {
        char layOnBack;

        Console::WriteLine("Good. For the next exercise, you should lay on your back");
        Console::Write("Are you laying on your back(y=Yes/n=No)? ");
        cin >> layOnBack;

        if(layOnBack == 'y')
            Console::WriteLine("\nGreat.Now we will start the next exercise.");
        else
            Console::WriteLine("\nWell, it looks like you are getting tired...");
    }
    else
        Console::WriteLine("We had enough today");

    Console::WriteLine("We will stop the session nowThanks.");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Are you sitting down now(y/n)? d

Could you please sit down for the next exercise?
Are you sitting down now(y/n)? p

Could you please sit down for the next exercise?
Are you sitting down now(y/n)? y

Wonderful. Now we will continue today's exercise...
...End of exercise

Do you want to continue(1=Yes/0=No)? 8
We had enough today
We will stop the session nowThanks.

Press any key to continue

In the same way, you can nest statements as you see fit. The goal is to provide an efficient and friendly application. You can insert and nest statements that provide valuable feedback to the user while minimizing boredom.

 

The break Statement

The break statement is used to stop a loop for any reason or condition the programmer sees considers fit. The break statement can be used in a while condition to stop an ongoing action. The syntax of the break statement is simply:

break;

Although made of only one word, the break statement is a complete statement; therefore, it can (and should always) stay on its own line (this makes the program easy to read).

The break statement applies to the most previous conditional statement to it; provided that previous statement is applicable.

Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
    int number = 2;

    while( number <= 8 )
    {
        Console::WriteLine("Number {0}", __box(number));
        break;
    }

    Console::WriteLine();
    return 0;
}

The break statement can also be used in a do…while or a for loop the same way.

The break statement is typically used to handle the cases in a switch statement. We saw earlier that all cases in a switch would execute starting where a valid statement is found.

Consider the program we used earlier to request a number from 1 to 3, a better version that involves a break in each case would allow the switch to stop once the right case is found. Here is a new version of that program:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int number;
	
    Console::Write("Type a number between 1 and 3: ");
    cin >> number;
	
    switch (number)
    {
    case 1:
        Console::WriteLine("You typed 1");
        break;
    case 2:
        Console::WriteLine("You typed 2");
        break;
    case 3:
        Console::WriteLine("You typed 3");
        break;
    }

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Type a number between 1 and 3: 2
You typed 2

Press any key to continue

Even when using the break statement, the switch allows many case to execute as one. To do this, as we saw when not using the break, type two cases together. This technique is useful when validating letters because the letters could be in uppercase or lowercase. This illustrated in the following program:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char letter;

    Console::Write("Type a letter: ");
    cin >> letter;

    switch( letter )
    {
    case 'a':
    case 'A':
    case 'e':
    case 'E':
    case 'i':
    case 'I':
    case 'o':
    case 'O':
    case 'u':
    case 'U':
	Console::Write("The letter you typed, ");
	Console::Write(__box(letter));
	Console::WriteLine(", is a vowel");
        break;

    case 'b':case 'c':case 'd':case 'f':case 'g':case 'h':case 'j':
    case 'k':case 'l':case 'm':case 'n':case 'p':case 'q':case 'r':
    case 's':case 't':case 'v':case 'w':case 'x':case 'y':case 'z':
	Console::Write(__box(letter));
	Console::WriteLine(" is a lowercase consonant");
        break;

    case 'B':case 'C':case 'D':case 'F':case 'G':case 'H':case 'J':
    case 'K':case 'L':case 'M':case 'N':case 'P':case 'Q':case 'R':
    case 'S':case 'T':case 'V':case 'W':case 'X':case 'Y':case 'Z':
	Console::Write(__box(letter));
	Console::WriteLine(" is a consonant in uppercase");
        break;

    default:
	Console::Write("The symbol ");
	Console::Write(__box(letter));
	Console::WriteLine(" is not an alphabetical letter");
    }

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Type a letter: h
h is a lowercase consonant

Press any key to continue

The switch statement is also used with an enumerator that controls cases. This is also a good place to use the break statement to decide which case applies. An advantage of using an enumerator is its ability to be more explicit than a regular integer.

To use an enumerator, define it and list each one of its members for the case that applies. Remember that, by default, the members of an enumerator are counted with the first member having a value of 0, the second is 1, etc. Here is an example of a switch statement that uses an enumerator.

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

enum EmploymentStatus { esFullTime=1, esPartTime, esContractor, esNS };

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int emplStatus;

    Console::WriteLine("Employee's Contract Status: ");
    Console::WriteLine("1 - Full Time  | 2 - Part Time");
    Console::WriteLine("3 - Contractor | 4 - Other");
    Console::Write("Status: ");
    cin >> emplStatus;

    Console::WriteLine();

    switch( emplStatus )
    {
    case esFullTime:
        Console::WriteLine("Employment Status: Full Time");
		Console::WriteLine("Employee's Benefits:");
		Console::WriteLine("\tMedical Insurance");
        Console::WriteLine("\tSick Leave");
        Console::WriteLine("\tMaternal Leave");
        Console::WriteLine("\tVacation Time");
        Console::WriteLine("\t401K");
        break;

    case esPartTime:
        Console::WriteLine("Employment Status: Part Time");
        Console::WriteLine("Employee's Benefits:");
		Console::WriteLine("\tSick Leave");
        Console::WriteLine("\tMaternal Leave");
        break;

    case esContractor:
        Console::WriteLine("Employment Status: Contractor");
        Console::WriteLine("Employee's Benefits: None");
        break;

    case esNS:
        Console::WriteLine("Employment Status: Other");
        Console::WriteLine("Status Not Specified");
        break;

    default:
        Console::WriteLine("Unknown Status");
    }

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Employee's Contract Status:
0 - Full Time  | 1 - Part Time
2 - Contractor | 3 - Other
Status: 2

Employment Status: Contractor
Employee's Benefits: None

Press any key to continue
 

The continue Statement

The continue statement uses the following syntax:

continue;

When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, do…while or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line.

The following programs asks the user to type 4 positive numbers and calculates the sum of the numbers by considering only the positive ones. If the user types a negative number, the program manages to ignore the numbers that do not fit in the specified category:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    // Declare necessary variables
    int posNumber, sum = 0;

    // Request 4 positive numbers from the user
    Console::WriteLine("Type 4 positive numbers.");
    // Make sure the user types 4 positive numbers
    for( int Count = 1; Count <= 4; Count++ )
    {
        Console::Write("Number: ");
        cin >> posNumber;

        // If the number typed is not positive, ignore it
        if( posNumber < 0 )
            continue;

        // Add each number to the sum
        sum += posNumber;
    }

    // Display the sum
    Console::WriteLine("Sum of the positive numbers you entered = {0}", __box(sum));


    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Type 4 positive numbers.
Number: 242
Number: -5
Number: 88
Number: -3784
Sum of the numbers you entered = 330

Press any key to continue

The goto Statement

The goto statement allows a program execution to jump to another section of the function in which it is being used.

In order to use the goto statement, insert a name on a particular section of your function so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have learned about C++ names (the name can be anything), then followed by a colon. The following program uses a for loop to count from 0 to 12, but when it encounters 5, it jumps to a designated section of the program:

#using <mscorlib.dll>
using namespace System;

int main()
{
    Console::WriteLine("We need to count from 0 to 12");
    for(int Count = 0; Count <= 12; ++Count)
    {
	Console::WriteLine("Count {0}", __box(Count));

        if( Count == 5 )
            goto MamaMia;
    }

MamaMia:
    Console::WriteLine("Stopped at 5");

    Console::WriteLine();
    return 0;
}
This would produce:
We need to count from 0 to 12
Count 0
Count 1
Count 2
Count 3
Count 4
Count 5
Stopped at 5

Press any key to continue

Logical Conjunction and Disjunction

 

Introduction

The conditional Statements we have used so far were applied to single situations. You can combine statements using techniques of logical thinking to create more complex and complete expressions. One way to do this is by making sure that two conditions are met for the whole expression to be true. On the other hand, one or the other of two conditions can produce a true condition, as long as one of them is true. This is done with logical conjunction or disjunction.

 

Logical Conjunction: AND

The logical conjunction operator && is used to check that the combination of two statements results in a true value. This is used when one condition cannot satisfy the intended result. Consider a pizza application whose valid sizes are 1 for small, 2 for medium, 3 for large, and 4 for jumbo. When a clerk uses this application, you would usually want to make sure that only a valid size is selected to process an order. After the user has selected a size, you can use a logical conjunction to validate the range of the item’s size. Such a program could be written (or started) as follows:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int pizzaSize;

    Console::WriteLine("Select your pizza size");
    Console::WriteLine("1=Small  | 2=Medium");
    Console::WriteLine("3=Medium | 4=Jumbo");
    Console::Write("Your Choice: ");
    cin >> pizzaSize;

    if(pizzaSize >= 0 && pizzaSize <= 4)
        Console::WriteLine("\nGood Choice. Now we will proceed with the toppings");
    else
        Console::WriteLine("\nInvalid Choice");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Select your pizza size
1=Small | 2=Medium
3=Medium | 4=Jumbo
Your Choice: 3

Good Choice. Now we will proceed with the toppings

Press any key to continue

When a program asks a question to the user who must answer by typing a letter, there is a chance that the user would type the answer in uppercase or lowercase. Since we know that C++ is case-sensitive, you can use a combined conditional statement to find out what answer or letter the user would have typed.

We saw that the truthfulness of a statement depends on how the statement is structured. In some and various cases, instead of checking that a statement is true, you can validate only negative values. This can be done on single or combined statements. For example, if a program is asking a question that requires a Yes or No answer, you can make sure the program gets a valid answer before continuing. Once again, you can use a logical conjunction to test the valid answers. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char sittingDown;

    do {
        Console::Write("Are you sitting down now(y/n)? ");
        cin >> sittingDown;

        if( sittingDown != 'y' && sittingDown != 'Y' )
            Console::WriteLine("\nCould you please sit down for the next exercise?");
    } while( sittingDown != 'y' && sittingDown != 'Y' );

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Are you sitting down now(y/n)? g

Could you please sit down for the next exercise?
Are you sitting down now(y/n)? k

Could you please sit down for the next exercise?
Are you sitting down now(y/n)? y

Wonderful!!!

Press any key to continue

Logical Disjunction: OR

Consider a program that asks a question and expects a yes or no answer in the form of y or n. Besides y for yes, you can also allow the user to type Y as a valid yes. To do this, you would let the compiler check that either y or Y was typed. In the same way, either n or N would be valid negations. Any of the other characters would fall outside the valid characters. Our hot-tempered program can be restructured as follows:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char answer;

    Console::Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
    cin >> answer;

    if( answer == 'y' || answer == 'Y' ) // Unique Condition
    {
        Console::WriteLine("\nThis job involves a high level of self-control.");
        Console::WriteLine("We will get back to you.");
    }
    else if( answer == 'n' || answer == 'N' ) // Alternative
        Console::WriteLine("\nYou are hired!");
    else
        Console::WriteLine("\nThat was not a valid answer!");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Do you consider yourself a hot-tempered individual(y=Yes/n=No)? s

That was not a valid answer!

Press any key to continue
 

 


Previous Copyright © 2004-2010 FunctionX, Inc. Next