Suite101

C Tutorial Conditions

Selectively executing code statements based on evaluation.

© Guy Lecky-Thompson

This C tutorial covers conditions in C programming, aimed at users of the Borland C compiler, or any other suitable C compiler. Covers if, else, case, switch and break...

Introduction

In this C programming tutorial, we are going to learn how to selectively execute code statements based on the evaluation of a condition. If the reader has not yet set up their environment using the Borland C compiler (or equivalent) they should refer to C Tutorial 1 before reading the rest of this tutorial.

We also introduce the concept of conditions, in general, in this tutorial. Before continuing, the reader is advised to take a look at the following general programming articles if they have not programmed before:

In addition, the tutorial covering Condition Testing is a pre-requisite for understanding this tutorial. Even current programmers should review the condition testing tutorial to ensure that we are all on the same page.

These tutorials are also part of the Computer Programming Topic here at Suite101.

The if Statement

An if statement takes the general form:

if ()
{
// ... code statements ...
}

As is usual with the C programming language, the code block to be executed is contained between braces ( { and } ), and the statement can be any valid combination of C operators which allow a test for veracity (true/false). If the condition evaluates to true, the code in braces is executed.

Thinking back to the last question of the C Tutorial - Lesson 2 we can use this in conjunction with a looping construct to provide an alternative to a counted loop.

For example, to print out every second letter of the alphabet, the for loop might look something like:

for (nLetter = 'a'; nLetter = 'z'; nLetter = nLetter + 2)
{
printf('%c',nLetter);
}

The reader will remember that the printf function allows formatted printing (covered in detail in another tutorial). We could also have reduced the nLetter = nLetter + 2 to a slightly less cumbersome shorthand nLetter+=2. This makes more sense remembering that the usual step statement for sing-stepping through a loop would be nLetter++.

So, if we wanted to conditionally print each second letter in a single stepped loop, we could use an if statement. All we need to do is determine whether the current value of nLetter qualifies as a 'second' letter : b,d,f,h etc.

As in many programming problems, there are many ways to do this. Some are more obvious that others, and some require more typing than others. Before we give the most elegant solution, let us look at the most cumbersome.

We could create a condition statement for each value of nLetter that should lead to printing out the current value:

for (nLetter = 'a'; nLetter = 'z'; nLetter++)
{
if (nLetter == 'b')
{
printf("%c",nLetter);
}
}

Note that we have a single stepped loop, and that we have not included all the necessary if statements (one for each letter). Clearly, there must be a better way!

We can reduce the number of if statements by creating a compound condition such as:

if (nLetter == 'b' ||
nLetter == 'd' ||
nLetter == 'f' ||
... etc. )

Again, in the interests of brevity, we have left most of the conditions out, as well as the rest of the code. Of note here is the || operator, which can be translated as or. So, the above says : if nLetter is 'b', or 'd', or 'f' ( and so on) then execute the statements.

Before we look at this from another angle, we should just explore another aspect of condition testing - the else statement. This is used to execute a piece of code should the if condition evaluate to false. In other words, we could use it to perform default processing when a condition is not met.

For example:

if (nLetter 'z')
{
printf("%c",nLetter);
}
else
{
break;
}

The above would break out of the current loop without printing the letter 'z'. This approach does not really help our current problem, so we need to look elsewhere.

The switch and case statements

The switch statement allows us to test a scalar variable for a single value within the range of discrete values allowed by the scalar type. The set of all letters is said to be scalar, because we know in advance how many there might be. The set of floating point numbers is not, because there are (depending on the accuracy chosen) an infinite number of possibilities.

Therefore, the switch statement most frequently crops up alongside variables containing letters or numbers. Let's jump in at the deep end:

for (nLetter = 'a'; nLetter = 'z'; nLetter++)
{
switch (nLetter)
{
case 'b':
printf("%c",nLetter);
break;
}
}

This is a good start. The switch statement contains, in brackets, the variable we wish to test. The case statements contain the value that we wish to test for (the equivalent to writing 'if (nLetter == b)' in this case). The break statement is vital - without it, the program would not know that we had found the one and only case that fits our needs.

This is important once we realize that we can write switch statements such as:

switch (nLetter)
{
case 'b':
case 'd':
case 'f':
printf("%c",nLetter);
break;
}
}

So, we could have one case [value] per letter. This improves our situation slightly. As an illustration of the statements in this tutorial these examples are all very well, but we should find an elegant solution to the current problem.

The Solution

As always, a more elegant solution needs a little bit of lateral thinking - if we want to print every second letter, we need a way to know if the letter is 'even'. Since we cannot guarantee that the character code for the letter will always be the same (some platforms have different numbering schemes), we would like an external counter to test this for us.

If that counter is 1, the letter is odd and we do not print it out, but increment the counter. Otherwise, we print the letter, and reset the value to 1.

int nCounter, nLetter;
for (nLetter = 'a'; nLetter = 'z'; nLetter++)
{
if (nCounter == 1)
{
nCounter++;
}
else
{
printf("%c",nLetter);
nCounter = 1;
}
}

This has been one of the longer tutorials, so please feel free to go over it again and post any questions in the discussion thread (at the bottom of the page). Suggestions for improvements should go to the author : computerprogramming@suite101.com .

Questions

Test your knowledge, by considering the following questions:

  1. How can the above be re-written with a case statement?
  2. How could the above be achieved with the modulo operator?

Answers via the mailing list, as well as an advance copy of the Lessons, as they arrive.


The copyright of the article C Tutorial Conditions in Computer Programming is owned by Guy Lecky-Thompson. Permission to republish C Tutorial Conditions in print or online must be granted by the author in writing.



Comments
Oct 14, 2007 7:32 AM
shahid :
Hi im trying to make an exe file from my source file (test.cpp) in the command prompt.

I am able to create the .obj file successfully by using the typing the follwing command

tcc test.cpp(source file name)

it successfully creates the test.obj file. Now i want to use the linker (tlink.exe) to convert the test.obj to test.exe


when i type:-

tlink test.obj

it does create the test.exe file and a test.map file but with the following error messages

Error: undefined symbol _getch in module test.cpp

Error: undefined symbol _printf in module test.cpp

Error: undefined symbol _clrscr in module test.cpp

but when the exe file run it dosent work properly and is very small in size.

i am able to create the exe file by using the tcc.exe. I want to know the how to create the exe straight from the .obj file by using the tlink

thanks
Oct 19, 2007 12:17 AM
Guy Lecky-Thompson :
Hi,

To do this, you need to specify the library files (.lib / .obj) on the command line. In this case, the library file that you need to link to should be listed in the Turbo C documentation.

Guy
2 Comments


Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo