Triangular number

0

I would like to know why, when I type in the program below, it checks if the number entered is triangular, that is, it is a multiple of three consecutive numbers, for example 60 it prints two "NO" and one "YES", and when I type 336 do five "NAO" and a "YES" appear?

#include <stdio.h>

int main(void)
{
    int numero, i;
    scanf("%d",&numero);

    for(i = 1 ; i*(i+1)*(i+2)<=numero ; i++)    
    {
        if(i*(i+1)*(i+2)==numero)
        {
            printf("SIM\n");
        }
        else
        {
            printf("NAO");
        }
    }
    return 0;
}
    
asked by anonymous 19.04.2015 / 19:48

2 answers

3

When i is 1 the program will do if

if (1 * 2 * 3 == numero)

and either prints "YES \ n" or prints "NO."
When the i is 2 the if becomes

if (2 * 3 * 4 == numero)

and the program prints "YES \ n" or "NO."

That is, the program prints anything every time it runs the loop. What you want and print only once, at the end of the loop.

Using an auxiliary variable can help you:

int variavel_auxiliar = 0;
for(i = 1 ; i*(i+1)*(i+2)<=numero ; i++)    
{
    if(i*(i+1)*(i+2)==numero)
    {
        variavel_auxiliar = 1;
    }
}
if (variavel_auxiliar) printf("SIM\n");
else                   printf("NAO\n");
    
19.04.2015 / 20:13
0

To know what the triangular numbers are up to a given position I've made a code:

int main(){
    int limitador=0,i;

    printf("Digite ate qual posicao voce quer saber o numero triangular: ");
    scanf("%d",&limitador);
        while(limitador < 0 || limitador > 1290){
        printf("Valor invalido!! Digite um numero entre 0 e 1290: ");
        scanf("%d",&limitador); 
        }
    for(i=0; i<limitador; i++)
        printf("%d x %d x %d =%d\n",i,i+1,i+2,i*(i+1)*(i+2));

    system("pause");    
    return 0;
}   

Note: The code only goes to position 1290 because in the next position the result goes from the amount of an integer value in the C language.

    
24.05.2018 / 16:42