Skip to content

Instantly share code, notes, and snippets.

@cbourke
Created September 11, 2018 17:25
Show Gist options
  • Save cbourke/6414bf5b314d4d2ddb056354e53af563 to your computer and use it in GitHub Desktop.
Save cbourke/6414bf5b314d4d2ddb056354e53af563 to your computer and use it in GitHub Desktop.
auto-posted gist

CSCE 155H - Computer Science I Honors

Loops

An introduction to loop control structures.

  • We need a way to repeatedly execute blocks of code
  • There are three basic elements to a loop control structure:
    • An initialization (where the loop starts)
    • A continuation condition (how long should the loop continue or when should it stop)
    • An increment or "update" (how you make progress toward that ending condition)
    • The loop body: what the loop actually does during its execution

For loops

  • Uses the keyword for
  • All three elements are on the same line
  • for(<initialization>; <continuation>; <increment>)
int i; //index variable
for(i=0; i<10; i++) {
	printf("%d\n", i);
}
printf("%d\n", i);
  • Alternatively in both languages (in fact, preferably in both languages) you can/should declare a loop-scoped index variable
for(int i=0; i<10; i++) {
	printf("%d\n", i);
}
printf("%d\n", i);//compiler error
  • In the above, the variable i only exists in the scope of the loop

  • In general you should limit the scope of variables to the smallest section of code that is necessary

  • Ex: Global variables are variables whose scope spans an ENTIRE PROGRAM, in general globals are evil

  • The i++ is a "postfix increment operator": simply adds one to the variable i

  • There is a prefix increment operator ++i (but don't worry about it)

  • You can also decrement by one: i--

  • More generally you can increment/decrement by a number other than one:

    • i += 5 adds 5 to the variable i ("equivalent" i = i + 5)
    • i -= 10 subtracts 10 from the variable i
    • i *= 2 multiples the value in i by 2 and (restores) the value into i ie it doubles it
    • i /= 3 divides the i by 3
  • Side note: in neither language are default values defined for primitive types (int, double, char).

    • In C: it could be anything, it could be zero, it could be garbage, it could be 0xDEADBEEF it all depends on the compiler and the Operating System
    • IN Java: it becomes a compiler error; you MUST initial your variables
    • In both languages: its best practice to initialize your variables

While Loops

  • While loops use the keyword while
  • However, the three elements (initialization, continuation, and increment) are not on the same line
int i = 0; //initialization
while(i < 10) {  //continuation
	printf("%d\n", i);
	i++;
}
  • In general, you use for loops when you know apriori (ie up front) how many iterations you want to execute
  • In general, you use a while loop when the number of iterations is not known up front or depends on the input
  • Otherwise, any for loop can be rewritten as a while loop and vice versa

Pitfalls

  • Consider the following code:
int i = 0;
while(i < 10) {
  printf("%d\n", i);
}
  • The above is an infinite loop

  • Eclipse: kill the current program with the "stop button" (red)

  • on the command line: use control-C to kill the current running program

  • On the grader: wait 5 minutes and the server will kill it

  • Similar pitfall: misplaced semicolons

int i = 0;
while(i < 10); {
  printf("%d\n", i);
  i++;
}
  • the semicolon causes a do-nothing infinite loop

  • don't put semicolons where they shouldn't be

  • Consider the following code:

int i = 0;
while(i < 10)
  printf("%d\n", i);
  i++;
  • The missing curly brackets makes the while loop bind to only the next executable statement (the printf) causing an infinite loop because the i++ is never executed

  • It is best practice to include the curly brackets even if they are not necessary

  • Another pitfall: classic off-by-one error

  • Zune Bug

Other Issues

  • do-while loops exist if you want to use them, but I generally stay away (error prone, different logic and different syntax)
  • Java has another loop control structure called the "enhanced for-loop", really its just a for-each loop
    • It still uses the keyword for (there is no foreach in either language)
    • Purpose: iterate over a collection (array, an ArrayList, etc.)
int a[] = {10, 20, 30, 40};

for(int x : a) {
	System.out.println(x);
}
  • You do NOT have this in C

Nesting Loops

  • You can (just as with conditionals) nest loops within loops
int i, j;
for(i=0; i<10; i++) {
  for(j=0; j<10; j++) {
    printf("%d\n", (i+j));
  }
}

Exercises

  1. Do the following
    • A list of even integers 0 to n, one to a line
    • The same list, but delimited by commas
    • A list of integers divisible by 3 between 10 and 100 (print a total as well)
    • Prints all positive powers of two, 1, 2, 4, 8, …, up to 2^30
    • Prints all even integers 2 thru 200 on 10 different lines (10 numbers per line) in reverse order
    • 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
  1. Write a FizzBuzz program (see here for more information)

  2. Write a program to project the total earnings in a savings account with a fixed APR, initial balance, and monthly deposit over a specified number of years.

#include <stdio.h>
#include<math.h>
int main(void) {

  double balance = 0;
  double apr = .09;
  double monthlyDeposit = 1000;
  int years = 10;
  double totalInterest;

  for(int i=1; i<=years*12; i++) {
    double monthInterest = round( (balance * apr / 12.0) * 100) / 100;
    totalInterest += monthInterest;
    balance += monthInterest + monthlyDeposit;
    printf("%3d $%8.2f $%8.2f\n", i, monthInterest, balance);
  }
  printf("total interest earned: %f\n", totalInterest);


  return 0;
}
  1. Implement a program to use the Babylonian method to compute a square root of a number a using the series,

$$x_{n+1} = \frac{1}{2} \cdot \left(x_n + \frac{a}{x_n} \right), \quad x_0 = 1$$

class Main {
  public static void main(String[] args) {

    double a = 2.0;
    double curr = 1.0, prev = 0.0;
    double epsilon = 0.0000001;
    while( Math.abs(curr - prev) > epsilon) {

      double t = .5 * (curr + a / curr);
      prev = curr;
      curr = t;

    }
    System.out.println("sqrt(" + a + ") = " + curr);
    System.out.println("sqrt(" + a + ") = " + Math.sqrt(2));
  }
}








Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment