reads in n numbers from the user storing the numbers in a vector. Print the numbers from the ends inwards (last, first, second last, second, third)

4 views (last 30 days)
How many numbers will you enter?: 5
Enter a number: 3
Enter a number: 5
Enter a number: 6
Enter a number: 4
Enter a number: 3
Your numbers from outside to middle are: 3 3 4 5 6
Let the element output follow the following rules: output last bit, output first, output penultimate second, input second
This is my code
%current is going from 1 to length of vector(maybe)
current = 0;
num = input('How many numbers will you enter?: ');
vector = [];
for i = 1:num
ele = input("Please enter the elements: ");
vector = [vector ele];
for current = 0:ceil(length(vector)/2)
%A = input('Enter a number');
fprintf("%d %d ",vector(length(vector)-current),vector(current+1));
It will have extra numbers in the last. like that
How many numbers will you enter : 6
Please enter the elements: 1
Please enter the elements: 2
Please enter the elements: 3
Please enter the elements: 4
Please enter the elements: 5
Please enter the elements: 6
6 1 5 2 4 3 3 4
How to improve this code?
  1 Comment
Rik on 19 Aug 2022
@Cheryl Pope:
For this question you have even less standing than the other question you requested deletion for.
You can contact Mathworks support if you want either to be deleted, I will not do so.

Sign in to comment.

Accepted Answer

Rik on 28 Mar 2022
You are asking the user for the number of elements. You should use that to pre-allocate the vector array so you can use indexing in your first loop.
For the second loop you should create a vector with the appropriate indices. Changing ceil to floor will not fix the problem. Perhaps the sort function can help you generate the indices.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!