DEV Community

Laxman Nemane
Laxman Nemane

Posted on

🧠 DSA Series - Day 3

πŸ“Œ Topic: For Loop Practice – Real-World Problems

Today is our practice session on loops. We are solving beginner-friendly problems using the for loop. Make sure to understand edge cases β€” this habit will save you from bugs and unexpected behaviors. πŸš€

βœ… 1. Find the Index of a Given Element
Problem:
Search for a specific element in an array. If it exists, return its index. If not, return -1.


function searchElement(arr, element) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === element) {
      return i;
    }
  }
  return -1;
}

let res = searchElement([12, 8, 4, 2, 99], 99);
console.log("Index:", res);

Enter fullscreen mode Exit fullscreen mode

βœ… 2. Count Positive and Negative Numbers
Problem:
Count how many positive and negative numbers are in an array.


function checkCount(arr) {
  let positiveCount = 0;
  let negativeCount = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
      positiveCount++;
    } else {
      negativeCount++;
    }
  }

  return { positiveCount, negativeCount };
}

let res = checkCount([12, 8, 4, 2, -99]);
console.log("Counts:", res);
Enter fullscreen mode Exit fullscreen mode

βœ… 3. Find the Largest Number
Problem:
Find the largest number in a given array.


function findLargest(arr) {
  let largeNumber = arr[0];

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > largeNumber) {
      largeNumber = arr[i];
    }
  }

  return largeNumber;
}

let res = findLargest([12, 8, 4, 2, -99]);
console.log("Largest:", res);
Enter fullscreen mode Exit fullscreen mode

βœ… 4. Find the Second Largest Number
Problem:
Find the second largest number in an array.

function findSecondLargest(arr) {
  if (arr.length < 2) {
    return "Array must contain at least 2 elements";
  }

  let fl = -Infinity; // First Largest
  let sl = -Infinity; // Second Largest

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > fl) {
      sl = fl;
      fl = arr[i];
    } else if (arr[i] > sl && arr[i] !== fl) {
      sl = arr[i];
    }
  }

  return { firstLargest: fl, secondLargest: sl };
}

let res = findSecondLargest([12, 8, 4, 2, 99]);
console.log("Second Largest:", res);

Enter fullscreen mode Exit fullscreen mode

🎯 Takeaway:
Always test your code for edge cases like:

  • Empty arrays
  • All elements being the same
  • Arrays with only negative numbers
  • Arrays with one element
  • Practicing like this strengthens your fundamentals. Stay consistent and keep building!

πŸ’¬ Let me know which one was your favorite or if you faced any issues!

πŸ’» Until tomorrow, Happy Coding! πŸ‘¨β€πŸ’»βœ¨

Top comments (0)