article

C++ - Lesson 3 : do, while, #include, #define

Email
Submitted on: 1/1/2015 6:59:00 AM
By: Found on the World Wide Web (from psc cd)  
Level: Beginner
User Rating: By 8 Users
Compatibility: C++ (general)
Views: 963
 
     Welcome fellow programmers to our third lesson in a long series on the road to programming C++. This articles explains do, while, #include, and #define. (from http://pa.pulze.com/)

 
				

Beginners C++ - Lesson 3   
Instructor:   Paul C. Benedict, Jr. (PCC PaulB)   

Color coded text:

    black            New things to Remember
    blue             C++ keywords (do, while)
    green           C++ preprocessor directives (#include, #define)


Section 3.1  
Welcome fellow programmers to our third lesson in a long series on the road to programming C++. Just like the real roads we travel on, they are not all big one straight line. Just imagine how boring driving would be if you were you limited to one flow of direction. Just imagine how boring programs would be if it couldn't branch off and make decisions. Every time you ran the program it would be the same, and that would just depress us all, wouldn't it? :-)   

We are going to learn that programs run in one big loop. Every program begins in a loop, and branches off to smaller loops, and smaller, etc. We will begin studying what kind of loops C++ support, practice when and when not to use certain types of loops, and find common mistakes. All that great boolean algebra we learned will yet appear again as we learn how to control our loops!   

C++ supports these types of branching mechanisms:   
if   
if..else   
if..else..if   
switch..case..default   

C++ supports these types of loops:   
for   
while   
do..while   

You can make decisions using these special operators:   
    Less-than                         <   
    Greater-than                     >   
    Less-than or equal to        <=   
    Greater-than or equal to    >=   
    Equal to                           ==   
    Not equal to                     !=   

We will use these operators in making decisions to what the program should do next. These set of operators are called "Rational and Equality Operators" and compare the value on the left to the value on the right. These evaluate to a bool value which is true or false.   
   
Example 3.1.1
    bool equal = (5 < 3);   
   
the variable equal gets assigned the value false because 5 is defined to be greater than 3 by our math system.   


Section 3.2

The most simplest form of control loop is the if keyword. The syntax for this keyword is as follows:   

    if ( expression )   
         statement1   
    else   
         statement2   

The if keyword executes statement1 if expression is true (nonzero); if else is present and expression is false (zero), it executes statement2. After executing statement1 or statement2, control passes to the next statement.   

Example 3.2.1
    if ( i > 0 )   
        x = y / i;   
    else   
        x = 0;   
   
In this example, the statement x = y / i; is executed if i is greater than 0. If i is less than or equal to 0, x is assigned the value of 0. Note that the statement forming the if clause does not end with a semicolon. Note that again so you don't forget.   

Let's look at a more complex example where we want to do more than one statement depending on how if the if clause evaluates.   

Example 3.2.2
    if ( i >= 5 )   
    {   
        x = 4 * i;   
        i++;   
    }   
    else   
        i = 5;   
   
In this example, the statements x= 4 * i; and i++; are executed if i is greater than or equal to 5. If i is less than 5, i is assigned the value 5. Note that how we grouped our statement in braces { } to indicate two or more statements that need to be executed if the if clause evaluates to be true (nonzero).   

Now the else clause does not need to be included if you don't have any optional functionality you need to be performed. It is perfectly legal to do this:   

Example 3.2.3
    if ( i >= 5 )
    {   
        x = 4 * i;       
        i++;   
    }   
   
Example 3.2.4
But what if we wanted to evaluate many cases? We will have to use a nested if..else..if statement to accomplish this. Let's say we wanted to perform a separate action when i is 0, 1, 2, 3, 4, 5. This is how it would be coded:   
    if ( i == 0 )   
        x = 1;   
    else if ( i == 1 )   
        x = 2;   
    else if ( i == 2 )   
        x = 4;   
    else if ( i == 3 )   
        x = 8;   
    else if ( i == 4 )   
        x = 16;   
    else if ( i == 5 )   
        x = 32;   
       
If i is 0, x is assigned 1, then control jumps to the end of our if clause.   
If i is 1, x is assigned 2, then control jumps to the end of our if clause.   
If i is 2, x is assigned 4, then control jumps to the end of our if clause.   
If i is 3, x is assigned 8, then control jumps to the end of our if clause.   
If i is 4, x is assigned 16, then control jumps to the end of our if clause.   
If i is 5, x is assigned 32, then control jumps to the end of our if clause.   

