🔄 Class 30 - Do-While & For-In Loops

Learn advanced loop types

Part 1: Do-While Loop

What is Do-While?

Runs code first, then checks condition. Runs at least once!

do {
  // Code runs first
} while (condition);

Do-While Example 1: Print Numbers

Print numbers from 1 to N

let i = 1;
do {
  console.log(i);
  i++;
} while (i <= n);

Do-While Example 2: Menu System

Simulates a menu that runs at least once

let choice = 0;
do {
  console.log('Menu: 1-Start, 2-Stop, 3-Exit');
  choice = getUserChoice();
} while (choice !== 3);

Part 2: For-In Loop

What is For-In?

Loop through object properties (keys)

for (let key in object) {
  console.log(key + ': ' + object[key]);
}

For-In Example 1: Student Info

Display student information using for-in

let student = {
  name: 'Ali',
  age: 20,
  grade: 'A',
  city: 'Karachi'
};

for (let key in student) {
  console.log(key + ': ' + student[key]);
}

For-In Example 2: Product Prices

Display product prices using for-in

let products = {
  laptop: 50000,
  phone: 30000,
  tablet: 20000,
  watch: 5000
};

for (let item in products) {
  console.log(item + ': Rs.' + products[item]);
}

📊 Quick Comparison

Do-While vs While

// While - checks first
while (i <= 5) {
  console.log(i);
  i++;
}

// Do-While - runs first, then checks
do {
  console.log(i);
  i++;
} while (i <= 5);

For-In vs For

// For - loop through numbers
for (let i = 0; i < 5; i++) {
  console.log(i);
}

// For-In - loop through object keys
for (let key in object) {
  console.log(key);
}

📝 Summary

✅ Remember:

  • Do-While: Runs at least once, checks condition after
  • For-In: Loop through object properties/keys
  • Use do-while for menus and validation
  • Use for-in for objects, not arrays