Calculate a sequence of triangular numbers less than 1000

0

I'm a beginner in programming and I'm having trouble with the following problem:

  

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

     

A triangular number is a natural number that can be represented in the triangular number

  equilateral triangle shape. To find the nth number   triangular from the previous just add n units. THE   triangular numbers (sequence A000217 in the OEIS),   beginning with the 0th term, is:

     

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

My code looks 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 to 1035.

    
asked by anonymous 15.08.2018 / 16:00

2 answers

4

The problem is that for tests the condition before executing the inner block, so the test b < 1000 occurs before 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 at IDEONE .


The above code is equivalent to reversing the "impression" 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 at IDEONE .


More on:

  

C For Rule

  

I can not learn syntax for

    
15.08.2018 / 16:09
3

The problem is that you first increment the value of b , and 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 incrementing the number together in the for structure:

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

The variable name does not influence, but I find the code more readable than a and b .

    
15.08.2018 / 16:24