1 / 36

Repetition in the programs

Repetition in the programs. Example 1: Suppose we want to display the consecutive digits: 0,1,2,….9. For doing that adding one to the previous number should be repeated 10 times .

akamu
Download Presentation

Repetition in the programs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Repetition in the programs Example 1: Suppose we want to display the consecutive digits: 0,1,2,….9. For doing that adding one to the previous number should be repeated10 times. Example 2: Mars Observer spacecraft’s mission plan called for seven orbit adjustment maneuvers in order to move from initial orbit to the desired orbit for mapping Mars. The spacecraft would have needed to execute similar sets of instructionsseven times, one set for each maneuver.

  2. Repetition in the programs The questions that determined whether loops are required in the algorithm: • Are there any repeated steps in the algorithm? • If repetition is required, how many times these steps should be repeated? • If the number of repetition is unknown, how long the repeating the steps should be kept? • The answer to question 1 indicates whether algorithm needs loop or not, and the answers to questions 2 and 3 determine which loop structure need to be used

  3. Counting loop (counter-controlled loop) The repetition is managed by a loop control variable whose value represents a count Set loop control variable to an initial value (0) while loop control variable < final value …… increase loop control variable by increment value (1)

  4. /* Loop to Process Seven Spacecraft Maneuvers */ count_mvr = 0; /* no maneuvers done yet */ while (count_mvr < 7) { /* test value of count_mvr */ printf("Number of orbits to next maneuver> "); scanf("%d", &orbits); printf("Orbit period, in hours and fraction of hours> "); scanf("%lf", &period); time to mvr = orbits * period; printf("Time to next maneuver is %6.1f hours\n", time to mvr); count_mvr = count_mvr + 1; /* increment count_mvr */ } printf("All maneuvers complete\n");

  5. count_mvr = 0 Flowchart of While statement count_mvr <7 true false …….. increase count_mvr by 1 Exit loop

  6. Counting loop and while statement Syntax of while statement: while (loop repetition condition) statement Three steps for a loop with a control variable are: • Initialization of loop control variable (if missing loop may repeat 0 or a wrong number of times) • Testing loop control variable (loop will be executed zero times if the condition is initially false) • Updating loop control variable (if missing the loop will execute forever, which is referred to as infinite loop)

  7. Computing a Sum in the Loop accumulator variable printf("Enter number of maneuvers> "); scanf("%d", &num_mvrs); total_time = 0.0; count_mvr = 0; while (count_mvr < num_mvrs) { loop can be repeated for any number printf("Number of orbits to next maneuver> "); scanf("%d", &orbits); printf("Orbit period, in hours and fraction of hours> "); scanf("%lf", &period); time_to_mvr = orbits * period; printf("Time to next maneuver is %6.1f hours\n\n", time_to_mvr); count_mvr = count_mvr + 1; total_time = total_time + time_to_mvr; accumulator increases with each loop iteration } printf("All maneuvers complete\n"); printf("Total time spent in maneuver phase is %6.1f hours\n", total_time); printing the value of accumulator

  8. Computing a Product in a Loop The loop control variable holds the result of the computation that is performed in the loop product = 1; while (product < 10000) { printf(“%d\n”, product); /* Display product so far */ printf(“Enter next item> “); scanf(“%d”, &item); product = product * item; /* Update product */ }

  9. Compound Assignment Operators Instead of variable = variable op expression; variable op= expression; can be used for +, -, *, /, and % operators. For example: ct = ct + 1; ct += 1; time = time – 1; time -= 1; product = product * data; product *= data; n = n * (x + 1); n *= x+1;

  10. The for Statement • Syntax: for (initialization expression; loop repetition condition; update expression) statement Example: for (count_star = 0; count_star < 20; count_star+=1 ) printf(“*”);

  11. The for Statement • Combines the three loop control steps of initialization, testing and update in one place (more complex than while) • Provides a consistent location for each of loop initialization, testing and update (more popular that while among the C programmers in industry) • Can be used to count up or down by any interval

  12. for (count_mvr = 0; /* initialization */ count_mvr < num_mvrs; /* loop condition */ count_mvr += 1){/* update */ printf("Number of orbits to next maneuver> "); scanf("%d", &orbits); printf("Orbit period, in hours and fraction of hours>"); scanf("%lf", &period); time_to_mvr = orbits * period; printf("Time to next maneuver is %6.1f hours\n\n", time_to_mvr); total_time += time_to_mvr; }

  13. #include <stdio.h> int main(void) { int time, start; printf("Enter starting time (an integer) in seconds> "); scanf("%d", &start); printf("\nBegin countdown\n"); for (time = start; time > 0; time -= 1) { printf("T - %d\n", time); } printf("Blast-off!\n"); return (0); } • Enter starting time (an integer) in seconds> 5 Begin countdown T - 5 T - 4 T - 3 T - 2 T - 1 Blast-off!

  14. /* Conversion of Celsius to Fahrenheit temperatures */ #include <stdio.h> /* Constant macros */ #define CBEGIN 10 #define CLIMIT -5 #define CSTEP 5 int main(void) { /* Variable declarations */ int celsius; double fahrenheit; /* Display the table heading */ printf(" Celsius Fahrenheit\n");

  15. /* Display the table */ for (celsius = CBEGIN; celsius >= CLIMIT; celsius -= CSTEP) { fahrenheit = 1.8 * celsius + 32.0; printf(" %3d %9.2f\n", celsius, fahrenheit); } return (0); } Celsius Fahrenheit 10 50.00 5 41.00 0 32.00 -5 23.00

  16. Increment and Decrement operators Suppose i =2 and j = ? • Prefix form: j= ++i; increments i and then use it => i=3,j=3 • Postfix form: j= i++; uses i and then increment it => i=3, j=2 Example : for n=4: printf ( %d,--n) => 3 printf ( %d,n--) => 4 Self-Check 5.4.4: for i = 3 and j = 9 what are the results of n = ++i * --j; m = i + j--; p = i + j;

  17. Conditional loops with for statement printf("Number of barrels currently in tank> "); scanf("%lf", &start_supply); for (current = start_supply; current >= min_supply; current -= remov_brls) { printf("%.2f barrels are available.\n\n", current); printf("Enter number of gallons removed> "); scanf("%lf", &remov_gals); remov_brls = remov_gals / GALS_PER_BRL; printf("After removal of %.2f gallons (%.2f barrels),\n", remov_gals, remov_brls); }

  18. Sentinel-Controlled Loop Correct Sentinel loop Incorrect Sentinel loop 1. sum=0 sum=0 2. get score while (score!=SENTINEL) 3. while (score! { =SENTINEL){ get score 4 . sum+=score sum+=score 5. Get score } }

  19. Sentinel-Controlled Loop /* Compute the sum of a list of exam scores. */ #include <stdio.h> #define SENTINEL -99 int main(void) { int sum = 0, /* sum of scores input so far */ score; /* current score */ printf("Enter first score (or %d to quit)> ", SENTINEL); for (scanf("%d", &score); What is the result if score entered as 7o? score != SENTINEL; scanf("%d", &score)) { sum += score; printf("Enter next score (%d to quit)> ", SENTINEL); } printf("\nSum of exam scores is %d\n", sum); return (0); }

  20. /* Batch Version of Sum of Exam Scores Program */ #include <stdio.h> /* defines fopen, fclose, fscanf, fprintf, and EOF */ int main(void) { FILE *inp; /* input file pointer */ int sum = 0, /* sum of scores input so far */ score, /* current score */ input_status; /* status value returned by fscanf */ inp = fopen("scores.dat", "r"); printf("Scores\n"); for (input_status = fscanf(inp, "%d", &score); input_status != EOF; input_status = fscanf(inp, "%d", &score)) { printf("%5d\n", score); sum += score; } printf("\nSum of exam scores is %d\n", sum); fclose(inp); return (0); }

  21. Avoiding Infinite Loops on Faulty Data • To avoid infinite loop when processing faulty data the loop in the “Sum exam score” program can be modified as the follows: …… for (input_status = fscanf(inp, "%d", &score); input_status == 1; input_status = fscanf(inp, "%d", &score)) { printf("%5d\n", score); sum += score; } if (input_status == EOF) printf(“Sum of scores is %d\n”, sum); else printf(“Error in input, bad character”); …… • Note that in case of reaching EOF input_status is negative and in case of faulty data input_status is zero otherwise it is always 1.

  22. /* Finds the product of nonzero data. */ #include <stdio.h> #define SENT -9999.0 int main(void) { double product = 1.0; /* product so far of nonzero data */ int status; /* status of input operation */ double data_item; /* current data value */ printf("Enter a data item (%.1f to quit)> ", SENT); for (status = scanf("%lf", &data_item); status == 1 && data_item != SENT; status = scanf("%lf", &data_item)) { if (data_item != 0) /* if statement is nested within the loop */ product *= data_item; printf("Enter next data item (%.1f to quit)> ", SENT); } if (status != 1) printf("Error in data list\n"); else /* The result will be shown for the correct input data */ printf("The product of nonzero data is %8.3f.\n", product); return (0); }

  23. Nested Loops #include <stdio.h> int main(void) { int i, j; /* loop control variables */ printf(" I J\n"); /* prints column labels */ Program output for (i = 1; i < 4; ++i) { /* outer for loop */ printf("Outer %6d\n", i); for (j = 0; j < i; ++j) { /* inner loop */ printf(" Inner%9d\n", j); } /* end of inner loop */ } /* end of outer loop */ return (0); } I J Outer 1 Inner 0 Outer 2 Inner 0 Inner 1 Outer 3 Inner 0 Inner 1 Inner 2

  24. The do-while Statement • The first iteration of the loop body occurs unconditionally (number of repetition is 1 or more instead of 0 or more in the while statement) • All the statements in the loop are processed identically • Can be used efficiently for checking the valid input data

  25. The do-while Statement • SYNTAX: do statement while ( loop repetition condition) • Example do /* Finding the first even number input */ status = scanf(“%d” &num); while (status >0 && num %2 !=0);

  26. Flowchart of do-while when using for input validation value not in desired range prompt user to get a value for checking valid input true false

  27. do-while When Using for Input Validation /* Gives an error message on input of an invalid data type */ printf("Enter minimum and maximum valid values> "); scanf("%d%d", &n_min, &n_max); do { printf("Enter an integer in the range from %d to %d inclusive> ", n_min, n_max); status = scanf("%d", &inval); if (status == 1) { error = 0; } else { error = 1; scanf("%c", &skip_ch); printf("\nInvalid character>>%c>> Skipping rest of line.\n", skip_ch); do { scanf("%c", &skip_ch); } while (skip_ch != '\n'); } /* Exit the loop only if the entry is valid */ } while (error || inval < n_min || inval > n_max);

  28. Flag_conrolled Validation Loop do { error = 0; /* No errors detected yet */ /* Get a fraction from the user */ printf("Enter a common fraction as two integers separated by "); printf("a slash\nand press <enter>\n> "); status = scanf("%d%c%d", &num, &slash, &den); /* Validate the fraction */ if (status < 3) { error = 1; printf("Input invalid-please read directions carefully\n"); } else if (slash != '/') { error = 1; printf("Input invalid-separate numerator and denominator"); printf(" by a slash (/)\n"); } else if (den <= 0) { error = 1; printf("Input invalid-denominator must be positive\n"); } do {/* Discard extra input characters */ scanf("%c", &discard); } while (discard != '\n'); } while (error); A flag (type int variable) is used as a condition of the while

  29. Case Study: Computing Radiation Level • Problem: ..Determine how long does it take before the radiation is down to a safe level of 0.466 millirem a day. Use a chart to display radiation level for every three days with the message unsafe and safe after every line. The program should stop just before the radiation level is one-tenth of the safe level. • Analysis: data requirements: Constants (SAFE_RAD, SAFETY_FACT), Input (init_radiation), Output (day, radiation_lev)

  30. Case study: Computing Radiation Level • Design :Algorithm • Initialize day to zero. • Compute the stopping level • Prompt user to enter the initial radiation level • Compute day number and radiation level every 3 days for the levels that exceed the stopping radiation level 4.1 Initialize radiation_lev to init_radiation 4.2 while radiation_lev exceeds min_radiation 4.3 Display the value of day, radiation_lev, and the string “Unsafe” or “Safe” 4.4 Add 3 to the value of day 4.5 Compute radiation_lev for the next period Can we Change it to the for loop?

  31. Case study: Computing Radiation Level • Implementation: ............................ ./* Prompts user to enter initial radiation level */ printf("Enter the radiation level (in millirems)> "); scanf("%lf", &init_radiation); /* Displays table */ printf("\n Day Radiation Status\n (millirems)\n"); for (radiation_lev = init_radiation; radiation_lev > min_radiation; radiation_lev /= 2.0) { if (radiation_lev > SAFE_RAD) printf(" %3d %9.4f Unsafe\n", day, radiation_lev); else printf(" %3d %9.4f Safe\n", day, radiation_lev); day += 3; } return (0); …………………..

  32. Case study: Computing Radiation Level • Testing : Program result: Enter the radiation level (in millirems)> 150.0 Day Radiation Status (millirems) 0 150.0000 Unsafe Initial value 3 75.0000 Unsafe 75 is 150 / 2, it shows calculation is ok 6 37.5000 Unsafe 9 18.7500 Unsafe The number of days increases by 3 12 9.3750 Unsafe 15 4.6875 Unsafe 18 2.3438 Unsafe 21 1.1719 Unsafe 24 0.5859 Unsafe 27 0.2930 Safe 30 0.1465 Safe Ending value, shows the loop exited correctly

  33. How to Debug and Test Programs • Using debugger programs: Quincy debugger • Debugging without a Debugger • Diagnostic call to printf #define DEBUG 1 if (DEBUG) printf(“***score is %d, sum is %d\n”,score,sum) ; fflush(stdout); /* copying the contents of buffer to associated output device */

  34. Debugging without a Debugger 2- Off-by-One loop errors: • Checking the loop repetition. For example: for (count =0; count <=n ;++count) sum+=count /*executes n+1 times*/ for (count =0; count <n ;++count) sum+=count /*executes n times */ • Checking the boundaries: initial value, end value and tracing loop with a small loop control variable

  35. Common Programming Errors • Confusion between if , while and for • Forgetting to put braces for more than two statements in the loop body • Making mistake when using tests for inequality to control loop repetition: while (balance !=0.0) instead of while (balance>0.0) The first while, repeats for negative balance

  36. Common Programming Errors • Using = instead of == in the loop repetition condition produces infinite loops: do { …. } while (again=1); • do-while can be used when there is no possibility of zero loop • Confusion in compound assignment operators: a *= b + c is a = a * (b+ c) it is not a = a * b + c • Confusion in increment and decrement operators by ignoring operator’s side effect of changing the value of the operand

More Related