Calculate sequence of triangular numbers smaller than 1000

Asked

Viewed 439 times

0

I’m a beginner in programming and I’m struggling with the following problem:

Make a program that calculates and prints all triangular numbers smaller than 1000.

A triangular number is a natural number which can be represented in equilateral triangle shape. To find the nth number triangular from the previous one just add n units. A sequence of triangular numbers (sequence A000217 in OEIS), starting with the 0 th term, is:

0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

My code went like this:

#include<iostream>
using namespace std;

int main(){
    int b, a;
    for (a = 0, b = 0; b < 1000;a++){
        b = (a + 1) + b;
        cout << b << endl;
    }
    return 0;
}

The only problem is that when I compile, it goes up to 1035.

2 answers

4

The problem is that the for tests the condition before executing the inner block, then the test b < 1000 occurs before the b = (a + 1) + b;.

A simple solution would be to pass the calculation into the for:

#include<iostream>
using namespace std;

int main(){
    int b, a;
    for (a = 0, b = 0; b < 1000; b = (a + 1) + b, a++) {
                              // ^^^^^^^^^^^^^^^^^^
                              // isto é processado ao final do bloco
                              // atenção à ordem do b antes do a++
        cout << b << endl;
    }
    return 0;
}

See working on IDEONE.


The above code is equivalent to reversing the "print position":

#include<iostream>
using namespace std;

int main(){
    int b, a;
    for (a = 0, b = 0; b < 1000;a++){
        cout << b << endl;
        b = (a + 1) + b;
    }
    return 0;
}

See working on IDEONE.


More in:

For rule in C

I can’t learn syntax for

3

The problem is that you first increase the value of b, to then display it. If you just reverse the order it will work:

int main(){
    int b, a;
    for (a = 0, b = 0; b < 1000;a++){
        cout << b << endl;   //  <---+-- Essas duas linhas foram invertidas
        b = (a + 1) + b;     //  <---+
    }
    return 0;
}

You can even simplify this by increasing the number together in the for:

int main() {
    for (int i = 1, numero = 0; numero < 1000; i++, numero += i+1) {
        cout << numero << endl;
    }
}

The name of the variables does not influence, but so I found more readable the code than a and b.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.