Write an algorithm that takes as input: (a) The size of a list, n (b) a list of
ID: 3783834 • Letter: W
Question
Write an algorithm that takes as input:
(a) The size of a list, n
(b) a list of numbers N1, . . . , Nn.
The algorithm goes over the list, counting the number of elements that are > 0 (positive), and nding their product, and counting the number of elements that are < 0 (negative), and nding their sum. The algorithm then prints all this information. For example, if the list consists of the elements {2,-5,8,-1,0,7}, the following will be printed:
- There are 3 positive numbers. Their product is 112.
- There are 2 negative numbers. Their sum is -6.
Explanation / Answer
Step 1: Take an array of size of a list, n.
Step 2: for every element of the array check whetehr it is positive or negative
Step3: If the number is a positive number do product*=array[n]
Step4: If the given number is a negative number Sum+=array[n]
Step5: Print values of product and Sum.
Get n from user
for 1 to n get n1 n2 n3, ...nn from the user.
set product=1, sum=0, count1=0, count2=0;
for 1 to n
if(arr[i]>0)
set product*=arr[i]
count1++;
else
set sum+=arr[i];
count2++;
printf("There are %d number of positive numbers. Their product is %d", count1, product);
printf("There are %d number of negative numbers. Their product is %d", count2, sum);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.