javascript

exercises

exercises.js
/**
 * ============================================
 * 3.1 Arithmetic Operators - Exercises
 * ============================================
 *
 * Practice arithmetic operations in JavaScript.
 * Solutions are at the bottom.
 */

// ============================================
// EXERCISE 1: Basic Calculations
// ============================================
// Calculate and store the results:

// 1a) Sum of 25 and 17

// 1b) Difference between 100 and 37

// 1c) Product of 8 and 12

// 1d) Quotient of 84 divided by 7

// 1e) Remainder of 29 divided by 5

// ============================================
// EXERCISE 2: Predict the Output
// ============================================
// What is the result and type of each expression?

// "5" + 3           Result: _____ Type: _____
// "5" - 3           Result: _____ Type: _____
// "5" * "3"         Result: _____ Type: _____
// 5 + 3 + "8"       Result: _____ Type: _____
// "5" + 3 + 8       Result: _____ Type: _____
// 10 / 0            Result: _____ Type: _____
// 0 / 0             Result: _____ Type: _____
// NaN + 5           Result: _____ Type: _____

// ============================================
// EXERCISE 3: Order of Operations
// ============================================
// Calculate these WITHOUT running the code first:

// 2 + 3 * 4         = _____
// (2 + 3) * 4       = _____
// 10 - 4 / 2        = _____
// 2 ** 3 ** 2       = _____ (hint: right-to-left)
// 100 / 10 / 2      = _____ (hint: left-to-right)
// 2 + 3 * 4 ** 2    = _____

// ============================================
// EXERCISE 4: Temperature Converter
// ============================================
// Create functions to convert temperatures:

// celsiusToFahrenheit: Formula: F = C × 9/5 + 32

// fahrenheitToCelsius: Formula: C = (F - 32) × 5/9

// YOUR CODE:

// ============================================
// EXERCISE 5: Modulo Applications
// ============================================
// Solve using the modulo operator:

// 5a) Check if 247 is even or odd

// 5b) Get the last digit of 98765

// 5c) Get the last two digits of 98765

// 5d) Check if 144 is divisible by 12

// 5e) Convert 400 degrees to 0-360 range

// ============================================
// EXERCISE 6: Circle Calculator
// ============================================
// Create functions for circle calculations:
// (Use Math.PI for π)

// circleArea: A = πr²

// circleCircumference: C = 2πr

// YOUR CODE:

// ============================================
// EXERCISE 7: Increment/Decrement
// ============================================
// Predict the values WITHOUT running the code:

let a = 5;
let b = 5;
let c = 5;
let d = 5;

// After: let r1 = a++;
// a = _____, r1 = _____

// After: let r2 = ++b;
// b = _____, r2 = _____

// After: let r3 = c-- + 2;
// c = _____, r3 = _____

// After: let r4 = --d + 2;
// d = _____, r4 = _____

// ============================================
// EXERCISE 8: Average Calculator
// ============================================
// Create a function that calculates the average of any number of arguments

function calculateAverage() {
  // YOUR CODE:
}

// Tests:
// calculateAverage(10, 20, 30)       → 20
// calculateAverage(5)                → 5
// calculateAverage(1, 2, 3, 4, 5)    → 3
// calculateAverage()                 → 0

// ============================================
// EXERCISE 9: Shopping Cart Total
// ============================================
// Calculate the total with tax and discount

function calculateTotal(items, taxRate, discountPercent) {
  // items is an array of { name, price, quantity }
  // taxRate is a percentage (e.g., 8 for 8%)
  // discountPercent is a percentage (e.g., 10 for 10% off)
  // Return the final total
  // YOUR CODE:
}

// Test:
// const cart = [
//     { name: "Widget", price: 9.99, quantity: 3 },
//     { name: "Gadget", price: 24.99, quantity: 2 }
// ];
// calculateTotal(cart, 8, 10) → 77.84 (approximately)

// ============================================
// EXERCISE 10: Random Range
// ============================================
// Create a function to generate random integers in a range

function randomInRange(min, max) {
  // Return a random integer between min and max (inclusive)
  // YOUR CODE:
}

// Tests:
// randomInRange(1, 10)   → 1-10
// randomInRange(0, 1)    → 0 or 1
// randomInRange(-5, 5)   → -5 to 5