For you math gurus out there, can you see what is happening to x depending on the value of i in Example 3.2.4? If anyone noticed the simple pattern, you would see we are calculating the powers of 2, using i as our exponent. We will go back to this example many times and show you different methods of doing this.   


Section 3.3

Now just imagine if we wanted to get the answer of 2 to some variable, which is i,  in C++. C++ does not have an exponent operator, so we would have to have to have huge and ugly code like Example 4 in Section 3.2. Fortunately, we can loop to find answers to complex problems like the 2 to the i-th power. This brings us to our third new keyword in our lesson. The for keyword has the syntax as follows:   

    for ( init_expr; cond_expr; loop_expr )   
        statement   

For even a simpler syntax of the for loop, remember this:   

    for ( step1; step2; step4 )   
        step3;   

Wow! This is alot to digest, so lets break apart each expression and look at each one individually:   
   
1. The first thing that happens when a for loop is encountered is the init_expr expression is evaluated. init_expr is most commonly used to initialize a variable which will control the loop.   
2. Next cond_expr is evaluated. This expression is a conditional expression, which determines if the loop will continue going or not. If cond_expr evaluates to true (nonzero), the loop continues. If cond_expr is false (zero), control passes to the statement following the for loop.   
3. statement is executed.   
4. loop_exr is than evaluated, and goes back to step 2.   

Notice that after loop_expr there is no semicolon!   

Example 3.3.1
    int x = 1;   
    for ( int i = 1; i <= 10; i++ )   
        x *= 2;   
   
Let's go through the steps of this for loop:   
1. First the i variable is created and initialized to 1.   
2. Next i <= 10; is evaluated next. Since i is 1 and is less than 10, it evaluates true and we enter the loop and execute x *= 2;.   
3. Next we increment i with our loop expression, i++;.   
4. Next i <= 10; is evaluated next. Since i is 2 and is less than 10, it evaulates true and we enter the loop and execute x *= 2;.   
5. Next we increment i with our loop expression, i++;.   
6. We continue this process until our conditional expression, i <= 10; evaluates for false, and we exit the loop. This happens when i increments to 11.   

Look at what we did! We just compacted that ugly if..else..if clauses into a for loop and we got the value of 2 to the 10th power, which is 1024! Now that surely beats the latter.

Example 3.3.2
But say we didn't wanted to calculate 2 to the 10th power, we wanted to calculate 2 to the nth power? We could go back and modify the example as follows:   
    int x = 1;   
    int n = 5;   

    for ( int i = 1; i <= n; i++ )   
        x *= 2;   
   
Remember that when you do programming with integers, the int data type can only hold 16-bits or 32-bits (or even 64-bits) depending on what bit compiler you use. So if we are using a 32-bit compiler, n being set to 19 would be safe because we have 32-bits (0 through 31) to work with. If we were working on a 16-bit compiler, 19 would overflow us and x would be complete junk to us.   

Remember our "bug" term from the last lesson? This unexpected overflow is one type of bug which can make a program spit out junk, even though the logic and the program is perfectly fine. Watch out for sneaky things like this.   


Section 3.4

Usually the for loop is used when we want to iterate through a list of numbers. In Example 2 of Section 3.3, we went from 1 to n. Sometimes there is nothing to iterate and just want to keep on looping while a condition is true. This brings us to the next kind of loop, called the while loop. The syntax for while loop is as follows:   

    while ( expression )   
        statement   

The while keyword executes statement while expression is true (nonzero).   

Example 3.4.1
    bool p = false;   
    int x = 0;   

    while ( !p )   
    {   
       x++;   
       p = (x > 20);   
    }   
    x++;   
        
This while loop does not terminate until p becomes true. When p is true, the expression !p evaluates to false, terminating the loop, then increments x one last time.   

The variable p that controls this loop isn't very good at describing what it does. Welcome to the world of good variable names! You have became advanced enough to give good variable names. This has many advantages like not having to guess at what a variable does. This is a much better example:   

Example 3.4.2
    bool IsXGreaterThan20 = false;   
    int x = 0;   

    while ( !IsXGreaterThan20 )   
    {   
       x++;   
       IsXGreaterThan20 = (x > 20);   
    }   
    x++;   
        
