Group Abstract Group Abstract

Message Boards Message Boards

0
|
4.7K Views
|
2 Replies
|
1 Total Like
View groups...
Share
Share this post:

Get sum of the first fifty positive even numbers?

Posted 6 years ago

The For loop that I input was

For[natNum = 2, natNum <= 50, natNum = natNum + 2, Print[natNum]]

This gives me a list of numbers from 2 to 50 and it is increasing by 2. Now I need to add these numbers, but I am not sure where to inster the Sum command. I was thinking on doing

Sum[For[natNum = 2, natNum <= 50, natNum = natNum + 2, Print[natNum]]]

, but the output shows an error.

POSTED BY: Laura Figueroa
2 Replies
Posted 6 years ago

Using For loops is frowned upon in MMa, also using Do loops, though I use Do loops if when trying to fit everything into memory fails. However, there are quite a few ways to achieve your desired result. You could just use the Sum command and forget about any For loops like so.

Sum[i, {i, 2, 50, 2}]

Other methods are:-

Total[Range[2, 50, 2]]

Total[Table[i, {i, 2, 50, 2}]]

n = 0; Do[n = n + i, {i, 2, 50, 2}]; n

and if you must use For loop, this works

m = 0; For[n = 0, n <= 50, n += 2, m = m + n]; m
POSTED BY: Paul Cleary
Posted 6 years ago
Range[2, 50, 2] // Total
(* 650 *)
POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard