0% found this document useful (0 votes)
8 views114 pages

Lecture Loops

Uploaded by

atif83837
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views114 pages

Lecture Loops

Uploaded by

atif83837
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

Introduction

Computer Science I
For Loops

While Loops
Loops
Other Loops

Pitfalls

Exercises
Dr. Chris Bourke
[email protected]
Outline

Introduction

For Loops
1. Introduction
While Loops

Other Loops
2. For loops
Pitfalls 3. While loops
Exercises
4. Other Loops & Issues
5. Pitfalls
6. Exercises
Introduction

For Loops

While Loops

Other Loops

Pitfalls
Part I: Introduction
Exercises
Motivation & Introduction to Loop Control Structures
Motivation

Introduction

For Loops

While Loops

Other Loops Need a way to repeatedly execute a block of code


Pitfalls

Exercises
Motivation

Introduction

For Loops

While Loops

Other Loops Need a way to repeatedly execute a block of code


Pitfalls Process data: apply an operation to each piece of data
Exercises
Motivation

Introduction

For Loops

While Loops

Other Loops Need a way to repeatedly execute a block of code


Pitfalls Process data: apply an operation to each piece of data
Exercises
Repeat an operation until some condition is satisfied
Loops

Introduction
A loop allows us to repeatedly execute a block of code while some condition is
For Loops
satisfied
While Loops

Other Loops

Pitfalls

Exercises
Loops

Introduction
A loop allows us to repeatedly execute a block of code while some condition is
For Loops
satisfied
While Loops

Other Loops While some boolean expression or condition evaluates to true, the loop will
Pitfalls continue to execute
Exercises
Loops

Introduction
A loop allows us to repeatedly execute a block of code while some condition is
For Loops
satisfied
While Loops

Other Loops While some boolean expression or condition evaluates to true, the loop will
Pitfalls continue to execute
Exercises
Once the condition is no longer satisfied, the loop terminates its execution
Loops

Introduction
A loop allows us to repeatedly execute a block of code while some condition is
For Loops
satisfied
While Loops

Other Loops While some boolean expression or condition evaluates to true, the loop will
Pitfalls continue to execute
Exercises
Once the condition is no longer satisfied, the loop terminates its execution
Each time a loop executes is referred to as an iteration
Loops

Introduction
A loop allows us to repeatedly execute a block of code while some condition is
For Loops
satisfied
While Loops

Other Loops While some boolean expression or condition evaluates to true, the loop will
Pitfalls continue to execute
Exercises
Once the condition is no longer satisfied, the loop terminates its execution
Each time a loop executes is referred to as an iteration
Different types of loops
Loops

Introduction
A loop allows us to repeatedly execute a block of code while some condition is
For Loops
satisfied
While Loops

Other Loops While some boolean expression or condition evaluates to true, the loop will
Pitfalls continue to execute
Exercises
Once the condition is no longer satisfied, the loop terminates its execution
Each time a loop executes is referred to as an iteration
Different types of loops
Components of a loop
Loop Components

Introduction A loop has several main components:


For Loops

While Loops
1 An initialization statement – a statement that indicates how the loop begins
Other Loops

Pitfalls

Exercises
Loop Components

Introduction A loop has several main components:


For Loops

While Loops
1 An initialization statement – a statement that indicates how the loop begins
Other Loops 2 A continuation condition – a boolean statement that specifies whether the
Pitfalls loop should continue executing
Exercises
Loop Components

Introduction A loop has several main components:


For Loops

While Loops
1 An initialization statement – a statement that indicates how the loop begins
Other Loops 2 A continuation condition – a boolean statement that specifies whether the
Pitfalls loop should continue executing
Exercises
3 An iteration statement – a statement that makes progress toward the
termination of the loop
Loop Components

Introduction A loop has several main components:


For Loops

While Loops
1 An initialization statement – a statement that indicates how the loop begins
Other Loops 2 A continuation condition – a boolean statement that specifies whether the
Pitfalls loop should continue executing
Exercises
3 An iteration statement – a statement that makes progress toward the
termination of the loop
4 Loop Body – the block of code that gets executed for each iteration
Loop Components

Introduction A loop has several main components:


For Loops

While Loops
1 An initialization statement – a statement that indicates how the loop begins
Other Loops 2 A continuation condition – a boolean statement that specifies whether the
Pitfalls loop should continue executing
Exercises
3 An iteration statement – a statement that makes progress toward the
termination of the loop
4 Loop Body – the block of code that gets executed for each iteration

Termination Condition – negation of the continuation condition


Simple Example

Introduction

For Loops Printout numbers 1 through 10:


While Loops

Other Loops
1 Initialize a variable i to 1
Pitfalls 2 While the variable i’s value is less than or equal to 10. . .
Exercises
3 Print i
4 Increment i by adding 1 to it
5 Go to step 2
Flow Diagram

Initialization:
i ← 1

Introduction

For Loops

While Loops Continuation: false


i ≤ 10?
Other Loops

Pitfalls
true
Exercises
loop body

Iteration:
repeat i ← (i + 1)

remaining program
Introduction

For Loops
Increment
Operators

While Loops

Other Loops Part II: For Loops


Pitfalls

Exercises
For Loop

Introduction

For Loops
Increment
Operators A a for loop uses the keyword for
While Loops

Other Loops

Pitfalls

Exercises
For Loop

Introduction

For Loops
Increment
Operators A a for loop uses the keyword for
While Loops
All three elements: initialization, continuation and increment are
Other Loops

Pitfalls

Exercises
For Loop

Introduction

For Loops
Increment
Operators A a for loop uses the keyword for
While Loops
All three elements: initialization, continuation and increment are
Other Loops
placed on the same line
Pitfalls

Exercises
For Loop

Introduction

For Loops
Increment
Operators A a for loop uses the keyword for
While Loops
All three elements: initialization, continuation and increment are
Other Loops
placed on the same line
Pitfalls
enclosed within parentheses
Exercises
For Loop

Introduction

For Loops
Increment
Operators A a for loop uses the keyword for
While Loops
All three elements: initialization, continuation and increment are
Other Loops
placed on the same line
Pitfalls
enclosed within parentheses
Exercises
Loop body is denoted using curly brackets
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops

Pitfalls

Exercises
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops Initialization, executed only once before the loop begins
Pitfalls

Exercises
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops Initialization, executed only once before the loop begins
Pitfalls
Continuation condition, evaluated before each iteration
Exercises
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops Initialization, executed only once before the loop begins
Pitfalls
Continuation condition, evaluated before each iteration
Exercises
Iteration executed at the end of each loop
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops Initialization, executed only once before the loop begins
Pitfalls
Continuation condition, evaluated before each iteration
Exercises
Iteration executed at the end of each loop
New syntax: i++
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops Initialization, executed only once before the loop begins
Pitfalls
Continuation condition, evaluated before each iteration
Exercises
Iteration executed at the end of each loop
New syntax: i++
Loop body denoted with curly brackets
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops Initialization, executed only once before the loop begins
Pitfalls
Continuation condition, evaluated before each iteration
Exercises
Iteration executed at the end of each loop
New syntax: i++
Loop body denoted with curly brackets
Correct usage of semicolons
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops Initialization, executed only once before the loop begins
Pitfalls
Continuation condition, evaluated before each iteration
Exercises
Iteration executed at the end of each loop
New syntax: i++
Loop body denoted with curly brackets
Correct usage of semicolons
Style elements
For Loop

1 int i;
2 for(i=1; i<=10; i++) {
Introduction 3 printf("i = %d\n", i);
For Loops 4 }
Increment
Operators

While Loops

Other Loops Initialization, executed only once before the loop begins
Pitfalls
Continuation condition, evaluated before each iteration
Exercises
Iteration executed at the end of each loop
New syntax: i++
Loop body denoted with curly brackets
Correct usage of semicolons
Style elements
Demonstration
Increment Operators

Introduction

For Loops
Increment
Several common “short-hand” operators for increment/decrement:
Operators

While Loops

Other Loops

Pitfalls

Exercises
Increment Operators

Introduction

For Loops
Increment
Several common “short-hand” operators for increment/decrement:
Operators

While Loops
i++ adds 1 to the variable i
Other Loops

Pitfalls

Exercises
Increment Operators

Introduction

For Loops
Increment
Several common “short-hand” operators for increment/decrement:
Operators

While Loops
i++ adds 1 to the variable i
Other Loops

Pitfalls
i-- subtracts 1 from the variable i
Exercises
Increment Operators

Introduction

For Loops
Increment
Several common “short-hand” operators for increment/decrement:
Operators

While Loops
i++ adds 1 to the variable i
Other Loops

Pitfalls
i-- subtracts 1 from the variable i
Exercises “Equivalent” to i = i + 1 and i = i - 1
Increment Operators

Introduction

For Loops
Increment
Several common “short-hand” operators for increment/decrement:
Operators

While Loops
i++ adds 1 to the variable i
Other Loops

Pitfalls
i-- subtracts 1 from the variable i
Exercises “Equivalent” to i = i + 1 and i = i - 1
Honorable mention: prefix versions ++i and --i
More Increment Operators

Introduction

For Loops
Increment
You can also use compound increment operators:
Operators

While Loops

Other Loops

Pitfalls

Exercises
More Increment Operators

Introduction

For Loops
Increment
You can also use compound increment operators:
Operators

While Loops
a += 10; adds 10 to the variable a
Other Loops

Pitfalls

Exercises
More Increment Operators

Introduction

For Loops
Increment
You can also use compound increment operators:
Operators

While Loops
a += 10; adds 10 to the variable a
Other Loops
a -= 5; subtracts 5 from the variable a
Pitfalls

Exercises
More Increment Operators

Introduction

For Loops
Increment
You can also use compound increment operators:
Operators

While Loops
a += 10; adds 10 to the variable a
Other Loops
a -= 5; subtracts 5 from the variable a
Pitfalls

Exercises a *= 2; multiplies a by 2
More Increment Operators

Introduction

For Loops
Increment
You can also use compound increment operators:
Operators

While Loops
a += 10; adds 10 to the variable a
Other Loops
a -= 5; subtracts 5 from the variable a
Pitfalls

Exercises a *= 2; multiplies a by 2
a /= 3; divides a by 3
More Examples

1 //print numbers 10, 20, 30, ... 100


2 int i;
Introduction
3 for(i=10; i<=100; i+=10) {
For Loops
Increment
4 printf("%d\n", i);
Operators
5 }
While Loops
6 printf("%d\n", i);
Other Loops
7
Pitfalls
8 int n = 10;
Exercises 9 int sum = 0; //without initialization, no default value
10 for(i=1; i<n; i++) {
11 //sum = sum + i;
12 sum += i;
13 }
14 printf("sum of integers 1..%d = %d\n", n, sum);
Introduction

For Loops

While Loops

Other Loops

Pitfalls Part III: While Loops


Exercises
While Loops

Introduction

For Loops

While Loops
A a while loop uses the keyword while
Other Loops

Pitfalls

Exercises
While Loops

Introduction

For Loops

While Loops
A a while loop uses the keyword while
Other Loops

Pitfalls Three elements (initialization, continuation, increment) are not on the same
Exercises line
While Loops

Introduction

For Loops

While Loops
A a while loop uses the keyword while
Other Loops

Pitfalls Three elements (initialization, continuation, increment) are not on the same
Exercises line
Same behavior: continuation condition is checked at the start of the loop
While Loops

1 int i = 1;
Introduction
2 while(i <= 10) {
For Loops 3 printf("i = %d\n", i);
While Loops 4 i++;
Other Loops 5 }
Pitfalls

Exercises
While Loops

1 int i = 1;
Introduction
2 while(i <= 10) {
For Loops 3 printf("i = %d\n", i);
While Loops 4 i++;
Other Loops 5 }
Pitfalls

Exercises

Initialization is before and outside the loop structure


While Loops

1 int i = 1;
Introduction
2 while(i <= 10) {
For Loops 3 printf("i = %d\n", i);
While Loops 4 i++;
Other Loops 5 }
Pitfalls

Exercises

Initialization is before and outside the loop structure


