Sunday, March 18, 2007

Control Statements


Conditional Statements

The if else Statement

This is used to decide between two or more courses of action.Lets see an example,The following test decides whether the cost is above 500

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


Else is optional,

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


The condition is always kept inside the brackets.
If the condition returns true then the statements following it is executed, if it returns false the the statements after else is executedAfter this, the rest of the program continues as normal.

We can have multiple if statements,

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.

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.

The switch Statement
This is another form of the multi way decision.

* 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.

Lets see an example,

int number;
{
switch(number)

{
case 0 :
printf("None\n");
break;
case 1 :
printf("One\n");
break;
case 2 :
printf("Two\n");
break;
case 3 :
case 4 :
printf("Several\n");
break;
default :
printf("Many\n");
break;
}
}


Each case is listed with a corresponding action.

The break statement prevents any further statements from being executed by leaving the switch. Since case 3 have no following break, they continue on allowing the same action for several values of number.

------------------------------------------------------------------------------------------------------------------------

Loops

There are three types of loops 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.Lets see a function that returns the length of a string(using while loop)

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.

-----------------------------------------------------------------------------------------------------------------------


Break & Continue Statements

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.

No comments: