π 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);
β
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);
β
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);
β
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);
π― 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)