while statement contains only the continuation condition
While Loops

1 int i = 1;
Introduction
2 while(i <= 10) {
For Loops 3 printf("i = %d\n", i);
While Loops 4 i++;
Other Loops 5 }
Pitfalls

Exercises

Initialization is before and outside the loop structure


while statement contains only the continuation condition
Increment is done inside the loop body
While Loops

1 int i = 1;
Introduction
2 while(i <= 10) {
For Loops 3 printf("i = %d\n", i);
While Loops 4 i++;
Other Loops 5 }
Pitfalls

Exercises

Initialization is before and outside the loop structure


while statement contains only the continuation condition
Increment is done inside the loop body
Take care: order inside the loop matters
While Loops

Introduction

For Loops

While Loops 1 int i = 1;


Other Loops 2 while(i <= 10) {
Pitfalls 3 i++;
Exercises 4 printf("i = %d\n", i);
5 }
Why Multiple Loops?

Introduction
Why do we have multiple loop control structures?
For Loops

While Loops

Other Loops

Pitfalls

Exercises
Why Multiple Loops?

Introduction
Why do we have multiple loop control structures?
For Loops

While Loops
Any for loop can be rewritten as a while loop and vice versa
Other Loops

Pitfalls

Exercises
Why Multiple Loops?

Introduction
Why do we have multiple loop control structures?
For Loops

While Loops
Any for loop can be rewritten as a while loop and vice versa
Other Loops

Pitfalls
Syntactic sugar, flexibility, variety
Exercises
Why Multiple Loops?

Introduction
Why do we have multiple loop control structures?
For Loops

While Loops
Any for loop can be rewritten as a while loop and vice versa
Other Loops

Pitfalls
Syntactic sugar, flexibility, variety
Exercises Generally, the situation/context will inform how “natural” each loop is
Why Multiple Loops?

Introduction
Why do we have multiple loop control structures?
For Loops

While Loops
Any for loop can be rewritten as a while loop and vice versa
Other Loops

Pitfalls
Syntactic sugar, flexibility, variety
Exercises Generally, the situation/context will inform how “natural” each loop is
Use for loops when the number of iterations is known up front
Why Multiple Loops?

Introduction
Why do we have multiple loop control structures?
For Loops

While Loops
Any for loop can be rewritten as a while loop and vice versa
Other Loops

Pitfalls
Syntactic sugar, flexibility, variety
Exercises Generally, the situation/context will inform how “natural” each loop is
Use for loops when the number of iterations is known up front
Use while loops when you don’t know how many iterations will be
executed/they may vary depending on the variable values
While Loop Scenario

Introduction

For Loops
Example: write a loop (or loops) to normalize a number:
While Loops

89237.49283 → 8.923749283 × 104


Other Loops

Pitfalls

Exercises
321.321 → 3.21321 × 102
0.00432 → 4.32 × 10−3
While Loop Scenario

1 double x = 89237.49283;
Introduction 2 int counter = 0;
For Loops 3 while(x > 10) {
While Loops
4 x /= 10.0;
Other Loops
5 counter++;
Pitfalls
6 }
7 printf("x = %f * 10^%d\n", x, counter);
Exercises
8 while(x < 1) {
9 x *= 10.0;
10 counter--;
11 }
12 printf("x = %f * 10^%d\n", x, counter);
13 return 0;
Introduction

For Loops

While Loops

Other Loops

Pitfalls Part IV: Other Issues & Types of Loops


Exercises
Loop Variable Scoping

Introduction

For Loops For loop examples declared the iteration variable before the loop
While Loops

Other Loops 1 int i;


Pitfalls 2 for(i=0; i<=10; i++) {
Exercises 3 ...
4 }
Loop Variable Scoping

Introduction

For Loops For loop examples declared the iteration variable before the loop
While Loops

Other Loops 1 int i;


Pitfalls 2 for(i=0; i<=10; i++) {
Exercises 3 ...
4 }

The scope of i lasted after the loop


Loop Variable Scoping

Introduction
Many modern languages and newer versions of C (C99) allow a loop-scoped
For Loops variable declaration:
While Loops

