Question

From a sequence of integers, finished with the value 0, and entered by keyboard, we are...

From a sequence of integers, finished with the value 0, and entered by keyboard, we are asked to calculate the number of mountains and valleys it has. (algorithm in C)

Mountain is called a set of 3 consecutive values where the value of the medium is higher than its neighbors (the previous and the later). Valley is called the opposite case, a set of three consecutive values where the value of the medium is lower than that of its neighbors. For example, in the following sequence there are 3 mountains and 3 valleys.

`3 4 7 2 3 1 9 8 5 2 7 0`

** Attention **: The same number can be part of a mountain (4, 7, 2) and a valley (7, 2, 3).

**Note:**
- The empty sequence can be given.
- If there is data, there will always be at least 3.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<stdio.h>

int main()

{

int a[40],mountain=0,valley=0,i,len;

len=0;

printf("\nEnter the sequence of number :");

while(1)

{

scanf("%d",&a[len]);

if(a[len]==0)

break;

else

len+=1;

}

for(i=1;i<len-1;i++)

{

if(a[i]>a[i-1]&&a[i]>a[i+1])

{

mountain+=1;

printf("\nMountain :(%d,%d,%d)",a[i-1],a[i],a[i+1]);

}

if(a[i]<a[i-1]&&a[i]<a[i+1])

{

valley+=1;

printf("\nValley:(%d,%d,%d)",a[i-1],a[i],a[i+1]);

}

}

printf("\nThe total # of valleys:%d",valley);

printf("\nThe total # of mountains:%d",mountain);

}

Algorithm

  1. Start
  2. Initialize array a[], valley=0, mountain, i, len
  3. accept value in array a[] untill zero is encountered
  4. Calculate the length of array in len
  5. For i=1 to len-1
  6. if(a[i]>a[i-1]&&a[i]>a[i+1])
  7. ​​​​​​increment mountain by 1
  8. else if(a[i]<a[i-1]&&a[i]<a[i+1])
  9. increment valley by 1
  10. Go to step 6 if I<len-1
  11. Print value of mountain and valley
  12. Stop

​​​​​​I hope the code help you in understanding the problem better.

if you have any questions comment down and please upvote thanks

Add a comment
Know the answer?
Add Answer to:
From a sequence of integers, finished with the value 0, and entered by keyboard, we are...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT