Select Page

Welcome to the final installment of a three-part introduction to C. In this chapter, various constructs are discussed including conditional statements and loops.

Conditionals

If-Statement

There are times in a program when you will want to perform actions based on certain results. For instance, let’s say that we want to test to see if a number entered is greater than 1. We might write a program like this (assume the proper headers and functions):

[sourcecode language=”cpp”]
int numGames;

printf( “How many video games have you beaten? ” );
scanf( “%d”, &numGames );

// determine the correct grammatical usage here
if ( numGames > 1 )
{
printf( “nYou have beaten %d games!”, numGames );
}
else if ( numGames == 1 )
{
printf( “nYou have beaten only %d game!”, numGames );
}
else if ( numGames == 0 )
{
printf( “nYou are not very adept at gaming because you have not beaten any games!” );
}
else
{
printf( “nThe input you entered is not valid.” );
}
[/sourcecode]

So, in this example, we are displaying text to the user based on the value of the integer that was entered when prompted to do so.

Switch-Block

The structure of an if-statement is as such that you must always have one and only one “if” clause, followed by zero or more “else if” clauses, then completed with an optional “else” clause. In any of these clauses (or blocks), if the statement inside of the parenthesis is true, then the code in the corresponding block shall be executed; if false, then the next evaluation is tested above the next block, if any. Once a block is executed, then execution goes to the code immediately following the end of the if-statement. <b>Switch Statement</b> The switch statement is very similar in use to the if-statement. Let’s see an example of the same code from above, but instead, using a switch statement:

[sourcecode language=”cpp”]
int numGames;

printf( “How many video games have you beaten? ” );
scanf( “%d”, &numGames );

// determine the correct grammatical usage here
switch ( numGames )
{
case 0:
printf( “nYou are not very adept at gaming because you have not beaten any games!” );
break;

case 1:
printf( “nYou have beaten only %d game!”, numGames );
break;

default:
printf( “nYou have beaten %d games!”, numGames );
break;
}
[/sourcecode]

So, there are some pros and cons to using the switch statement over the if-statement. Off the bat, you should notice that there is no differentiation between values that are less than 0 or greater than 1. The reason being is that evaluations using the greater than, less than, and such signs cannot be done with this type of construct. Therefore, the “default” block takes the place of the “else” block in the switch.

Something else of note in this switch statement is the use of the “break” keyword. When execution reaches this keyword in a switch statement, execution jumps to the line directly after the switch statement in question.

On the plus side, you have the option of “falling-through” on the blocks of a switch statement. What does this mean exactly? In essence, if you did not put in the “break” keywords, execution would fall thought to the next block and the next and the next until a “break” had been executed. In this particular example, it’s not really useful. However, there are some cases (pun intended) when falling through is advantageous. For instance, when parsing text files, which is beyond the scope of this article.

Operators

When writing comparisons in the if-statements described above or the various loops that are to follow, there are several options at your disposal when constructing these comparisons. These options are some of many types of operators in C. The following is a list of only the evaluation operators and their meaning:

Symbol Meaning
> Greater Than
< Less Than
>= Greater Than Or Equal To
<= Less Than Or Equal To
== Is Equal To
!= Is Not Equal To

Of special note is that if you would like to compare two values to be equal, you use a double equal sign (==) instead of the single equal sign (=). Remember, the single equal sign is for assignment of a value into a variable. If you are uncertain about this, please go back toPart Two for a clearer explanation.

Loops

Loops are a mechanism for executing the same piece of code multiple times. There are two distinct types of loops that are discussed in this article: while and for.

While-Loop 

Let’s say that we would like to display a character several times. To do so, we might write a piece of code in this fashion:

[sourcecode language=”cpp”]
int iNumTimes = 0;
char cSymbol = ‘X’;

while ( iNumTimes < 5 )
{
printf( “%d”, cSymbol );
iNumTimes = iNumTimes + 1;
}
[/sourcecode]

The output for this program would look like this:

XXXXX

Instead of asking the user to enter a number and a character, we are simply hard-coding values to emphasize the structure of the while-loop. When execution comes to the beginning of the while-loop, the comparison inside of the parenthesis is evaluated similar to an if-statement. If the comparison results to be true, then the code inside the following block is executed. Once executed, the comparison at the top of the while-loop is evaluated again and so on. When the comparison becomes false, then the execution point is placed directly after the subsequent block of code.

Of special note is the line that increments the variable, “iNumTimes”. If this line was not inside of the block, the comparison would never evaluate to be false; therefore, the loop would never exit. This is termed as an infinite loop. It is important to remember to code in a way for the loop to eventually cleanly exit.

For-Loop 

A for-loop is very similar to a while-loop, but is specifically useful for counting. We can recode the previous example in the following way:

[sourcecode language=”cpp”]
int iNumTimes;
char cSymbol = ‘Y’;

for ( iNumTimes = 0; iNumTimes < 4; i++ )
{
printf( “%d”, cSymbol );
}
[/sourcecode]

This code gives similar output:

YYYY

The block of the for-loop is the same as the while-loop. However, inbetween the parenthesis is a more complex statement. This area is made up of three parts, all separated by semi-colons:

  1. Initialization: initialize the counter.
  2. Comparison: same as the while-loop; true puts the execution inside of the block, false skips it.
  3. Increment: increment your counter.

When execution first comes to the for-loop, the first part (initialization) is run. This is the only time that the first part is ever run. Then the second part (comparison) is evaluated. If it’s true, then the subsequent code block is executed; otherwise, execution goes to the statement directly following the subsequent code block. When the second part evaluates to true and the code block is run, execution goes back to the top and the third part (increment) is run. From this point on, the second part is run, if it’s still true, then the block is run, then the third part again and so on.