javascript

exercises

exercises.js
/**
 * =====================================================
 * 4.3 FOR LOOPS - EXERCISES
 * =====================================================
 * Practice iterative programming
 */

/**
 * Exercise 1: Sum Range
 *
 * Calculate the sum of all numbers from start to end (inclusive).
 */
function sumRange(start, end) {
  // TODO: Use a for loop to sum numbers from start to end
}

// Test cases:
console.log('Exercise 1:');
console.log(sumRange(1, 5)); // 15 (1+2+3+4+5)
console.log(sumRange(3, 7)); // 25 (3+4+5+6+7)
console.log(sumRange(10, 10)); // 10

/**
 * Exercise 2: Factorial
 *
 * Calculate the factorial of n (n!).
 * Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
 */
function factorial(n) {
  // TODO: Use a for loop to calculate factorial
}

// Test cases:
console.log('\nExercise 2:');
console.log(factorial(0)); // 1 (by definition)
console.log(factorial(1)); // 1
console.log(factorial(5)); // 120
console.log(factorial(10)); // 3628800

/**
 * Exercise 3: Count Vowels
 *
 * Count the number of vowels (a, e, i, o, u) in a string.
 * Case-insensitive.
 */
function countVowels(str) {
  // TODO: Loop through the string and count vowels
}

// Test cases:
console.log('\nExercise 3:');
console.log(countVowels('hello')); // 2
console.log(countVowels('AEIOU')); // 5
console.log(countVowels('JavaScript')); // 3
console.log(countVowels('rhythm')); // 0

/**
 * Exercise 4: Find Index
 *
 * Return the index of the first occurrence of target in the array.
 * Return -1 if not found.
 */
function findIndex(arr, target) {
  // TODO: Use a for loop to find the target
}

// Test cases:
console.log('\nExercise 4:');
console.log(findIndex([1, 2, 3, 4, 5], 3)); // 2
console.log(findIndex(['a', 'b', 'c'], 'b')); // 1
console.log(findIndex([1, 2, 3], 5)); // -1
console.log(findIndex([], 1)); // -1

/**
 * Exercise 5: Reverse Array
 *
 * Create a new array with elements in reverse order.
 * Do NOT use the built-in reverse() method.
 */
function reverseArray(arr) {
  // TODO: Build a new array in reverse order
}

// Test cases:
console.log('\nExercise 5:');
console.log(reverseArray([1, 2, 3, 4, 5])); // [5, 4, 3, 2, 1]
console.log(reverseArray(['a', 'b', 'c'])); // ["c", "b", "a"]
console.log(reverseArray([1])); // [1]
console.log(reverseArray([])); // []

/**
 * Exercise 6: FizzBuzz Array
 *
 * Generate an array from 1 to n with FizzBuzz rules:
 * - "FizzBuzz" for multiples of both 3 and 5
 * - "Fizz" for multiples of 3
 * - "Buzz" for multiples of 5
 * - The number as string otherwise
 */
function fizzBuzzArray(n) {
  // TODO: Create an array with FizzBuzz values
}

// Test cases:
console.log('\nExercise 6:');
console.log(fizzBuzzArray(5));
// ["1", "2", "Fizz", "4", "Buzz"]
console.log(fizzBuzzArray(15)[14]); // "FizzBuzz"

/**
 * Exercise 7: Sum of Multiples
 *
 * Find the sum of all multiples of 3 or 5 below n.
 */
function sumMultiples(n) {
  // TODO: Sum all numbers below n that are divisible by 3 or 5
}

// Test cases:
console.log('\nExercise 7:');
console.log(sumMultiples(10)); // 23 (3+5+6+9)
console.log(sumMultiples(20)); // 78
console.log(sumMultiples(1000)); // 233168

/**
 * Exercise 8: Is Prime
 *
 * Check if a number is prime (only divisible by 1 and itself).
 */
function isPrime(n) {
  // TODO: Check if n is prime using a for loop
}

// Test cases:
console.log('\nExercise 8:');
console.log(isPrime(2)); // true
console.log(isPrime(17)); // true
console.log(isPrime(4)); // false
console.log(isPrime(1)); // false
console.log(isPrime(97)); // true

/**
 * Exercise 9: Matrix Sum
 *
 * Calculate the sum of all elements in a 2D array.
 */
function matrixSum(matrix) {
  // TODO: Use nested loops to sum all elements
}

// Test cases:
console.log('\nExercise 9:');
console.log(
  matrixSum([
    [1, 2],
    [3, 4],
  ])
); // 10
console.log(
  matrixSum([
    [1, 2, 3],
    [4, 5, 6],
  ])
); // 21
console.log(matrixSum([[5]])); // 5
console.log(matrixSum([])); // 0

/**
 * Exercise 10: Remove Duplicates
 *
 * Create a new array with duplicate values removed.
 * Preserve the order of first occurrences.
 */
function removeDuplicates(arr) {
  // TODO: Build array without duplicates
}

// Test cases:
console.log('\nExercise 10:');
console.log(removeDuplicates([1, 2, 2, 3, 3, 3])); // [1, 2, 3]
console.log(removeDuplicates([1, 2, 1, 2, 1, 2])); // [1, 2]
console.log(removeDuplicates(['a', 'b', 'a'])); // ["a", "b"]

