Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Prashant Basnet
👋 Welcome to my Signature, a space between logic and curiosity.
I’m a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and “aha” moments that keep me building.
Whenever we are updating the iteration by only 1 count regardless we use for.
If we want to update out iteration based certain count depending on the condition. Then we use while loop.
// Simple array traversal for(let i = 0; i < arr.length; i++) { // i++ means we're moving one step at a time console.log(arr[i]); } // String traversal for(let i = 0; i < str.length; i++) { // Looking at each character one by one console.log(str[i]); }WHILE Loop - When increment varies:
// Like in our string encoding problem let i = 0; while(i < str.length) { // i moves by variable amounts i += lengthStr.length + 1 + wordLength; } // Binary search example let left = 0, right = nums.length - 1; while(left <= right) { let mid = Math.floor((left + right) / 2); // Moving left or right by varying amounts if(nums[mid] < target) left = mid + 1; else right = mid - 1; }This is why while loops are often better for:
#basicsOfProgramming #loop