I am trying to write a program for adding the natural numbers from 1 to n (1 + 2 + 3 + ... + n). However, the sum appears 1 when I use if
statement. And when I use for-next
statement there is a syntax error that I don't understand.
if
:
30 let s = 0
40 let i = 1
50 s = s + i
60 i = i + 1
70 if i<=n, then goto 50
80 print s
for-next
:
30 let i, s
40 s = 0
50 for i = 1 to n
60 s = s + i
70 next i
80 print n
if
statement code gives a result of 1, but it should be 55.for-next
statement, it gives no result saying that there is a syntax error in 30.Why is this happening?
The following code works in this online Basic interpreter.
10 let n = 100
30 let s = 0
40 let i = 1
50 s = s + i
60 i = i + 1
70 if i <= n then goto 50 endif
80 print s
I initialised n
on the line labelled 10, removed the comma on the line labelled 70 and added an endif
on the same line.
This is the for-next
version:
30 let n = 100
40 let s = 0
50 for i = 1 to n
60 s = s + i
70 next i
80 print s
(btw, the sum of the first n
natural numbers is n(n+1)/2
:
10 let n = 100
20 let s = n * (n + 1) / 2
30 print s
)