C For Loop MCQ Questions and Answers
Q. What is the purpose of a 'for' loop in C programming?
To repeat a block of code a fixed number of timesTo iterate through a collection of items
To make the program wait for a specified duration
To execute a set of instructions indefinitely
Q. How do you write a 'for' loop to display the numbers from 1 to 10?
for (int i = 1; i <= 10; i++) {for (int i = 1; i < 10; ++i) {
for (int i = 1; i <= 10) {
for (int i = 1; i < 11; i++) {
Q. What is the output of the following code snippet?
<code>for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
continue;
}
printf("%d ", i);
}</code>
1 2 3 4 51 3 5
2 4
None of the above
Q. What is the difference between a 'for' loop and a 'while' loop in C?
'for' loop is used for a fixed number of iterations, while 'while' loop is used for an indefinite number of iterations.'for' loop uses a pre-test condition, while 'while' loop uses a post-test condition.
'for' loop is faster than 'while' loop.
'while' loop is used for iterating through arrays, while 'for' loop is not.
Q. How can you iterate through an array using a 'for' loop?
for (int i = 0; i < array_size; i++) {for (int i = 1; i <= array_size; ++i) {
for (int i = 0; i <= array_size; i++) {
for (int i = 1; i < array_size; i++) {
Q. What is the output of the following code?
<code>int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
printf("Sum: %d", sum);</code>
Sum: 15Sum: 10
Sum: 20
Sum: 5
Q. How can you use a 'for' loop to find the maximum value in an array?
for (int i = 0; i < array_size; i++) {if (array[i] > max) {
max = array[i];
}
}
for (int i = 0; i < array_size; ++i) {
max = array[i];
}
for (int i = 0; array[i] < max; i++) {
max = array[i];
}
for (int i = 0; i < array_size; ++i) {
if (array[i] > array[i+1]) {
swap(array[i], array[i+1]);
}
}
Q. What is the output of the following code?
<code>for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
printf("%d ", i);
}</code>
1 21 2 3
1 2 3 4 5
1 2 4 5
Q. How can you use a 'for' loop to print the even numbers from 2 to 20?
for (int i = 2; i <= 20; i++) {if (i % 2 == 0) {
printf("%d ", i);
}
}
for (int i = 2; i <= 20; i += 2) {
printf("%d ", i);
}
for (int i = 2; i <= 20; ++i) {
if (i % 2 != 0) {
printf("%d ", i);
}
}
for (int i = 2; i < 20; i += 2) {
printf("%d ", i);
}