// =====================================================
// BONUS CHALLENGES
// =====================================================

/**
 * Bonus 1: Spiral Matrix
 *
 * Generate an n×n spiral matrix.
 * Example for n=3:
 * [[1, 2, 3],
 *  [8, 9, 4],
 *  [7, 6, 5]]
 */
function spiralMatrix(n) {
  // TODO: Create a spiral matrix
}

console.log('\nBonus 1:');
console.log(spiralMatrix(3));

/**
 * Bonus 2: Pascal's Triangle
 *
 * Generate the first n rows of Pascal's triangle.
 * Row 0: [1]
 * Row 1: [1, 1]
 * Row 2: [1, 2, 1]
 * Row 3: [1, 3, 3, 1]
 */
function pascalsTriangle(n) {
  // TODO: Generate Pascal's triangle
}

console.log('\nBonus 2:');
console.log(pascalsTriangle(5));

/**
 * Bonus 3: Two Sum
 *
 * Find indices of two numbers in the array that add up to target.
 * Return [index1, index2] or null if not found.
 */
function twoSum(nums, target) {
  // TODO: Find two numbers that sum to target
}

console.log('\nBonus 3:');
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
console.log(twoSum([3, 2, 4], 6)); // [1, 2]
console.log(twoSum([3, 3], 6)); // [0, 1]

// =====================================================
// SOLUTIONS (Uncomment to check your answers)
// =====================================================

/*
// Exercise 1 Solution:
function sumRange(start, end) {
    let sum = 0;
    for (let i = start; i <= end; i++) {
        sum += i;
    }
    return sum;
}

// Exercise 2 Solution:
function factorial(n) {
    let result = 1;
    for (let i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

// Exercise 3 Solution:
function countVowels(str) {
    const vowels = "aeiouAEIOU";
    let count = 0;
    for (let i = 0; i < str.length; i++) {
        if (vowels.includes(str[i])) {
            count++;
        }
    }
    return count;
}

// Exercise 4 Solution:
function findIndex(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === target) {
            return i;
        }
    }
    return -1;
}

// Exercise 5 Solution:
function reverseArray(arr) {
    const reversed = [];
    for (let i = arr.length - 1; i >= 0; i--) {
        reversed.push(arr[i]);
    }
    return reversed;
}

// Exercise 6 Solution:
function fizzBuzzArray(n) {
    const result = [];
    for (let i = 1; i <= n; i++) {
        if (i % 15 === 0) {
            result.push("FizzBuzz");
        } else if (i % 3 === 0) {
            result.push("Fizz");
        } else if (i % 5 === 0) {
            result.push("Buzz");
        } else {
            result.push(String(i));
        }
    }
    return result;
}

// Exercise 7 Solution:
function sumMultiples(n) {
    let sum = 0;
    for (let i = 1; i < n; i++) {
        if (i % 3 === 0 || i % 5 === 0) {
            sum += i;
        }
    }
    return sum;
}

// Exercise 8 Solution:
function isPrime(n) {
    if (n < 2) return false;
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) {
            return false;
        }
    }
    return true;
}

// Exercise 9 Solution:
function matrixSum(matrix) {
    let sum = 0;
    for (let row = 0; row < matrix.length; row++) {
        for (let col = 0; col < matrix[row].length; col++) {
            sum += matrix[row][col];
        }
    }
    return sum;
}

// Exercise 10 Solution:
function removeDuplicates(arr) {
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        let isDuplicate = false;
        for (let j = 0; j < result.length; j++) {
            if (arr[i] === result[j]) {
                isDuplicate = true;
                break;
            }
        }
        if (!isDuplicate) {
            result.push(arr[i]);
        }
    }
    return result;
}

// Bonus 1 Solution:
function spiralMatrix(n) {
    const matrix = Array.from({ length: n }, () => Array(n).fill(0));
    let value = 1;
    let top = 0, bottom = n - 1, left = 0, right = n - 1;
    
    while (top <= bottom && left <= right) {
        // Right
        for (let i = left; i <= right; i++) matrix[top][i] = value++;
        top++;
        // Down
        for (let i = top; i <= bottom; i++) matrix[i][right] = value++;
        right--;
        // Left
        if (top <= bottom) {
            for (let i = right; i >= left; i--) matrix[bottom][i] = value++;
            bottom--;
        }
        // Up
        if (left <= right) {
            for (let i = bottom; i >= top; i--) matrix[i][left] = value++;
            left++;
        }
    }
    return matrix;
}

// Bonus 2 Solution:
function pascalsTriangle(n) {
    const triangle = [];
    for (let row = 0; row < n; row++) {
        const currentRow = [];
        for (let col = 0; col <= row; col++) {
            if (col === 0 || col === row) {
                currentRow.push(1);
            } else {
                currentRow.push(triangle[row - 1][col - 1] + triangle[row - 1][col]);
            }
        }
        triangle.push(currentRow);
    }
    return triangle;
}

// Bonus 3 Solution:
function twoSum(nums, target) {
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                return [i, j];
            }
        }
    }
    return null;
}
*/
Exercises - JavaScript Tutorial | DeepML