This section contains carefully selected MCQs and Previous Year Questions with explanations to help students understand concepts and prepare effectively for examinations, interviews, and competitive tests.
Q: 1Consider the following segment of C++ code.
int j, n;
for(j=1;j<=n;)
j=j*2;
What is the number of comparisons made in the execution of the loop for any n>0?
Option D
The given C++ code is:
int j, n;
for(j = 1; j <= n;)
j = j * 2;
Here, the value of j starts from 1 and becomes twice its previous value after every iteration. The values of j will be, 1 → 2 → 4 → 8 → 16 → 32 → and so on.
In each iteration, j is multiplied by 2. Therefore, after k iterations: j=2k
The loop continues until j becomes greater than n. Therefore, the number of iterations is approximately: log2 n+1
For example, if n=8:
| Iteration | Value of j |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 4 |
| 4 | 8 |
So, the loop executes 4 times.
Using the formula: log2 8+1 = 3+1 = 4
Therefore, the number of iterations is log2 n+1.
Q: 2Find output of the following program?
void main()
{
int a,b;
for(a=1,b=1;a<5,b<10;b++)
cout<<a;
}
Option C
Here, the important point is the comma operator used in the for-loop condition.
for(a=1,b=1; a<5,b<10; b++)
cout << a;
In a for loop, the condition part can use the comma operator (,). When the comma operator is used, all expressions are evaluated, but the result of the last expression decides the loop condition.
You have reached the end of this topic. Continue learning with the next topic below.
Thank you so much for taking the time to read my Computer Science MCQs section carefully. Your support and interest mean a lot, and I truly appreciate you being part of this journey. Stay connected for more insights and updates! If you'd like to explore more tutorials and insights, check out my YouTube channel.
Don’t forget to subscribe and stay connected for future updates.