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

Computers are very good at performing repetitive tasks very qinter-base.netkly. In this ar we will learn how to make computer repeat actions either a specified variety of times or till some stopping problem is met.

You are watching: In some cases, a loop control variable does not have to be initialized.

while Loops ( Condition-Controlled Loops )

Both when loops and also do-while loops ( see listed below ) are condition-controlled, definition that they proceed to loop till some condition is met. Both while and also do-while loops alternative between performing actions and testing for the preventing condition. if loops inspect for the stopping condition first, and also may no execute the human body of the loop at all if the condition is originally false. Syntax:

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


int ns = 0; while( i

do-while Loops

do-while loops are specifically like if loops, other than that the test is performed in ~ the finish of the loop fairly than the beginning. This promises that the loop will be carry out at the very least once, which is advantageous for check user input among other things ( see instance below. ) Syntax: perform body; while( problem ); In theory the body can be either a single statement or a block the statements in ~ curly braces , however in practice the curly braces are practically always provided with do-whiles. Example: int month; do printf( "Please go into the month of her birth > " ); scanf( "%d", &month ); when ( month 12 ); note that the over example can be improved by reporting to the user what the difficulty is if month is not in the variety 1 come 12, and also that that could likewise be done using a while loop if month to be initialized come a value that guarantee entering the loop.The complying with diagram shows the difference in between while and also do-while loops. Note that as soon as you enter the loop, the procedure is the same from that point forward:

for Loops

for-loops room counter-controlled, meaning that they are generally used whenever the variety of iterations is recognized in advance. Syntax:


whereby again the body can be one of two people a single statement or a block of statements within curly braces .

Details: The initialization step occurs one time only, before the loop begins. The condition is tested at the beginning of every iteration that the loop. If the condition is true ( non-zero ), climate the body of the loop is executed next. If the condition is false ( zero ), climate the human body is no executed, and also execution continues with the code following the loop. The incrementation wake up AFTER the execution of the body, and also only as soon as the body is executed. Example:

special Notes: The third component of the loop is labeling "incrementation", due to the fact that it usually takes the type of "i++" or something similar. However it have the right to be any legal C/C++ statement, such as "N += 3" or "counter = base + delta". In the example above, the variable i is declared before the loop, and continues to exist after ~ the loop has completed. Friend will additionally see occasions where the loop change is claimed as part of the because that loop, ( in C99 ), in which case the variable exists just within the body of the loop, and also is no much longer valid when the loop completes: for( int i = 0; ns ( In Dev C++ you can specify assistance for C99 by selecting Project->Project alternatives from the menu, and also then choosing the Parameters tab. Under "C compiler", include the line: -std=c99 )

The comma operator

C has actually a comma operator, that basically combines two statements so the they can be thought about as a solitary statement. About the only place this is ever used is in for loops, to either administer multiple initializations or to permit for multiple incrementations. For example: int i, j = 10, sum; for( i = 0, amount = 0; ns

break and continue

break and also continue space two C/C++ statements that enable us come further manage flow within and out the loops. break causes execution to immediately jump the end of the present loop, and proceed with the code adhering to the loop. continue reasons the remainder of the existing iteration that the loop to be skipped, and for execution come recommence through the next iteration. In the case of for loops, the incrementation action will be executed next, followed by the problem test to start the next loop iteration. In the instance of while and do-while loops, execution jumps to the next loop condition test. ( us have also seen break offered to jump the end of switch statements. Continue has no meaning in switch statements. )

Infinite Loops

unlimited loops are loops that repeat forever without stopping. Usually they are brought about by some sort of error, such as the following instance in which the wrong variable is incremented: int i, j; for( ns = 0; i various other times infinite loops serve a beneficial purpose, such together this alternate means of check user input: while( true ) { printf( "Please enter a month from 1 come 12 > " ); scanf( "%d", &month ); if( month > 0 && month

Empty Loops

A common error is to place an extra semi-colon in ~ the finish of the if or for statement, creating an north loop body between the closeup of the door parenthesis and the semi-colon, such as: int i; for( i = 0; i or: int i = 0; while( ns In the case of the while loop displayed above, that is not only empty but likewise infinite. There are some an extremely rare circumstances in i m sorry a programmer will certainly deliberately write an empty loop, most of i beg your pardon are past the limit of this course. ( This is know as a busy loop. ) In this case, the semicolon should be inserted on a line by itself, and plainly commented to suggest that the north loop is deliberate and not one oversight: while( ( error = someFunction( ) ) != 0 ) ; // north loop - does nothing forever, until someFunction returns a zero printf( "error = %d\n", error ); // after ~ the loop. Error should be zero to gain here.

Nested Loops

The code inside a loop can be any kind of valid C code, consisting of other loops. Any type of kind that loop can be nested within of any kind of other kind of loop. Because that loops are typically nested inside of other for loops, for instance to create a an easy multiplication table: const int NROWS = 10; const int NCOLS = 10; for( int r = 0; r some programmers favor to use successive integers i, j, k, l, etc. For usage in nested because that loops. This have the right to be suitable if the mathematiinter-base.net being implemented uses many ijk subscripts. other times it have the right to be less confusing come use alternative variables the are an ext meaningful to the problem at hand, such together the r and also c variables used over to save track of rows and also columns. The limits regarding how deeply loops might be nested is implementation dependent, however is usually too high to be of any concern, other than in situations of extremely complex or incredibly poorly composed programs.

See more: Eric Church Love Your Love The Most Lyrics, Lyrics For Love Your Love The Most By Eric Church

Floating allude Increments within Loops

Engineers and also scientists commonly write iterative program in i beg your pardon a floating point value measures through a selection of worths in tiny increments. Because that example, suppose the "time" variable requirements to change from a low of tMin come a high the tMax in steps of deltaT, whereby all this variables are doubles. The obvious BUT INCORRECT strategy is together follows: for( time = tMin; time for this reason why is this therefore wrong? If deltaT is small and/or the selection is huge ( or both ), the loop may execute for hundreds of iterations. That means that by the end of the loop, time has actually been calculation by the summation of thousands of enhancement operations. Numbers the seem "exact" to united state in decimal form, such together 0.01 are not exact when the computer system stores castle in binary, which method that the value offered for deltaT is yes, really an approximation come the exact value. Thus each enhancement step introduces a very tiny amount of roundoff error, and also by the time you add up thousands of these errors, the complete error can be significant. The correct technique is as follows, if you know the minimum and also maximum values and the desired adjust on each iteration: int nTimes = ( tMax - tMin ) / deltaT + 1; for( int i = 0; ns Or additionally if you recognize the minimum, maximum, and variety of desired iterations: dual deltaT = ( tMax - tMin ) / ( nTimes - 1 ); for( int ns = 0; ns In general there are 4 values that can be supplied to specify stepping v a range - the low end of the range, the high end of the range, the number of step to take, and the increment to take on each action - and also if you know any three that them, then you deserve to calculate the fourth one. The correct loop have to use an integer respond to to complete the loop a given variety of times, and also use the low end of the variety and the increment as displayed to calculate the floating point loop variable at the beginning of every iteration that the loop. for this reason why is that better? The variety of times the the loop executes is now managed by one integer, i m sorry does not have any kind of roundoff error top top incrementation, so over there is no opportunity of performing one too countless or one too few iterations early out to accumulated roundoff. The moment variable is currently calculated indigenous a solitary multiplication and a single addition, which deserve to still present some roundoff error, yet far less than hundreds of additions. wherein does that +1 come from? The +1 is essential in stimulate to include both endpoints the the range. Intend tMax to be 20 and also tMin to be 10, and deltaT were 2. The wanted times would certainly be 10, 12, 14, 16, 18, 20, i m sorry is a total of 6 time values, not 5. ( 5 intervals if you desire to look at it the way. ) ( 20 - 10 ) / 2 yields 5, so you have actually to add the extra 1 to obtain the correct number of times that 6. Another way of looking at this is the if nTimes is the variety of data point out in the range, then nTimes - 1 is the number of gaps in between the data points. Example: interpolate.c is a qinter-base.netk-and-dirty example of interpolating floating allude numbers in a loop, the was whipped increase in 10 minute in class. That is NOT an instance of great code, yet it is an instance of how a qinter-base.netk little program can be offered to check out, play with, or in this situation demonstrate a brand-new or unfamiliar concept. This instance interpolates the function f( x ) = x^3 over the range from -1.0 come 4.0 in actions of 0.5, using three approachs: consistent - take it the typical of the inputs at the end points, evaluate f( mean input ), and assume the duty is constant over the range. Direct - evaluate the role at the endpoints, and then usage a straight interpolation that the endpoint role values in between. Non-Linear - Linearly interpolate the duty inputs end the range, and also at every evaulation point, advice the duty of the interpolated inputs.

When to usage Which Loop ?

If you know ( or deserve to calculate ) how numerous iterations you need, then use a counter-controlled ( for ) loop. Otherwise, if the is necessary that the loop complete at least once prior to checking because that the stopping condition, or if the is not possible or coherent to inspect the stopping condition before the loop has executed at the very least once,then usage a do-while loop. Otherwise use a while loop.


write a regimen that generates a table mirroring the difference between "time1" calculated together "time1 += deltaT" and also "time2" calculated together "time2 = i * deltaT", for iterations indigenous 0 up to an upper limit mentioned by the user. The user should additionally specify a frequency for how generally (s)he wants the results printed in the table. Therefore if they enter 10 for the frequency you need to print outcomes every 10th time v the loop, and also if they get in 100, then print every 100th time through the loop, etc. Hint: usage mod for the to press frequency. Compose a regimen to calculation epsilon, the smallest worth that have the right to be added to 1.0 and still be identified from 1.0. Hint: begin with epsilon same to 1.0, and also then keep dividing it through 2.0 until 1.0 + epsilon / 2.0 is identical from 1.0;