Writing a function that computes the sum from 1 to an input using the while loop?
Mostrar comentarios más antiguos
I need help composing a function that computes the sum of numbers from 1 to n (n being an input) using a “while" loop. I know that this could possibly done without using a loop, but I need to construct one without the loop. The input would be a single integer and the goal that computes the sum from 1 to n.
4 comentarios
@Amanda Mnt: What have you tried so far? The more you think, the more you attempt (even if it does not work), the more you will learn. If you put in some effort into solving this then you will learn more from doing that course. Really those instructions tell a lot about how to do this: think about what you need to loop over. Think about how you can use a while to loop over it. Add that value on each loop iteration and you are done.
Amanda Mnt
el 30 de En. de 2017
Editada: Amanda Mnt
el 30 de En. de 2017
Amanda Mnt
el 30 de En. de 2017
@Amanda Mnt: the task is rather artificial, so it will not be obvious, nor even a good use of MATLAB. But if your task is to use a while loop then so be it.
To start with: what do you need to loop over? How can you do that? Read about while loops, try some of the examples. Get comfortable with how they work.
Beginners often try to solve everything at once. Relax, you don't need to do that. Split the task into parts, e.g.: what does the loop need to do? How to sum within the loop? Once you understand the parts, then you can put the parts together.
Respuestas (1)
Jan
el 30 de En. de 2017
Start with a counter, which runs from 1 to n:
x = 1;
n = 10;
while x < n
disp(x)
x = x + 1;
end
Now inster the code for summing: Add the current value to a variable.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!