Question

In the following code segement, how many times is STMT executed? for (I=N; i >1 ;...

In the following code segement, how many times is STMT executed?

for (I=N; i >1 ; i = i/2)

for (j = 1; j <= N; j++)

STMT

I can do normal summation formula, what throws me off is the first for loop. Any help would be appreciated. Thank you .

0 0
Add a comment Improve this question Transcribed image text
Answer #1

(Please do rate the answer if you found useful - Assuming program is in C++ - Output is attached - Please read comments for explanation)

We can solve this problem by analyzing the time complexity. Total running time complexity of statement will be O(N) - (pronounced Big-Oh of N)

Let us breakdown:

Outer Loop Executes Log2N times - Trace the value like first assume N=5 hence Outer loop executes Log25 = 2

next assume N=15 Outer Loop executes Log215 = 3 (Note - Example tracing is shown below as images)

Inner Loop Executes Count of outer loop times N - Trace value First assume N=5 hence Outer loop executes Log25 = 2 then Inner loop executes N*2 = 10, Now assume N=15 Outer Loop executes Log215 = 3 inner loop executes N*3=45

Hence lets call Outer loop executes Log2N times and inner loop executes N*Log2N times Hence complexity of total program is O(NLog2N)

Simple Program for Clear Understanding

#include <iostream>

using namespace std;

int main()
{
int i,j,n;
cout<<"Enter N:";
cin>>n;
int firstloop=0,secondloop=0; //count for outerloop and innerloop
for (i=n; i >1 ; i = i/2)
{
firstloop++; //incrementing count
cout<<"First loop"<<i<<endl;
for (j = 1; j <= n; j++)
{
secondloop++;   //incrementing count
cout<<"Secondloop"<<j<<endl;
}
}
cout<<"First Loop Count :"<<firstloop<<endl<<"Second Loop Count :"<< secondloop<<endl;
return 0;
}

Output

Add a comment
Know the answer?
Add Answer to:
In the following code segement, how many times is STMT executed? for (I=N; i >1 ;...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT