# Build an array of square and square root of user input

4 visualizaciones (últimos 30 días)
Mina el 4 de Jun. de 2021
Editada: David Fletcher el 4 de Jun. de 2021
The aim of this project is to build an array depending on a number from 1 to 10 entered by the user.
From 1 to num, all multiples of 2 should be squared and for all other numbers, the element should be square rooted.
Build the array sqr as the square or square-root (see story above) of all the numbers from 1 to the number entered by the user.
Display the array you built.
##### 4 comentariosMostrar 2 comentarios más antiguosOcultar 2 comentarios más antiguos
Bob Thompson el 4 de Jun. de 2021
What is the specific problem you're having with the code? This seemed to work for me.
Mina el 4 de Jun. de 2021
I'm not sure how to display the outputs as an array

Iniciar sesión para comentar.

David Fletcher el 4 de Jun. de 2021
Editada: David Fletcher el 4 de Jun. de 2021
The code you have written largely does what is asked, the only thing that is missing is that you are throwing the calculated sqr value away on each iteration of the loop rather than building an array from the values. You just need to save the values into the sqr vector by using the loop iterator to index into the vector. I suppose if you are being pedantic, the question asks you to display the array that has been built wheras you are displaying each value separately as it is calculated, but I think you've demonstated you can easily remedy that yourself.
clear
num = input('Please enter your favourite number between 1 and 10: ');
while num < 1 || num > 10
num = input('Invalid input. Please enter your favourite number between 1 and 10: ');
end
sqr = 1:num;
for i = 1:num
if mod(i,2) == 0
sqr(i) = i.^2;
else
sqr(i) = sqrt(i);
end
fprintf ('%6.4f \n', sqr(i));
end
disp(sqr);
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Categorías

Más información sobre Linear Programming and Mixed-Integer Linear Programming en Help Center y File Exchange.

### Community Treasure Hunt

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

Start Hunting!

Translated by