Other Loops
1 for(int i=0; i<=10; i++) {
2 ...
Pitfalls
3 }
Exercises
Loop Variable Scoping

Introduction
Many modern languages and newer versions of C (C99) allow a loop-scoped
For Loops variable declaration:
While Loops

Other Loops
1 for(int i=0; i<=10; i++) {
2 ...
Pitfalls
3 }
Exercises

Scope of i is limited to the loop


Loop Variable Scoping

Introduction
Many modern languages and newer versions of C (C99) allow a loop-scoped
For Loops variable declaration:
While Loops

Other Loops
1 for(int i=0; i<=10; i++) {
2 ...
Pitfalls
3 }
Exercises

Scope of i is limited to the loop


If you use this modern style, you must compile with:
gcc -std=c99 or
c99
Flag-Controlled Loops

Instead of a continuation condition, we could use a boolean “flag” variable

Introduction

For Loops

While Loops

Other Loops

Pitfalls

Exercises
Flag-Controlled Loops

Instead of a continuation condition, we could use a boolean “flag” variable


Most commonly used with while loops
Introduction

For Loops 1 int flag = 1;


2 while(flag) {
While Loops
3 ...
Other Loops 4 if(<some complex logic>) {
Pitfalls 5 flag = 0;
6 }
Exercises
7 }
Flag-Controlled Loops

Instead of a continuation condition, we could use a boolean “flag” variable


Most commonly used with while loops
Introduction

For Loops 1 int flag = 1;


2 while(flag) {
While Loops
3 ...
Other Loops 4 if(<some complex logic>) {
Pitfalls 5 flag = 0;
6 }
Exercises
7 }

Sometimes, people use break to break out instead:


1 while(1) {
2 ...
3 if(<some complex logic>) {
4 break;
5 }
6 }
Do-While Loops

Introduction Do-while loops check the continuation condition at the end of the loop
For Loops

While Loops

Other Loops

Pitfalls

Exercises
Do-While Loops

Introduction Do-while loops check the continuation condition at the end of the loop
For Loops
Consequence: they always execute at least once
While Loops

Other Loops

Pitfalls

Exercises
Do-While Loops

Introduction Do-while loops check the continuation condition at the end of the loop
For Loops
Consequence: they always execute at least once
While Loops

Other Loops
Example:
Pitfalls
1 int i = 0;
Exercises
2 do {
3 i++;
4 print("i = %d\n", i);
5 } while(i < 10);
For Each Loops

Introduction

For Loops

While Loops

Other Loops Many languages support “for each” loops


Pitfalls

Exercises
For Each Loops

Introduction

For Loops

While Loops

Other Loops Many languages support “for each” loops


Pitfalls Used to iterate over “collections” (arrays, sets, lists, etc.)
Exercises
For Each Loops

Introduction

For Loops

While Loops

Other Loops Many languages support “for each” loops


Pitfalls Used to iterate over “collections” (arrays, sets, lists, etc.)
Exercises
Not supported in C
Nesting Loops

Loops can be written inside of other loops


Introduction

For Loops

While Loops

Other Loops

Pitfalls

Exercises
Nesting Loops

Loops can be written inside of other loops


Introduction Called “nesting” or nested loops
For Loops

While Loops

Other Loops

Pitfalls

Exercises
Nesting Loops

Loops can be written inside of other loops


Introduction Called “nesting” or nested loops
For Loops Very common when iterating over matrices/tables of data
While Loops

Other Loops

Pitfalls

Exercises
Nesting Loops

Loops can be written inside of other loops


Introduction Called “nesting” or nested loops
For Loops Very common when iterating over matrices/tables of data
While Loops
For each row, then for each column in the row
Other Loops

Pitfalls

Exercises
Nesting Loops

Loops can be written inside of other loops


Introduction Called “nesting” or nested loops
For Loops Very common when iterating over matrices/tables of data
While Loops
For each row, then for each column in the row
Other Loops

Pitfalls Example:
Exercises
1 int i, j;
2 for(i=1; i<=10; i++) {
3 for(j=1; j<=10; j++) {
4 printf("%d\n", (i+j));
5 }
6 }
Introduction

