Basic Programming Problem Set
Below are some fundamental programming problems along with solutions and explanations:
Description: Write a function that takes two numbers as input and returns their sum.
Solution:
function calculateSum(a, b) { return a b; }
Explanation: The function simply adds the two input numbers together and returns the result.
Description: Write a function that takes an array of numbers as input and returns the maximum number.
Solution:
function findMax(arr) { let max = arr[0]; for (let i = 1; i < arr.length; i ) { if (arr[i] > max) { max = arr[i]; } } return max; }
Explanation: The function iterates through the array, updating the maximum number found so far.
Description: Write a function that takes a number as input and returns true if it's prime, false otherwise.
Solution:
function isPrime(num) { if (num <= 1) return false; for (let i = 2; i <= Math.sqrt(num); i ) { if (num % i === 0) { return false; } } return true; }
Explanation: The function checks divisibility of the number up to its square root to determine if it's prime.
Description: Write a function that takes a string as input and returns the string reversed.
Solution:
function reverseString(str) { return str.split('').reverse().join(''); }
Explanation: The function splits the string into an array of characters, reverses the array, and then joins it back into a string.
Description: Write a function that takes a string as input and returns true if it's a palindrome, false otherwise.
Solution:
function isPalindrome(str) { const reversed = str.split('').reverse().join(''); return str === reversed; }
Explanation: The function checks if the original string is equal to its reversed form.