Correct Answer: Ensure that the loop termination condition is reachable and properly updated
Explanation: To avoid unintentional infinite loops, it’s crucial to ensure that the loop termination condition can be reached and is correctly updated within the loop body.
Correct Answer: Loop sentinel
Explanation: A loop sentinel is a condition that, when met, terminates the loop and prevents it from running infinitely.
#include <stdio.h>
int main() {
int i = 0;
do {
printf("%d ", i);
} while (--i);
return 0;
}
Correct Answer: No output
Explanation: The loop condition “–i” decrements i before evaluating it, so when i becomes negative, the condition becomes false, leading to no output.
Correct Answer: Infinite loops always lead to system crashes.
Explanation: While infinite loops can consume CPU resources and cause programs to become unresponsive, they don’t always lead to system crashes; however, they can if not properly handled.
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
printf("%d ", ++i);
i = i - 2;
}
return 0;
}
Correct Answer: 1 3 5 7 9
Explanation: The loop increments i by 1 each iteration, then subtracts 2 from it, resulting in odd numbers less than 10 being printed.
Correct Answer: Using debugging tools to identify and fix the cause
Explanation: Using debugging tools allows developers to identify the cause of unintentional infinite loops and fix the issue efficiently.
#include <stdio.h>
int main() {
int i = 5;
while (i > 0) {
printf("%d ", i++);
}
return 0;
}
Correct Answer: This code will result in an infinite loop
Explanation: The value of i is incremented inside the loop, causing it to continually increase without reaching the termination condition.
Correct Answer: The break statement
Explanation: The break statement is used to terminate the loop and exit it immediately, breaking out of an infinite loop.
#include <stdio.h>
int main() {
int i = 0;
while (1) {
if (i > 5)
break;
printf("%d ", i);
i++;
}
return 0;
}
Correct Answer: 0 1 2 3 4 5
Explanation: The loop continues until i becomes greater than 5, at which point the break statement is encountered, terminating the loop.
Correct Answer: They may lead to excessive CPU usage.
Explanation: Intentional infinite loops can lead to excessive CPU usage, especially in long-running programs, consuming system resources unnecessarily.