← Previous | 🏠 Homepage | Next Chapter → |
Multiple Initializations in for
Loops
In 'C', the
for
loop is like a 3-in-1 shampoo—initialization, condition, and update all in one line!You can actually start multiple variables like this:
for (i = 1, j = 2; j <= 10; i++, j++) {
// loop body
}
Cool, right? You can update more than one variable too. But only one condition allowed. (Even loops have limits, okay?)
- Why semicolons and not commas?
Because we already use commas inside the parts! Semicolons are like traffic lights—they keep things in order.
The "Odd" Loop
Sometimes you don't know how many times a loop should run—like when your little cousin keeps asking "Why?"
Use a do-while
loop when you need to run at least once, no matter what.
Example:
char another;
int num;
do {
printf("Enter a number: ");
scanf("%d", &num);
printf("Square of %d is %d\n", num, num * num);
printf("Want to enter another number (y/n)? ");
scanf(" %c", &another);
} while (another == 'y');
- do-while
ensures one run—even if the user says "no" first. It’s polite like that.
Odd Loops with for
and while
You can do the same as above using for
or while
:
Using for
:
char another = 'y';
int num;
for (; another == 'y';) {
// same code as above
}
Using while
:
char another = 'y';
int num;
while (another == 'y') {
// same code
}
They're like siblings—different styles, same work.
The break
Statement
Imagine you’re in a boring session or lecture. You suddenly remember your dosa is on the way—you break out!
int i = 2;
while (i <= num - 1) {
if (num % i == 0) {
printf("Not a prime number\n");
break;
}
i++;
}
if (i == num)
printf("Prime number\n");
- break
jumps out of the loop like a ninja.
The continue
Statement
Ever ignored someone mid-conversation to avoid drama? That’s what continue
does.
for (i = 1; i <= 2; i++) {
for (j = 1; j <= 2; j++) {
if (i == j)
continue;
printf("%d %d\n", i, j);
}
}
- When i == j
, we skip the rest and jump to the next round!
The do-while
Loop—Always on the First Date
The do-while
loop always gives the loop a first chance, even if the condition is false.
do {
printf("Hello there\n");
} while (4 < 1); // Still prints once!
- do-while
doesn’t care if it’s wrong. It just goes for it!
break
& continue
in do-while
Same as in other loops:
-
break
= Bye! Exit the loop. -
continue
= Skip to the test condition at the end.
TL;DR – Loop Life Lessons
-
Use multiple initializations with commas in
for
loops. -
Use
do-while
when you want at least one run. -
Use
break
to escape a loop when needed. -
Use
continue
to skip the rest and go again. -
Loops are like driving a bicycle—you control the ride!
No comments:
Post a Comment