CC-03: For Loops

with Carmen Salas • 2024/10/07

slides

For Loops

What is an expression? An expression is any valid unit of code that resolves to a value.

For Loop Structure

for ([initial expression], [condition expression], [increment expression]) {
    [statement/s]
}

A for loop repeats until the condition expression evaluates to false.

While Loop Structure

while ([condition expression]) {
    [statement/s]
}

while and for loops are the same, and you can always convert one to the other!

Code Challenge

  1. Write a function named countToTen that console.logs all the integers from 1 to 10.

const countToTen = () => {
  for (let i = 1; i <= 10; i++) {
    console.log(i);
  }
}

// test functions
// countToTen() //logs: 1,2,3,4,5,6,7,8,9,10
  1. Write a function named countUpFromOne that takes in an integer argument, and console.logs all the integers from 1 up to the given integer.

const countUpFromOne = (num) => {
  for (let i = 1; i <= num; i++) {
    console.log(i);
  }
}

// tests
// countUpFromOne(7) //logs: 1,2,3,4,5,6,7
  1. Write a function named countDownFromN that takes in an integer argument, and console.logs all the integers from the given integer to 1.

const countDownFromN = (num) => {
  for (let i = num; i >= 1; i--) {
    console.log(i)
  }
}

// tests
// countDownFromN(7) //logs: 7,6,5,4,3,2,1
  1. Write a function named countEveryEven that takes in an integer argument, and console.logs all the even integers from 1 up to the given integer, including the given integer.

const countEveryEven = (num) => {
  for (let i = 2; i <= num; i+=2) {
    console.log(i);
  }
}

// tests
// countEveryEven(10) //logs: 2 4 6 8 10
  1. Write a function named countEveryOdd that takes in an integer argument, and console.logs all the odd integers from 1 up to the given integer, including the given integer.

const countEveryOdd = (num) => {
  for (let i = 1; i <= num; i+=2) {
    console.log(i);
  }
}

// tests
// countEveryOdd(10) // logs: 1 3 5 7 9

BONUS

  1. Write a fucntion named countEvens that takes in an array of integers and returns the number of integers in the array that are even numbers.

const countEvens = (numsArr) => {
  let count = 0;
  numsArr.forEach((num) => {
    if (num % 2 == 0) { count ++; }
  });
  return count;
}

// tests
// countEvens([1,2,3,4,5,6,7,8,9,12]) // returns 5
// countEvens([1,2,22,204]) // returns 3
// countEvens([1,3,7,17,19]) // returns 0

Last updated