CC-03: For Loops
with Carmen Salas • 2024/10/07
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]
}Code Challenge
- Write a function named - countToTenthat 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- Write a function named - countUpFromOnethat 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- Write a function named - countDownFromNthat 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- Write a function named - countEveryEventhat 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- Write a function named - countEveryOddthat 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 9BONUS
- Write a fucntion named - countEvensthat 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 0Last updated