# Infinite Loop with conditional statement if

3 vues (au cours des 30 derniers jours)
Hdez le 2 Nov 2020
Commenté : Ameer Hamza le 2 Nov 2020
Hello everyone.
I am new to Matlab and I got a question that I have solved but I think it is wrong. It is supposed to be solved with the Conditional statement if
Question: Write a programme that will keep asking the user of the code to enter a value. The code will return the square root of the entered value. The programme should be implemented using an inifinite for loop that will be broken when the user does not need to enter another value.
clc
clear all
for i=1:1:inf
a= input ('Enter a value to be square rooted:');
r= sqrt (a);
fprintf ('The square root of %g is:\n', a)
end
r
I don't know where to add the if, also, is the if condition the reason while the infinite value will be broken? Thank you
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponses (2)

Abdolkarim Mohammadi le 2 Nov 2020
The for loop can be broken using break statement.
for
if
break
end
end
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Hdez le 2 Nov 2020
clc
clear all
for i=1:1:inf
a= input ('Enter a value to be square rooted:');
r= sqrt (a);
if r==10
break;
end
fprintf ('The square root of %g is:\n', a)
end
I have written this in stead but it does not break

Connectez-vous pour commenter.

Ameer Hamza le 2 Nov 2020
Modifié(e) : Ameer Hamza le 2 Nov 2020
You are not printing the square-root value and also not breaking the loop.
clc
while 1
a= input ('Enter a value to be square rooted:');
r= sqrt (a);
fprintf ('The square root of %g is: %f\n', a, r)
m = input ('Do you want to enter another number (Type ''n'' to stop):', 's');
if lower(m)=='n'
break;
end
end
##### 4 commentairesAfficher 2 commentaires plus anciensMasquer 2 commentaires plus anciens
Hdez le 2 Nov 2020
I input 110 but it doesn't break at all
Ameer Hamza le 2 Nov 2020
You gave the condition r==100, Try giving condition r > 100
if r > 10

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by