Intro to Programming: Using Loops
USING LOOPS
INTRODUCTION
Looping, also called iteration, is a crucial feature in programming.
It allows you to repeat a set of statements until specific conditions are met.
In C, there are three primary loop constructs:
The
whilestatementThe
do-whilestatementThe
forstatement
THE WHILE LOOP
The
whileloop repeatedly executes a statement while a given condition is true.When the condition is no longer true, the loop terminates.
General form of the
whilestatement:
while (expression) {
statement;
}Example Using the While Loop:
int x = 1;
while (x <= 5) {
printf("%d ", x);
x++;
}THE DO-WHILE LOOP
The
do-whileloop ensures that the statements in the loop are executed at least once before testing the condition.
General form of the do-while statement:
do {
statement;0
} while (expression);Example Using the Do-While Loop:
int y = 1;
do {
printf("%d ", y);
y++;
} while (y <= 5);
THE FOR LOOP
The
forloop provides a more concise way to control loops and combines initialization, condition, and increment in one line.General form of the
forstatement:for (expression1; expression2; expression3) { statement; }Example Using the For Loop:
for (int i = 1; i <= 5; i++) { printf("%d ", i); }
THE NULL STATEMENT
The
forstatement does not end with a semicolon; it contains either a statement block or a single statement.A
forstatement can have a null statement represented by a semicolon.
Example Using the Null Statement:
for (int i = 1; i <= 5; i++)
; // This is a null statementUSING COMPLEX EXPRESSIONS IN A FOR STATEMENT
You can use the comma operator to combine multiple expressions in the three parts of a
forstatement.
Example Using Complex Expressions in a For Loop:
for (int i = 1, j = 10; i != j; i++, j--) {
/* statement block */
}USING NESTED LOOPS
Nested loops involve putting one loop inside another, creating inner and outer loops.
When the program reaches an inner loop, it runs like any other statement inside the outer loop.
Example Using Nested Loops:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d %d ", i, j);
}
printf("\n");
}SUMMARY
Looping in C is a powerful feature that allows you to repeat code until specific conditions are met.
The three loop statements,
while,do-while, andfor, offer different ways to implement loops.Pay attention to semicolon placement in
forstatements to avoid unintended consequences.You can use complex expressions in a
forloop by using the comma operator.Nested loops are used when you need to create a loop within a loop, and inner loops complete before outer loops.