CC-04: For Loops and Conditionals

with Carmen Salas • 2024/10/08

Review

yesterday's CC

Code Challenge

  1. Write a function named countFromOne that takes in an integer argument, and console.logs all the integers from 1 up to the given integer.

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

// tests
// countFromOne(10);
// countFromOne(1);
  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 = (x) => {
  for (let i = 1; i <= x; i+=2) {
    console.log(i)
  }
}

// tests
// countEveryOdd(11);
// countEveryOdd(6);
  1. Write a function isNegative that takes in a number parameter and returns true if the number is a negative value and false if the number is a positive value.

const isNegative = (x) => {
  return (x < 0) ? true : false;
}

// tests
// console.log(isNegative(-1));
// console.log(isNegative(10));
// console.log(isNegative(0));
  1. Write a function named betweenFiveAndTwenty that takes in an integer parameter, and checks whether a given integer is within 5 and 20. It returns true if it is and false if not.

const betweenFiveAndTwenty = (x) => {
  return (x >= 5 && x <= 20) ? true : false;
}

// tests
// console.log(betweenFiveAndTwenty(12));
// console.log(betweenFiveAndTwenty(5));
// console.log(betweenFiveAndTwenty(100));
  1. Write a function named sumOfThreeOrFive that returns the sum of all the multiples of 3 or multiples of 5 from 1 to 1000, exclusive.

const sumOfThreeOrFive = () => {
  sum = 0;
  for (let i = 1; i < 1000; i++) {
    if (i%3 == 0 || i%5 == 0) {
      sum += i;
    }
  }
  return sum;
}

// test
// console.log(sumOfThreeOrFive());
  1. Write a function named isAllLowerCase that takes in a string parameter, and returns true or false if the string consists of only lowercase letters.

const isAllLowerCase = (str) => {
  for (let i = 0; i < str.length; i++) {
    asciiCode = str.charCodeAt(i);
    if (asciiCode == 32) { continue; }
    if (asciiCode < 97 || asciiCode > 122) { return false; }
  }
  return true
}

// test
// console.log(isAllLowerCase("hello")) //returns true
// console.log(isAllLowerCase("seven eleven")) //returns true
// console.log(isAllLowerCase("Seven eleven has the best slushies")) //returns false

BONUS

  1. Write a function named countMultiplesOfFive that takes in an array of integers and returns the number of integers in the array that are multiples of five.

const countMultiplesOfFive = (arr) => {
  return arr.filter((x) => x%5 == 0).length;
}

// test
// console.log(countMultiplesOfFive([1,2,3,4,5,6,7,8,9,10])) // returns 2
// console.log(countMultiplesOfFive([15,23,35,45,67])) // returns 3
// console.log(countMultiplesOfFive([2,6,14])) // returns 0

Last updated