while loop to sum elements

9 ビュー (過去 30 日間)
leon leon
leon leon 2013 年 10 月 16 日
回答済み: Maneet Kaur Bagga 2022 年 7 月 5 日
Use a while loop to sum up the elements of a vector (starting with the first element) until the sum is bigger than 14. Print out a message if the sum never gets bigger than 14. Otherwise, print out the sum. Both print statements should happen AFTER the loop has finished. Test the while loop with x=[2.2 4 9 7 8] and x=[-4 5 3 -5 1 -10 1 8]. Hint: A simple way to swap from one x to the other is to declare both assignments and just comment one out. Then you can demonstrate both to the TA without having to make a copy of the while loop. eg %x =[2.2 4 9 7 8]; x=[-4 5 3 -5 1 -10 1 8] Hint: You will need an index variable to tell if you’ve gone past the end of the array.
  1 件のコメント
Image Analyst
Image Analyst 2013 年 10 月 16 日
編集済み: Image Analyst 2013 年 10 月 16 日
If you're telling us to do your homework for you, that's not quite how this works. See http://www.mathworks.com/matlabcentral/answers/8626-how-do-i-get-help-on-homework-questions-on-matlab-answers

サインインしてコメントする。

回答 (1 件)

Maneet Kaur Bagga
Maneet Kaur Bagga 2022 年 7 月 5 日
As per my understanding you want to find the sum of elements of the vector until the sum gets gretaer than 14 and want to print the result after the loop ends. Please find the below attached code as a solution. Hope it helps!
x = [1:10]
x = 1×10
1 2 3 4 5 6 7 8 9 10
sum=0
sum = 0
x = sort(x)
x = 1×10
1 2 3 4 5 6 7 8 9 10
i=1
i = 1
while(sum<14 && i<=length(x))
sum = sum + x(i)
if(sum==14)
break;
end
i = i + 1
end
sum = 1
i = 2
sum = 3
i = 3
sum = 6
i = 4
sum = 10
i = 5
sum = 15
i = 6
if(sum==14)
display("Sum exists");
elseif(sum<14 && i==length(x))
display("Sum can never be 14")
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by