Control Statements In C Language - Online Article

A program consists of a number of statements which are usually executed in sequence. Programs can be much more powerful if we can control the order in which statements are run.

Statements fall into three general types:

  • Assignment, where values, usually the results of calculations, are stored in variables.
  • Input / Output, data is read in or printed out.
  • Control, the program makes a decision about what to do next.

This section will discuss the use of control statements in C. We will show how they can be used to write powerful programs by:

  • Repeating important sections of the program.
  • Selecting between optional sections of a program.

The if else Statement

This is used to decide whether to do something at a special point, or to decide between two courses of action. The following test decides whether a student has passed an exam with a pass mark of 45.

if (result >= 45)
	printf("Pass\n");
else
	printf("Fail\n");

It is possible to use the if part without the else.

if (temperature < 0)
	print("Frozen\n"); 

Each version consists of a test, (this is the bracketed statement following the if). If the test is true then the next statement is obeyed. If is is false then the statement following the else is obeyed if present. After this, the rest of the program continues as normal. If we wish to have more than one statement following the if or the else, they should be grouped together between curly brackets. Such a grouping is called a compound statement or a block.

if (result >= 45)
{
	printf("Passed\n");
	printf("Congratulations\n")
}
else
{
	printf("Failed\n");
	printf("Good luck in the resits\n");
}

Sometimes we wish to make a multi-way decision based on several conditions. The most general way of doing this is by using the else if variant on the if statement. This works by cascading several comparisons. As soon as one of these gives a true result, the following statement or block is executed, and no further comparisons are performed. In the following example we are awarding grades depending on the exam result.

if (result >= 75)
	printf("Passed: Grade A\n");
else if (result >= 60)
	printf("Passed: Grade B\n");
else if (result >= 45)
	printf("Passed: Grade C\n");
else
	printf("Failed\n");

In this example, all comparisons test a single variable called result. In other cases, each test may involve a different variable or some combination of tests. The same pattern can be used with more or fewer else if's, and the final lone else may be left out. It is up to the programmer to devise the correct structure for each programming problem.

The switch Statement

This is another form of the multi way decision. It is well structured, but can only be used in certain cases where;

  • Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (int, long, short or char).
  • Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases.

Hopefully an example will clarify things. This is a function which converts an integer into a vague description. It is useful where we are only concerned in measuring a quantity when it is quite small.

estimate(number)
int number;
/* Estimate a number as none, one, two, several, many */
{
	switch(number)
	{
		case 0:
			printf("None\n");
		break;
		case 1:
			printf("One\n");
		break;
		case 2:
			printf("Two\n");
		break;
		case 3:
		case 4:
		case 5:
			printf("Several\n");
		break;
		default:
			printf("Many\n");
			break;
	} 
} 

Each interesting case is listed with a corresponding action. The break statement prevents any further statements from being executed by leaving the switch. Since case 3 and case 4 have no following break, they continue on allowing the same action for several values of number. Both if and switch constructs allow the programmer to make a selection from a number of possible actions. The other main type of control statement is the loop. Loops allow a statement, or block of statements, to be repeated. Computers are very good at repeating simple tasks many times, the loop is C's way of achieving this.

Loops

C gives you a choice of three types of loop, while, do while and for.

  • The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed.
  • The do while loops is similar, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once.
  • The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers.

The while Loop

The while loop repeats a statement until the test at the top proves false. As an example, here is a function to return the length of a string. Remember that the string is represented as an array of characters terminated by a null character '\0'.

int string_length(char string[])
{
	int i = 0;
	while (string[i] != '\0')
		i++;
	return(i);
}

The string is passed to the function as an argument. The size of the array is not specified, the function will work for a string of any size. The while loop is used to look at the characters in the string one at a time until the null character is found. Then the loop is exited and the index of the null is returned. While the character isn't null, the index is incremented and the test is repeated.

The do while Loop

This is very similar to the while loop except that the test occurs at the end of the loop body. This guarantees that the loop is executed at least once before continuing. Such a setup is frequently used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable.

do
{
	printf("Enter 1 for yes, 0 for no :");
	scanf("%d", &input_value);
} while (input_value != 1 && input_value != 0);

The for Loop

The for loop works well where the number of iterations of the loop is known before the loop is entered. The head of the loop consists of three parts separated by semicolons.

  • The first is run before the loop is entered. This is usually the initialisation of the loop variable.
  • The second is a test, the loop is exited when this returns false.
  • The third is a statement to be run every time the loop body is completed. This is usually an increment of the loop counter.

The example is a function which calculates the average of the numbers stored in an array. The function takes the array and the number of elements as arguments.

float average(float array[], int count)
{
	float total = 0.0;
	int i;
	for(i = 0; i < count; i++)
	total += array[i];
	return(total / count);
} 

The for loop ensures that the correct number of array elements are added up before calculating the average. The three statements at the head of a for loop usually do just one thing each, however any of them can be left blank. A blank first or last statement will mean no initialisation or running increment. A blank comparison statement will always be treated as true. This will cause the loop to run indefinitely unless interrupted by some other means. This might be a return or a break statement.

It is also possible to squeeze several statements into the first or third position, separating them with commas. This allows a loop with more than one controlling variable. The example below illustrates the definition of such a loop, with variables hi and lo starting at 100 and 0 respectively and converging.

for (hi = 100, lo = 0; hi >= lo; hi--, lo++)

The for loop is extremely flexible and allows many types of program behaviour to be specified simply and quickly.

The break Statement

We have already met break in the discussion of the switch statement. It is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch. With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition.

The continue Statement

This is similar to break but is encountered less frequently. It only works within loops where its effect is to force an immediate jump to the loop control statement.

  • In a while loop, jump to the test statement.
  • In a do while loop, jump to the test statement.
  • In a for loop, jump to the test, and perform the iteration.

Like a break, continue should be protected by an if statement. You are unlikely to use it very often.

The goto Statement

C has a goto statement which permits unstructured jumps to be made. Its use is not recommended, so we'll not teach it here. Consult your textbook for details of its use.

About the Author:

No further information.




Comments

No comment yet. Be the first to post a comment.