Question

3. Chapter 7. Write an algorithm that accepts an array of positive integers and two more positive integers. The algorithm sho
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Algorithm :

Step 1 of 4 :

Input the array elements of positive integers.

int arr[size];

for (i=0;i<size;i++)

{

cin>>arr[i];

}

Step 2 of 4 :

Input the two numbers for which the numbers between them are to be selected.

int a,b;

cin>>a>>b;

Step 3 of 4 :

Iterate through the loop and check if the element is greater than min(a,b) and less than max(a,b).

If the element satisfies this range then put that element in a new array.

int newarray[size];

k=0;

for (i=0;i<size;i++)

{

if (arr[i]>=min(a,b) && arr[i]<=max(a,b))

{

newarray[k]=arr[i];

k++;

}

}

Step 4 of 4 :

print the new array .

for(i=0;i<k;i++)

{

cout<<newarray[i];

}

=> The above algorithm iterates through the array size ( n ) times. Therefore, the number of comparisons would be n and the time complexity of the above algorithm in terms of Big-O will be O(n). An example of the above algorithm is given below. If you have any queries please comment in the comments section and kindly upvote.

#include<iostream>
using namespace std;
int main()
{
// input the size of the array
cout<<"Enter the size of the array\n";
int n;
cin>>n;
// create an array of size n
int arr[n];
// input array elements
cout<<"Enter the elements\n";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
// input the two numbers a and b
int a,b;
cout<<"Enter the two numbers\n";
cin>>a>>b;
// compare and put the elements in the new array
int newarray[n];
int k=0;
for(int i=0;i<n;i++)
{
if(arr[i]>=min(a,b) && arr[i]<=max(a,b))
{
newarray[k]=arr[i];
k++;
}
}
// print the new array
for(int i=0;i<k;i++)
{
cout<<newarray[i]<<" ";
}
return 0;
}

#include<iostream> using namespace std; int main() // input the size of the array cout<<Enter the size of the array\n; intint n; cin>>n; // create an array of size n int arr[n]; // input array elements cout<<Enter the elements\n; for (int i=0;i<Enter the size of the array Enter the elements 16 33 Enter the two numbers 13 20 16 19 14 15 Process returned o (@xo_ Press a

Add a comment
Know the answer?
Add Answer to:
3. Chapter 7. Write an algorithm that accepts an array of positive integers and two more...
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