This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 1 1 Loop techniques s Cumulative sum s Fencepost loops 2 Cumulative sum 3 Adding many numbers s Consider the following code: printf("Type a number: "); int num1; scanf("%d", &num1); printf("Type a number: "); int num2; scanf("%d", &num2); printf("Type a number: "); int num3; scanf("%d", &num3); int sum = num1 + num2 + num3; printf("The sum is %d\n", sum); s Any ideas to improve the code? 4 Cumulative sum s The variables num1 , num2 and num3 can be reduced to a single variable: int num; int sum = 0; printf("Type a number: "); scanf("%d", &num); sum += num; printf("Type a number: "); scanf("%d", &num); sum += num; printf("Type a number: "); scanf("%d", &num); sum += num; printf("The sum is " + sum); s cumulative sum : A variable that keeps a suminprogress and is updated many times until the task of summing is finished. b The variable sum in the above code represents a cumulative sum. 5 s How could we modify the code to sum 100 numbers? b Creating 100 copies of the same code would be redundant. s An incorrect solution: for (int i = 1; i <= 100; i++) { int sum = 0; printf("Type a number: "); int num; scanf("%d", &num); sum += num; } printf("The sum is %d\n", sum); s How could we modify the code to sum 100 numbers? b Creating 100 copies of the same code would be redundant. s An incorrect solution: for (int i = 1; i <= 100; i++) { int sum = 0; printf("Type a number: "); int num; scanf("%d", &num); sum += num; } printf("The sum is %d\n", sum); // sum out of scope Cumulative sum 6 Cumulative sum loop s A correct version: int sum = 0; for (int i = 1; i <= 100; i++) {...
View
Full
Document
 Spring '10
 Benson
 Summation, printf, cumulative sum, Fencepost loop

Click to edit the document details