Going back to our "2 to the n-th power" example, we can use a while loop to do the same thing as the for loop did. (The for loop is more appropriate for this kind of situation, so you should stick with that). Just remember these two simple rules:   
    1. Use for when wanting to iterate a range of values.   
    2. Use while when you want to loop while a condition is true.   

Example 3.4.3
    int x = 1;   
    int n = 5;   
    int i = 1;   

    while ( i <= n )   
    {   
        x *= 2;   
        i++;   
    }   
   

 

Section 3.5

Sometimes, it might not always be appropriate for a loop to test its condition at the beginning of the loop, like the while loop. If you want to enter the loop and then check at the end, we use the do..while loop. The syntax for the do..while loop is as follows:   

    do   
        statement   
    while ( expression );   

This works just like the while loop, except the evaluation of the expression comes at the end. This kind of loop ensures the statement will be executed at least one time. Therefore, we do not need to go in-depth on this section.   

Example 3.5.1
    int y = 0;   
    int x = 10;   

    do    
    {   
        y = x + 5;   
        x--;   
    } while ( x > 0 );   
   
The loop is entered. then y gets added x + 5, then x gets decremented. This loop continues running until x is no longer greater than 0. So y gets added 15, then 14, 13, 12, ... until 6.   


Section 3.6

The last and final control statement in C++ is the switch..case..default trio. This is the syntax:   

    switch ( expression )   
    {   
    case constant_expression:   
    ...   
        statement   
    ...   
    default:   
        statement   
    }   

We use this when we want a more readable form of an if statement. constant_expression must be an int value like 2, 3, -6, but not a variable or a floating point number. It cannot be a variable because as the word implies, it varies. It cannot be a floating point, because computers can't represent fractions perfectly, which would mess up the case.   

A case is just like if the code read, if ( expression == case ), but much more readable. You can think of default: as being the else clause also.

Example 3.6.1
Watch how we convert the if clause to the switch clause:   
    if ( x == 2 )   
         i = 1;   
    else if ( (x == 3) || (x == 5) || (x == 7) )   
         i = 2;   
    else if ( (x == 4) || (x == 9) )   
         i = 3;   
    else   
         i = 4;   
       
can be transformed into
    switch ( x )   
    {   
    case 2:   
        i = 1;   
        break;   
    case 3, 5, 7:   
        i = 2;   
        break;   
    case 4, 9:   
        i = 3;   
        break;   
    default:   
        i = 4;   
    }       
   
Now isn't that much easier to understand? Notice the break; statement. This "breaks" us out of the switch clause and we continue execution outside of it. If we did not have break;, the next statement would keep on executing until it hits the ending right brace }.

Example 3.6.2
Here is an example of the problem stated above:
    switch ( x )   
    {   
    case 2:   
        i = 1;   
    case 3, 5, 7:   
        i = 2;   
    default:   
        i = 4;   
    }   
   
Oh no! if x is 2, then it will assign i to 1, then 2, then 4! We don't want this, so we must put our break; statement in there to prevent this from happening. This is another peculiar bug which can creep into your code.   


New terms to remember

Bug
Clause
Condition
default   
do   
else   
for   
if   
Loop
switch   
while   


Review problems

01. Find the bug:   
         int x = 2;   
         if ( x = 0 )   
             x = 3;   
         else   
             x = 4;   
   
02. Why doesn't this program ever make y equal to 3 when x is 0?   
        int x = 0;   
        int y = 0;   

        if ( x == 0 )   
        {
            x = 1;   
            y = 3;   
        }   
        else   
            x = 3;   
        y = 1;   
   
03. Write a for loop which will sum all the numbers from 1 to 20.   

04. Why doesn't this loop ever end?   
          int n = 2;   
          while ( n <= 3 )   
          {   
              n *= 2;   
              n -= 2;   
          }        
   
05. Convert this if..else..if clause into an easier reading switch clause:   
          if ( (x == 0) || (x == 3) )   
              i++;   
          else if ( x == 2 )   
              i *= 2;   
          else if ( (x == 6) || (x == 4) || (x == 5) )   
              i = i + 5 % i;   
          else if ( x == 1 )   
              i = 2;   
          else   
              i = x;     
         
06. Write a loop that sums every odd number from 1 to 255. There are two possible ways of doing this, do both.


Other 18 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.