What is the value of n and counter when the code below is executed?
n = 256; counter = 1; while n ~= 1 if rem(counter,2) == 0
n = n/2;
else
n = n/4;
end counter = counter + 1 ; end
a.
n=1;
counter = 6
b.
n=5;
counter = 6;
c.
n=6;
counter = 256;
d.
n=256
counter = 6
e.
n=128;
counter=64;
Here the answer is solved witth the following steps.
Step 1: At first the answer the given with correct option.
Step 2: After that the explanation of the answer is given point wise in details.
Stpe 3: A complete matlab code with screen shot and output is given. From the output the explanation is verified.
Correct option: a) n=1;
counter = 6
Explanation:
i. n=256, counter=1
As n is not equal to 1
Here, mod (counter, 2) is not equal to 0, because mod (1, 2)=1, so else condition satisfies,
Then, n=n/4
n=256/4=64
counter=counter+1 or counter=1+1=2
ii. n=64 , counter=2
now again n is not equal to 1
As, rem(counter,2) is equal to 0, because mod(2,2)=0, so if condition satisfies,
Then n=n/2
n=64/2=32
counter=counter+1 or counter=2+1=3
iii. n=32, counter=3
As n is not equal to 1
Here, mod (counter, 2) is not equal to 0, because mod (3, 2)=1, so else condition satisfies,
Then, n=32/4
n=32/4=8
counter=counter+1 or counter=3+1=4
iv. n=8 , counter=4
now again n is not equal to 1
As, rem(counter,2) is equal to 0, because mod(4,2)=0, so if condition satisfies,
Then n=n/2
n=8/2=4
counter=counter+1 or counter=4+1=5
v. n=4, counter=5
As n is not equal to 1
Here, mod (counter, 2) is not equal to 0, because mod (5, 2)=1, so else condition satisfies,
Then, n=n/4
n=4/4=1
counter=counter+1 or counter=5+1=6
vi. Now n =1, so, while loop will not be executed and loop will be broken.
So, finally, n=1 and counter=6
Answer: n=1, counter=6
HERE THE ABOVE EXPLAINED PROGRAM IS DONE WITH COMPLETE MATLAB PROGRAMMING LANGUAGE.
n = 256;
counter = 1;
while n ~= 1
if rem(counter,2) == 0
n = n/2;
else
n = n/4;
end
counter = counter + 1 ;
end
fprintf('n=%d\ncounter=%d\n',n,counter);
SCREEN SHOT
OUTPUT
Get Answers For Free
Most questions answered within 1 hours.