Sum of first 100 integers?

47 vues (au cours des 30 derniers jours)
Ian
Ian le 3 Fév 2014
Commenté : Jan le 15 Mar 2022
Write a script that uses a for loop to calculate the sum of the first 100 integer numbers

Réponse acceptée

Mischa Kim
Mischa Kim le 3 Fév 2014
Modifié(e) : Mischa Kim le 3 Fév 2014
my_sum = 0;
for ii = 1:100
my_sum = my_sum + ii;
end
  1 commentaire
Lukeus Perez
Lukeus Perez le 3 Mar 2017
You're the best

Connectez-vous pour commenter.

Plus de réponses (4)

Sean de Wolski
Sean de Wolski le 3 Fév 2014
for ii = 100
s = sum(1:ii);
end

Roger Stafford
Roger Stafford le 3 Fév 2014
Modifié(e) : Roger Stafford le 3 Fév 2014
Or you could emulate the mathematical genius, Karl Friedrich Gauss, who is said to have done it this way at the age of ten:
s = (100+1)+(99+2)+(98+3)+...+(51+50) = 50*101 = 5050
  2 commentaires
Ian
Ian le 3 Fév 2014
Gotta love good ol' Gauss!
Jan
Jan le 4 Mar 2021
This means as code:
n = 100;
s = (n * (n + 1)) / 2

Connectez-vous pour commenter.


Mayur Gaikwad
Mayur Gaikwad le 7 Déc 2017
Could someone write the script for matlab mobile version for the sum of the squares of first 100 natural numbers.. !
  1 commentaire
Jan
Jan le 7 Déc 2017
Yes. Simply add a "^2" in Mischa's answer.
Please do not inject a new question as an answer to an existing thread. Such thread-hijacking confuses the readers, because it is not clear anymore, to which question an answer belongs.
Because this sounds like a homework, let me encourage you to try to solve this by your own.

Connectez-vous pour commenter.


Bhanuprasad Akula
Bhanuprasad Akula le 3 Mar 2021
sum(1:100)
  1 commentaire
Jan
Jan le 15 Mar 2022
"uses a for loop"...

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