// ============================================
// EXERCISE 11: Time Calculator
// ============================================
// Convert total seconds to hours, minutes, seconds

function formatTime(totalSeconds) {
  // Return object with hours, minutes, seconds
  // e.g., 3661 → { hours: 1, minutes: 1, seconds: 1 }
  // YOUR CODE:
}

// Tests:
// formatTime(3661)    → { hours: 1, minutes: 1, seconds: 1 }
// formatTime(7265)    → { hours: 2, minutes: 1, seconds: 5 }
// formatTime(45)      → { hours: 0, minutes: 0, seconds: 45 }

// ============================================
// EXERCISE 12: Compound Interest
// ============================================
// Calculate compound interest

function compoundInterest(principal, rate, timesPerYear, years) {
  // Formula: A = P(1 + r/n)^(nt)
  // P = principal
  // r = annual rate (decimal)
  // n = times compounded per year
  // t = years
  // Return final amount
  // YOUR CODE:
}

// Test:
// $1000 at 5% compounded monthly for 10 years
// compoundInterest(1000, 0.05, 12, 10) → 1647.01 (approximately)

// ============================================
// EXERCISE 13: Safe Division
// ============================================
// Create a function that handles division edge cases

function safeDivide(numerator, denominator) {
  // Handle:
  // - Division by zero (return null)
  // - Non-numeric inputs (return null)
  // - NaN results (return null)
  // Otherwise return the result
  // YOUR CODE:
}

// Tests:
// safeDivide(10, 2)        → 5
// safeDivide(10, 0)        → null
// safeDivide("10", 2)      → 5 (convert strings)
// safeDivide("abc", 2)     → null
// safeDivide(10, null)     → null

// ============================================
// EXERCISE 14: Digit Operations
// ============================================
// Create functions to work with digits

// getDigitCount: Return the number of digits in a positive integer

// sumOfDigits: Return the sum of all digits

// reverseNumber: Reverse the digits of a number

// YOUR CODE:

// ============================================
// EXERCISE 15: Precision Handling
// ============================================
// Create a function for safe decimal math

function preciseAdd(a, b, decimalPlaces = 2) {
  // Add two numbers and return result rounded to decimalPlaces
  // Handle floating point issues
  // YOUR CODE:
}

// Tests:
// preciseAdd(0.1, 0.2)           → 0.3
// preciseAdd(0.1, 0.2, 4)        → 0.3
// preciseAdd(19.99, 0.01)        → 20
// preciseAdd(1.005, 0, 2)        → 1.01

// ============================================
// EXERCISE 16: Powers and Roots
// ============================================
// Create these functions WITHOUT using Math methods
// (use ** operator instead)

// square: Return x²

// cube: Return x³

// squareRoot: Return √x (hint: x ** 0.5)

// cubeRoot: Return ³√x (hint: x ** (1/3))

// nthRoot: Return ⁿ√x

// YOUR CODE:

// ============================================
// ============================================
//              SOLUTIONS
// ============================================
// ============================================

/*

// SOLUTION 1: Basic Calculations
let sum = 25 + 17;           // 42
let difference = 100 - 37;   // 63
let product = 8 * 12;        // 96
let quotient = 84 / 7;       // 12
let remainder = 29 % 5;      // 4


// SOLUTION 2: Predict the Output
// "5" + 3           → "53" (string)
// "5" - 3           → 2 (number)
// "5" * "3"         → 15 (number)
// 5 + 3 + "8"       → "88" (string)
// "5" + 3 + 8       → "538" (string)
// 10 / 0            → Infinity (number)
// 0 / 0             → NaN (number)
// NaN + 5           → NaN (number)


// SOLUTION 3: Order of Operations
// 2 + 3 * 4         = 14
// (2 + 3) * 4       = 20
// 10 - 4 / 2        = 8
// 2 ** 3 ** 2       = 512 (2^9, right-to-left)
// 100 / 10 / 2      = 5 (left-to-right)
// 2 + 3 * 4 ** 2    = 50 (2 + 3 * 16)


// SOLUTION 4: Temperature Converter
function celsiusToFahrenheit(celsius) {
    return celsius * 9 / 5 + 32;
}

function fahrenheitToCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5 / 9;
}


// SOLUTION 5: Modulo Applications
// 5a) Check if 247 is even or odd
console.log(247 % 2 === 0 ? "even" : "odd");  // odd

// 5b) Get the last digit of 98765
console.log(98765 % 10);  // 5

// 5c) Get the last two digits of 98765
console.log(98765 % 100);  // 65

// 5d) Check if 144 is divisible by 12
console.log(144 % 12 === 0);  // true

// 5e) Convert 400 degrees to 0-360 range
console.log(400 % 360);  // 40


// SOLUTION 6: Circle Calculator
function circleArea(radius) {
    return Math.PI * radius ** 2;
}

function circleCircumference(radius) {
    return 2 * Math.PI * radius;
}


// SOLUTION 7: Increment/Decrement
// let r1 = a++;   → a = 6, r1 = 5
// let r2 = ++b;   → b = 6, r2 = 6
// let r3 = c-- + 2;  → c = 4, r3 = 7 (5 + 2)
// let r4 = --d + 2;  → d = 4, r4 = 6 (4 + 2)


// SOLUTION 8: Average Calculator
function calculateAverage(...numbers) {
    if (numbers.length === 0) return 0;
    return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
}


// SOLUTION 9: Shopping Cart Total
function calculateTotal(items, taxRate, discountPercent) {
    // Calculate subtotal
    let subtotal = items.reduce((sum, item) => {
        return sum + (item.price * item.quantity);
    }, 0);
    
    // Apply discount
    let afterDiscount = subtotal * (1 - discountPercent / 100);
    
    // Apply tax
    let total = afterDiscount * (1 + taxRate / 100);
    
    return Math.round(total * 100) / 100;
}


// SOLUTION 10: Random Range
function randomInRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


// SOLUTION 11: Time Calculator
function formatTime(totalSeconds) {
    let hours = Math.floor(totalSeconds / 3600);
    let minutes = Math.floor((totalSeconds % 3600) / 60);
    let seconds = totalSeconds % 60;
    
    return { hours, minutes, seconds };
}


// SOLUTION 12: Compound Interest
function compoundInterest(principal, rate, timesPerYear, years) {
    let amount = principal * Math.pow(1 + rate / timesPerYear, timesPerYear * years);
    return Math.round(amount * 100) / 100;
}


// SOLUTION 13: Safe Division
function safeDivide(numerator, denominator) {
    // Convert to numbers
    let num = Number(numerator);
    let den = Number(denominator);
    
    // Check for invalid inputs
    if (Number.isNaN(num) || Number.isNaN(den)) {
        return null;
    }
    
    // Check for division by zero
    if (den === 0) {
        return null;
    }
    
    let result = num / den;
    
    // Check for NaN or Infinity result
    if (Number.isNaN(result) || !Number.isFinite(result)) {
        return null;
    }
    
    return result;
}


// SOLUTION 14: Digit Operations
function getDigitCount(num) {
    if (num === 0) return 1;
    return Math.floor(Math.log10(Math.abs(num))) + 1;
}

function sumOfDigits(num) {
    num = Math.abs(num);
    let sum = 0;
    while (num > 0) {
        sum += num % 10;
        num = Math.floor(num / 10);
    }
    return sum;
}

function reverseNumber(num) {
    let isNegative = num < 0;
    num = Math.abs(num);
    let reversed = 0;
    while (num > 0) {
        reversed = reversed * 10 + num % 10;
        num = Math.floor(num / 10);
    }
    return isNegative ? -reversed : reversed;
}


// SOLUTION 15: Precision Handling
function preciseAdd(a, b, decimalPlaces = 2) {
    let multiplier = 10 ** decimalPlaces;
    let result = (Math.round(a * multiplier) + Math.round(b * multiplier)) / multiplier;
    return Math.round(result * multiplier) / multiplier;
}


// SOLUTION 16: Powers and Roots
function square(x) {
    return x ** 2;
}

function cube(x) {
    return x ** 3;
}

function squareRoot(x) {
    return x ** 0.5;
}

function cubeRoot(x) {
    return x ** (1 / 3);
}

function nthRoot(x, n) {
    return x ** (1 / n);
}

*/
Exercises - JavaScript Tutorial | DeepML