4. For Loops

Cards (8)

  • For Loops are a line of code that repeats a set number of times, also known as counted loops.
  • The steps for a For Loops are:
    1. Declare the counter variable(where the loop starts)
    2. Where the loop should stop
    3. How much the counter increments or decrements
  • Loop 10 times, starting at 0
    for(int i = 0; i < 10; i++){
    }
  • Loop 20 times, counting by 2s
    for(int i = 0; i < 20; i += 2){
    }
  • Counting backwards from 100 down to 1 by 3s
    for(int i = 100; i >= 1; i -= 3){
    }
  • Sum up all numbers from 1 to 100
    int sum = 0;
    for(int i = 1; i <= 100; i++){
    sum += i;
    }
  • Product of every odd number from -51 to 51
    int product = 1;
    for(int i = -51; i <= 51; i += 2){
    product *= i;
    }
  • Subtract all even numbers from 60 to 30 from 8192
    int num = 8192;
    for(int i = 60; i >= 30; i -= 2){
    num -= i;
    }