|
|
|
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...
IntroductionIn 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 StatementAn 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 statementsThe 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 SolutionAs 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 . QuestionsTest your knowledge, by considering the following questions:
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 :
Oct 19, 2007 12:17 AM
Guy Lecky-Thompson :
2 Comments
|
|
|
|
|
|
|
|