1. Write a Matlab program using WHILE loop that computes the sum of the elements
ID: 3802809 • Letter: 1
Question
1. Write a Matlab program using WHILE loop that computes the sum of the elements of an array. Load the lab7.mat file and from it, use Array1 as the sample array to compute the sum. Use the length command to know the elements in the array.
Write a Matlab program using WHILE loop that computes the largest element of an array. Load lab7.mat, and use Array1 as the sample array to test your program. Use the length command to know the elements in the array.
Use a while loop to write a program that given a vector of numbers computes how many numbers are greater than 10. Use Array2 to check your program.Write a program that reads numbers from the user and computes their sum until the user enters a negative number. Test program to illustrate functionality.
Array1 =
71 3 28 5 10 82 69 32 95 3 44 38 77 80 19
Array2 =
7 5 10 3 11 4 1 12 15 2
Explanation / Answer
Program 1:
Array1=[71 3 28 5 10 82 69 32 95 3 44 38 77 80 19];
arr1Len = length(Array1);
i=1;
sumArray1 = 0;
while(i<=arr1Len)
sumArray1 = sumArray1 + Array1(i);
i=i+1;
end
fprintf('Sum : %d ',sumArray1);
Program 2:
i=2;
maxArray1=Array1(1);
while(i<=arr1Len)
if(maxArray1<Array1(i))
maxArray1 = Array1(i);
end
i=i+1;
end
fprintf('Max Value : %d ',maxArray1);
Program 3:
Array2=[7 5 10 3 11 4 1 12 15 2];
count =0;
sumGreater10 = 0;
i=1;
arr2Len = length(Array2);
while(i<=arr2Len)
if(Array2(i)>10)
sumGreater10 = sumGreater10 + Array2(i);
count = count + 1;
end
i=i+1;
end
fprintf('Number of element greater than 10 is : %d ',count);
Program 4:
x = input('Enter number : ');
sumArr = x;
while(x>0)
x = input('Enter number : ');
sumArr = sumArr + x;
end
fprintf('Sum : %f ',sumArr);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.