For Loops

While Loops

Other Loops

Pitfalls
Part V: Pitfalls
Exercises
Common Errors & Misconceptions
Pitfall
Improper Increment

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops 2 while(i <= 10) {
Other Loops 3 printf("%d\n", i);
Pitfalls 4 }
Exercises
Pitfall
Improper Increment

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops 2 while(i <= 10) {
Other Loops 3 printf("%d\n", i);
Pitfalls 4 }
Exercises

Results in an infinite loop


Pitfall
Improper Increment

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops 2 while(i <= 10) {
Other Loops 3 printf("%d\n", i);
Pitfalls 4 }
Exercises

Results in an infinite loop


There is no increment/progress toward the termination condition
Pitfall
Improper Increment

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops 2 while(i <= 10) {
Other Loops 3 printf("%d\n", i);
Pitfalls 4 }
Exercises

Results in an infinite loop


There is no increment/progress toward the termination condition
To kill a command line program: control-C
Pitfall
Misplaced Semicolon

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops
2 while(i <= 10); {
Other Loops
3 printf("%d\n", i);
Pitfalls
4 i++;
5 }
Exercises
Pitfall
Misplaced Semicolon

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops
2 while(i <= 10); {
Other Loops
3 printf("%d\n", i);
Pitfalls
4 i++;
5 }
Exercises

Results in an infinite loop


Pitfall
Misplaced Semicolon

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops
2 while(i <= 10); {
Other Loops
3 printf("%d\n", i);
Pitfalls
4 i++;
5 }
Exercises

Results in an infinite loop


Extraneous semicolon, similar to conditional pitfall
Pitfall
Misplaced Semicolon

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops
2 while(i <= 10); {
Other Loops
3 printf("%d\n", i);
Pitfalls
4 i++;
5 }
Exercises

Results in an infinite loop


Extraneous semicolon, similar to conditional pitfall
Empty loop body
Pitfall
Bad Coding Style

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops 2 while(i <= 10)
Other Loops 3 printf("%d\n", i);
Pitfalls 4 i++;
Exercises
Pitfall
Bad Coding Style

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops 2 while(i <= 10)
Other Loops 3 printf("%d\n", i);
Pitfalls 4 i++;
Exercises

Results in an infinite loop


Pitfall
Bad Coding Style

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops 2 while(i <= 10)
Other Loops 3 printf("%d\n", i);
Pitfalls 4 i++;
Exercises

Results in an infinite loop


Missing brackets means loop body is only the next line
Pitfall
Bad Coding Style

Consider the following code:


Introduction

For Loops 1 int i = 1;


While Loops 2 while(i <= 10)
Other Loops 3 printf("%d\n", i);
Pitfalls 4 i++;
Exercises

Results in an infinite loop


Missing brackets means loop body is only the next line
Always include curly brackets even if they are not necessary!
Pitfall
Off-By-One Errors

Introduction

For Loops
Initialization/continuation must be considered carefully
While Loops

Other Loops

Pitfalls

Exercises
Pitfall
Off-By-One Errors

Introduction

For Loops
Initialization/continuation must be considered carefully
While Loops

Other Loops
Loops may be off-by-one iteration (start or end)
Pitfalls

Exercises
Pitfall
Off-By-One Errors

Introduction

For Loops
Initialization/continuation must be considered carefully
While Loops

Other Loops
Loops may be off-by-one iteration (start or end)
Pitfalls Zune Bug: December 31st, 2008
Exercises
Pitfall
Off-By-One Errors

Introduction

For Loops
Initialization/continuation must be considered carefully
While Loops

Other Loops
Loops may be off-by-one iteration (start or end)
Pitfalls Zune Bug: December 31st, 2008
Exercises
Thousands of Zunes froze for 24 hours
Pitfall
Off-By-One Errors

Introduction

For Loops
Initialization/continuation must be considered carefully
While Loops

Other Loops
Loops may be off-by-one iteration (start or end)
Pitfalls Zune Bug: December 31st, 2008
Exercises
Thousands of Zunes froze for 24 hours
2008 was a leap year: 366 days
Pitfall
Off-By-One Errors

Introduction

For Loops
Initialization/continuation must be considered carefully
While Loops

Other Loops
Loops may be off-by-one iteration (start or end)
Pitfalls Zune Bug: December 31st, 2008
Exercises
Thousands of Zunes froze for 24 hours
2008 was a leap year: 366 days
An embedded module in the Zune contained the following (actual) code
Zune Bug
What happened?

Introduction
1 while(days > 365) {
For Loops
2 if(IsLeapYear(year)) {
While Loops
3 if(days > 366) {
4 days -= 366;
Other Loops
5 year += 1;
Pitfalls
6 }
Exercises
7 } else {
8 days -= 365;
9 year += 1;
10 }
11 }
Introduction

For Loops

While Loops

Other Loops

Pitfalls Part VI: Exercises


Exercises
Exercise

Write code snippets to do the following.

Introduction 1 Print a list of even integers 0 to n, one to a line


For Loops 2 The same list, but delimited by commas
While Loops

Other Loops
3 A list of integers divisible by 3 between 10 and 100 (print a total as well)
Pitfalls
4 Prints all positive powers of two, 1, 2, 4, 8, . . . , 230
Exercises 5 Prints all even integers 2 thru 200 on 10 different lines (10 numbers per line)
in reverse order
6 Prints the following pattern of numbers (hint: use some value of i + 10j):

11, 21, 31, 41, ..., 91, 101


12, 22, 32, 42, ..., 92, 102
...
20, 30, 40, 50, ..., 100, 110
Exercise

Introduction

For Loops

While Loops

Other Loops Write a FizzBuzz program: print numbers from 1 to 100, but for numbers that are
Pitfalls multiples of 3 print “Fizz” instead. For numbers that are multiples of 5, print
Exercises “Buzz” instead. For numbers that are multiples of both 3 and 5, print “FizzBuzz”
Exercise

Introduction

For Loops

While Loops Implement a program to use the Babylonian method to compute a square root of a
Other Loops number a using the series,
Pitfalls
 
Exercises 1 a
xn+1 = · xn + , x0 = 1
2 xn
Exercise


Example: compute 2 (a = 2)
Introduction

For Loops

While Loops

Other Loops

Pitfalls

Exercises
Exercise


Example: compute 2 (a = 2)
Introduction
 
For Loops 1 a
x1 = · x0 +
While Loops 2 x0
Other Loops

Pitfalls

Exercises
Exercise


Example: compute 2 (a = 2)
Introduction
 
For Loops 1 a
x1 = · x0 +
While Loops 2 x0
Other Loops
 
Pitfalls 1 2
x1 = · 1 + = 1.5
Exercises 2 1
Exercise


Example: compute 2 (a = 2)
Introduction
 
For Loops 1 a
x1 = · x0 +
While Loops 2 x0
Other Loops
 
Pitfalls 1 2
x1 = · 1 + = 1.5
Exercises 2 1
 
1 a
x2 = · x1 +
2 x1
Exercise


Example: compute 2 (a = 2)
Introduction
 
For Loops 1 a
x1 = · x0 +
While Loops 2 x0
Other Loops
 
Pitfalls 1 2
x1 = · 1 + = 1.5
Exercises 2 1
 
1 a
x2 = · x1 +
2 x1
 
1 2
x2 = · 1.5 + = 1.41666
2 1.5
Exercise

Introduction

For Loops Would you accept a job with the following conditions?
While Loops

Other Loops You only get paid a dollar a month.


Pitfalls
However, each month your pay doubles.
Exercises
Your contract lasts 2 years.

Write a program to project your earnings.


Exercise

Introduction

For Loops

While Loops DogeCoin is ’sploding! It increases 20% in value every week! Suppose we start with
Other Loops 1000 DogeCoin which is initially worth $10 (1 DogeCoin = 1 cent). Let’s take the
Pitfalls
following strategy: at the end of each week, we sell half our gains, and keep the
Exercises
rest growing. Then, at the end of the year we’ll report how much cash we have,
how much DogeCoin we have, and how much that is worth in total USD.

You might also like