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)
26 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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];
end
for current = 0:ceil(length(vector)/2)
%A = input('Enter a number');
fprintf("%d %d ",vector(length(vector)-current),vector(current+1));
%A(length(A)-current),A(current+1));
end
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 Commento
Rik
il 19 Ago 2022
@Cheryl Pope:
You can contact Mathworks support if you want either to be deleted, I will not do so.
Risposta accettata
Rik
il 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.
2 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!