3

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
  1. When I take n = 10, the if statement code gives a result of 1, but it should be 55.
  2. When I try to use the for-next statement, it gives no result saying that there is a syntax error in 30.

Why is this happening?

Sep Roland
  • 33,889
  • 7
  • 43
  • 76

3 Answers3

5

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

)

peter.cntr
  • 308
  • 2
  • 8
2

Why is this happening? Where am I mistaking?

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

Fix #1: Initialize variable 'n':

20 let n = 10

Fix #2: Remove comma from line 70:

70 if i<=n then goto 50
30 let i, s
40 s = 0
50 for i = 1 to n
60 s = s + i
70 next i
80 print n

Fix #1: Initialize variable 'n':

30 let n = 10

Fix #2: Print 's' instead of 'n':

80 print s
Everton
  • 12,589
  • 9
  • 47
  • 59
0
10 cls
20 let x=1
30 for x=1 to 100
40 print x
50 next x
60 end