Wednesday, 25 December 2013

Difference

 Difference between if and switch

The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple  alternatives. It uses an int expression to determine which alternative should be executed.

 Difference between for and while

One first basic rule is that you should use the for loop when the number of iterations is known. For instance: The loop iterates over the elements of a collection. The loop iterates over a range of  values which is known in advance at execution time. The object provides a way to iterate over its elements with a for statements (e.g files). The while loop is the more general one because its loop condition is more flexible and can be more complicated than that of a for loop. The condition of a for loop is always the same and implicit in the construction. A for loop stops if there are no more elements in the collection to treat. For simple traversals or iterations over index ranges it is a good advice to use the for statement because it handles the iteration variable for you, so it is more  secure than while where you have to handle the end of the iteration and the change of the iteration variable by yourself. The while loop can take every boolean expression as condition and permits therefore more complex end conditions. It is also the better choice if the iteration variable does not change evently by the same step or if there are more than one iteration variable. Even if you can handle more than one iteration variable in a for statement, the collections from which to choose the values must have the same number of elements. Note: In C 'for' and 'while' can be easily replaced by each other: while (exp) stmt for (;exp;) stmt for (exp1;exp2;exp3) stmt { exp1; while (exp2) { stmt exp3}}

No comments:

Post a Comment