L> C Programming Course note - Looping Constructs arrival to C Programming Looping Constructs

Computers room very great at performing repetitive tasks really qlondonchinatown.orgkly. In this section we will learn how to make computer system repeat actions one of two people a specified variety of times or till some stopping problem is met.

You are watching: The number of iterations of a counter-controlled loop is known in advance.

while Loops ( Condition-Controlled Loops )

Both if loops and also do-while loops ( see listed below ) room condition-controlled, definition that they proceed to loop until some problem is met. Both while and also do-while loops alternate between performing actions and testing because that the preventing condition. if loops examine for the stopping problem first, and also may not execute the body of the loop at every if the problem is originally false. Syntax:

while( condition ) body; where the body have the right to be either a solitary statement or a block of statements in ~ curly braces .

Example:

int ns = 0; while( ns

do-while Loops

do-while loops are precisely like while loops, except that the test is performed in ~ the finish of the loop rather than the beginning. This guarantees that the loop will be carry out at least once, which is beneficial for checking user input amongst other things ( see example below. ) Syntax: carry out body; while( problem ); In concept the body can be one of two people a solitary statement or a block of statements in ~ curly braces , however in exercise the curly braces are almost always used with do-whiles. Example: int month; do printf( "Please enter the month of your birth > " ); scanf( "%d", &month ); when ( month 12 ); keep in mind that the over example can be improved by report to the user what the difficulty is if month is not in the variety 1 come 12, and that the could likewise be done utilizing a while loop if month were initialized to a value that ensures entering the loop.The adhering to diagram shows the difference between while and also do-while loops. Note that once you go into the loop, the procedure is identical from that point forward:
*

for Loops

for-loops are counter-controlled, definition that they are normally used whenever the number of iterations is known in advance. Syntax:

*

whereby again the body have the right to be either a solitary statement or a block of statements within curly braces .

Details: The initialization step occurs one time only, before the loop begins. The problem is tested at the beginning of each iteration of the loop. If the condition is true ( non-zero ), then the body of the loop is executed next. If the condition is false ( zero ), climate the human body is not executed, and execution continues with the code following the loop. The incrementation happens AFTER the execution the the body, and also only once the human body is executed. Example:
*

one-of-a-kind Notes: The third component of the loop is labeling "incrementation", due to the fact that it normally takes the form of "i++" or something similar. Yet it deserve to be any kind of legal C/C++ statement, such as "N += 3" or "counter = basic + delta". In the instance above, the variable i is declared before the loop, and also continues come exist ~ the loop has completed. You will additionally see occasions whereby the loop variable is asserted as component of the because that loop, ( in C99 ), in which situation the change exists just within the human body of the loop, and also is no longer valid when the loop completes: for( int i = 0; i ( In Dev C++ you have the right to specify support for C99 by selecting Project->Project choices from the menu, and also then picking the Parameters tab. Under "C compiler", include the line: -std=c99 )

The comma operator

C has a comma operator, that basically combines two statements so the they deserve to be considered as a single statement. Around the only ar this is ever used is in for loops, come either administer multiple initializations or to permit for multiple incrementations. For example: int i, j = 10, sum; for( ns = 0, sum = 0; i

break and continue

break and continue room two C/C++ declaration that enable us to further control flow within and out of loops. break reasons execution to instantly jump out of the present loop, and also proceed with the code adhering to the loop. continue reasons the remainder the the present iteration the the loop to be skipped, and for execution to recommence with the following iteration. In the instance of for loops, the incrementation action will be executed next, adhered to by the problem test to start the next loop iteration. In the situation of while and do-while loops, execution jumps come the next loop problem test. ( we have likewise seen break provided to jump the end of switch statements. Proceed has no definition in move statements. )

Infinite Loops

infinite loops space loops that repeat forever without stopping. Generally they are led to by some type of error, such as the following example in i beg your pardon the wrong change is incremented: int i, j; for( i = 0; i various other times infinite loops offer a useful purpose, such as this alternate method of checking user input: while( true ) { printf( "Please enter a month from 1 come 12 > " ); scanf( "%d", &month ); if( month > 0 && month

Empty Loops

A usual error is to place an extra semi-colon at the end of the when or for statement, developing an empty loop body in between the closing parenthesis and also the semi-colon, such as: int i; for( ns = 0; ns or: int ns = 0; while( i In the instance of the while loop shown above, that is not only empty but likewise infinite. There room some really rare circumstances in i beg your pardon a programmer will deliberately create an north loop, most of which are beyond the limit of this course. ( This is know as a busy loop. ) In this case, the semicolon need to be inserted on a heat by itself, and plainly commented to suggest that the empty loop is deliberate and also not one oversight: while( ( error = someFunction( ) ) != 0 ) ; // empty loop - does nothing forever, till someFunction returns a zero printf( "error = %d ", error ); // after ~ the loop. Error must be zero to gain here.

Nested Loops

The password inside a loop deserve to be any kind of valid C code, including other loops. Any type of kind that loop have the right to be nested within of any kind of other sort of loop. Because that loops are commonly nested within of other for loops, for example to create a an easy multiplication table: const int NROWS = 10; const int NCOLS = 10; for( int r = 0; r some programmers like to use succeeding integers i, j, k, l, etc. For usage in nested because that loops. This can be appropriate if the mathematilondonchinatown.org being applied uses lot of ijk subscripts. various other times it can be much less confusing come use alternative variables that are an ext meaningful come the trouble at hand, such together the r and also c variables used above to store track that rows and also columns. The limits regarding how deeply loops might be nested is implementation dependent, however is usually too high to it is in of any type of concern, except in cases of extremely complex or exceptionally poorly composed programs.

See more: Which Type Of Sensory Receptor Allows Us To Feel An Insect Landing On Our Skin?

Floating suggest Increments in ~ Loops

Engineers and also scientists commonly write iterative programs in i beg your pardon a floating allude value measures through a range of worths in little increments. Because that example, suppose the "time" variable demands to change from a short of tMin come a high the tMax in actions of deltaT, whereby all these variables room doubles. The apparent BUT INCORRECT approach is together follows: for( time = tMin; time so why is this so wrong? If deltaT is small and/or the variety is large ( or both ), the loop might execute for thousands of iterations. That means that through the end of the loop, time has been calculate by the summation that thousands of addition operations. Numbers that seem "exact" to us in decimal form, such together 0.01 room not exact when the computer system stores castle in binary, which means that the value supplied for deltaT is really an approximation to the precise value. Because of this each addition step introduces a very small amount the roundoff error, and by the time you add up hundreds of these errors, the complete error have the right to be significant. The correct approach is as follows, if you recognize the minimum and maximum values and also the desired readjust on every iteration: int nTimes = ( tMax - tMin ) / deltaT + 1; for( int i = 0; ns Or conversely if you know the minimum, maximum, and number of desired iterations: double deltaT = ( tMax - tMin ) / ( nTimes - 1 ); for( int ns = 0; i In general there are four values that can be provided to point out stepping v a range - the low finish of the range, the high finish of the range, the variety of step to take, and the increment to take it on each step - and if you know any type of three the them, climate you deserve to calculate the 4th one. The correct loop have to use one integer counter to finish the loop a given number of times, and also use the low end of the variety and the increment as displayed to calculation the floating point loop variable at the beginning of every iteration that the loop. therefore why is that better? The number of times that the loop executes is now managed by one integer, which does no have any type of roundoff error upon incrementation, so over there is no opportunity of performing one too countless or one too couple of iterations early to built up roundoff. The time variable is now calculated indigenous a solitary multiplication and a single addition, which can still introduce some roundoff error, however far less than countless additions. wherein does the +1 come from? The +1 is essential in stimulate to incorporate both endpoints of the range. Intend tMax were 20 and also tMin were 10, and deltaT to be 2. The preferred times would be 10, 12, 14, 16, 18, 20, i m sorry is a complete of 6 time values, no 5. ( 5 intervals if you desire to look in ~ it that way. ) ( 20 - 10 ) / 2 returns 5, therefore you have to include the extra 1 to get the correct variety of times the 6. Another way of looking in ~ this is that if nTimes is the variety of data point out in the range, climate nTimes - 1 is the variety of gaps between the data points. Example: interpolate.c is a qlondonchinatown.orgk-and-dirty example of interpolating floating allude numbers in a loop, that was whipped up in 10 minutes in class. That is NOT an instance of good code, however it is an example of how a qlondonchinatown.orgk little program deserve to be used to test out, beat with, or in this instance demonstrate a new or unfamiliar concept. This example interpolates the role f( x ) = x^3 over the selection from -1.0 come 4.0 in actions of 0.5, using three approachs: constant - take the median of the inputs at the end points, evaluate f( median input ), and also assume the role is continuous over the range. Direct - evaluate the function at the endpoints, and also then use a straight interpolation of the endpoint role values in between. Non-Linear - Linearly interpolate the role inputs over the range, and at each evaulation point, evaluate the function of the interpolated inputs.

When to use Which Loop ?

If you recognize ( or have the right to calculate ) how countless iterations friend need, then use a counter-controlled ( because that ) loop. Otherwise, if the is crucial that the loop finish at the very least once before checking for the protecting against condition, or if the is not possible or systematic to inspect the avoiding condition prior to the loop has executed at least once,then usage a do-while loop. Otherwise usage a when loop.

Exercises

compose a program that generates a table reflecting the difference in between "time1" calculated as "time1 += deltaT" and "time2" calculated as "time2 = i * deltaT", for iterations native 0 as much as an top limit mentioned by the user. The user should additionally specify a frequency for how generally (s)he desires the results printed in the table. So if they go into 10 for the frequency you need to print results every 10th time through the loop, and also if they go into 100, then print every 100th time v the loop, etc. Hint: use mod because that the print frequency. Compose a regimen to calculate epsilon, the smallest value that have the right to be included to 1.0 and still be distinguished from 1.0. Hint: start with epsilon equal to 1.0, and also then keep dividing it by 2.0 until 1.0 + epsilon / 2.0 is indistinguishable from 1.0;