Getting an increasing every other while loop for m+1 up to k. If m<k
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello I am completing this assignment and I am having trouble with getting my loop to work. This is the question:
3. Prompt the user twice for numeric input. Assume the user enters two positive integers m and k, where m < k. Then use a while loop to iterate k-m+1 times, printing the “i-th” value every other time. The “i-th” val starts at m and ends at k, incrementing once per iteration. For example, m = 3 and k = 9 would output
4
6
8
I started with this code:
m = input("Smaller positive integer ");
k = input("Larger positive integer ");
while m < k-1
m = m+2;
disp(m);
end
As you can see it did not give me the right output.
So I then made some tweaks and added in a mod and now I have this:
m = input("Smaller positive integer ");
k = input("Larger positive integer ");
i = 1:(k-m);
t = mod(i,2);
while m < k
m = i.*t.*(m+1);
disp(m');
end
Which is still incorrect.
What can I change to get the correct output for any input of m and k as long as m<k?
0 commentaires
Réponses (2)
Parth Dethaliya
le 15 Juil 2020
By looking at the problem statement it seems if m=3; and k=9; then there will be k-m+1 = 9-3+1 = 7 iterations. On each iteration ith value is to be displayed starting from m so, output will be,
4,5,6,7,8,9 not 4 6 8.
Anyway I have given code for the output I suggested you can tweek according to your usage.
m = input("Smaller positive integer ");
k = input("Larger positive integer ");
if k<m
error('k is smller tha m, please give correct input')
end
counter = k-m+1;
Init = 0;
while counter>1
disp(string(m+Init))
Init = Init+1;
counter = counter -1;
end
1 commentaire
Tanmay Das
le 15 Juil 2020
Hi,
I have the understanding that you want to print i-th value in every alternative iteration. The following code may be helpful for your understanding:
m = input("Smaller positive integer ");
k = input("Larger positive integer ");
if k<m
error('k should be larger than m')
end
count = 0;
for i = m:k
count = count+1;
if rem(count,2)==0
disp(i);
end
end
Hope that helps!
0 commentaires
Voir également
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!