Asked by Ilker Enes Çirkin
on 28 May 2019

I just couldn't figure out how to convert it into a while loop. here is the code:

clc;

clear;

clear all;

n=input('Enter the number of elements in your array:'); % number of array elements

for i=1:n

values(i)=input('Enter the values:')

if values(i)<0

values(i)=values(i)*(-1)

end

end

for k=1:(n-1)

d=k+1

Xaverage(k)=(values(d)+values(k))/2

end

y=1:1:n;

plot(values,y)

hold on

z=1:1:(n-1);

plot(Xaverage,z)

Answer by James Tursa
on 28 May 2019

Accepted Answer

This for loop:

for i=1:n

% stuff

end

is equivalent to this while loop:

i = 1;

while i <= n

% stuff

i = i + 1;

end

Your biggest problem is you never increment i or k in your while loops.

Ilker Enes Çirkin
on 28 May 2019

James Tursa
on 28 May 2019

Please post your current code.

Sign in to comment.

Answer by Ilker Enes Çirkin
on 28 May 2019

This is my current code:

n=input('Enter the number of elements in your array:'); % number of array elements

i=1;

while i<=n

i=i+1;

values(i)=input('Enter the values:')

if values(i)<0

values(i)=values(i)*(-1)

end

end

k=1;

while k<=(n-1)

k=k+1;

d=k+1

Xaverage(k)=(values(d)+values(k))/2

end

y=1:1:n;

plot(values,y)

hold on

z=1:1:(n-1);

plot(Xaverage,z)

James Tursa
on 28 May 2019

Ilker Enes Çirkin
on 28 May 2019

oh thank you so much it works now :)

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Ilker Enes Çirkin (view profile)

## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/464478-how-do-i-convert-this-for-loop-into-a-while-loop#comment_709500

Sign in to comment.