DEV Community

King coder
King coder

Posted on • Edited on

Day 8 of My DSA Problem Solving Journey

โœ… 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

Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

Problem1_Exalidrow

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

Enter fullscreen mode Exit fullscreen mode

โœ… 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

Enter fullscreen mode Exit fullscreen mode

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.


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

//

โœ… 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

Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

Top comments (0)