โ Problem 1: Two Sum
๐ Problem Statement:
- Given an integer input, the objective is check whether the given integer is Positive or Negative. In order to do so we have the following methods,
Example
Input: num = 12;
Output: The number is positive
Approach
1. Create a function.
2. Take a number as input.
3. Check if the number is less than 0 โ if so, the number is negative.
4. Otherwise, the number is positive.
Js Code
function checkPositiveOrNegative(num) {
if (num < 0) {
return 'The number is negative';
} else {
return 'The number is positive';
}
}
console.log(checkPositiveOrNegative(12)); // Output: The number is positive
console.log(checkPositiveOrNegative(0)); // Output: The number is positive
console.log(checkPositiveOrNegative(-10)); // Output: The number is negative
โ Problem 2: Even or Odd
๐ Problem Statement:
- Check whether the given number is Even or Odd
Example
Input: num = 12;
Output: The number is Even
Input: num = 11;
Output: The number is Odd
Approach
1. Create a function called CheckEvenOdd.
2. Take a number as input.
3. If the number is divisible by 2 , then the number is even.
4. Otherwise, the number is odd.
Js Code
function CheckEvenOdd(num) {
if (num % 2 === 0) {
return 'The Number is Even';
} else {
return 'The Number is Odd';
}
}
console.log(CheckEvenOdd(2)); // Output: The Number is Even
console.log(CheckEvenOdd(3)); // Output: The Number is Odd
console.log(CheckEvenOdd(5)); // Output: The Number is Odd
console.log(CheckEvenOdd(8)); // Output: The Number is Even
//
โ Problem 3: Sum of First N Natural Numbers
๐ Problem Statement:
- Find the Sum of First N Natural Numbers.
- Natural numbers start from 1 and go on infinite.
Example
Input: num = 5;
Output: 15
Input: num = 10;
Output: 55
Approach
1. Create a function called SumOfNaturalNumber.
2. Initialize a variable `sum` to 0.
3. Run a loop from 1 to the given number `num`.
4. In each iteration, add the current number to `sum`.
5. After the loop ends, return the
Js Code
// Sum of First N Natural Numbers
function SumOfNaturalNumber(num) {
let sum = 0;
for (let i = 1; i <= num; i++) {
sum += i;
}
return sum;
}
// Test cases
console.log(SumOfNaturalNumber(5)); // Output: 15
console.log(SumOfNaturalNumber(10)); // Output: 55
console.log(SumOfNaturalNumber(2)); // Output: 3
Top comments (0)