UP | HOME

Exercise 6 solutions

Table of Contents


Python

e06.py

n = int(raw_input("enter n: "))
sum = 0
for i in range(n+1):
    sum = sum + i
print "the sum of the first %d positive integers is: %d" % (n, sum)

MATLAB / Octave

e06.m

n = input('enter n: ');
sum = 0;
for i=1:n
  sum = sum + i;
end;
disp(['the sum of the first ',num2str(n),' positive integers is: ',num2str(sum)]);

R

e06.R

n <- as.integer(readline("enter n: "))
sum <- 0
for (i in 1:n) {
    sum <- sum + i
}
cat("the sum of the first",n,"positive integers is:",sum,"\n")

C

e06.c

// compile with: gcc -o e06 e06.c

#include <stdio.h>

int main(int argc, char *argv[]) {

  int n;
  printf("enter n: ");
  scanf("%d", &n);
  int sum = 0;
  int i;
  for (i=1; i<=n; i++) {
    sum = sum + i;
  }
  printf("the sum of the first %d positive integers is: %d\n", n, sum);

  return 0;
}

Paul Gribble | fall 2014
This work is licensed under a Creative Commons Attribution 4.0 International License
Creative Commons License