Question

# MATLAB Task: Use a for loop to find how many numbers you have to add to...

MATLAB

Task: Use a for loop to find how many numbers you have to add to get a sum greater than 1,000. The numbers in the problem are consecutive, so adding up 1+2+3+4+5+6+.... until you reach the user defined value 1000.

Method : must Make a variable equal to 1 then add 2, 3, 4...to it, until you reach 1000, then you break out the loop once the sum hits 1,000.

Following is the matlab script in which the code is implemented

MATLAB Code:

% sum is a global variable

sum = 1;

count = 1;

% for loop from 2 to 1000, we have taken upper limit as 1000 otherwise the sum exceedes 1000

for temp = 2:1000

sum = sum + temp;

count = count + 1;

% If sum exceeds 1000 then break

if (sum > 1000)

break;

end

end

% Display the output

fprintf('We need to add %d consecutive numbers to get a sum greater than 1000', count)

Proof:

1 + 2 + 3 +..................... + 44 = 990 < 1000

1 + 2 + 3 +............................ + 45 = 1035 > 1000

Please refer to the following picture for indentation and the output shown in the command window below:

#### Earn Coins

Coins can be redeemed for fabulous gifts.