Triangular number

Asked

Viewed 4,930 times

0

I wonder, why when I type in the program below that checks if the typed number is triangular, ie, is multiple of three consecutive numbers, as example 60 it prints two "NO" and a "YES", and when type 336 appear five "NO" and a "YES"?

#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;
}

2 answers

3


When i for 1 the program will do if

if (1 * 2 * 3 == numero)

Either print "YES N" or print "NO".
When the i for 2 if becomes

if (2 * 3 * 4 == numero)

and the program prints "YES N" or "NO".

That is, the program prints anything whenever it runs the loop. What you want is to 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");
  • 1

    (+1) or even for(i = 1 ; i*(i+1)*(i+2)<numero ; i++){}&#xA;if(i*(i+1)*(i+2)==numero) { printf("SIM\n"); }else { printf("NAO"); }

  • (if is out of cycle)

  • the braces empty fooled me :)

  • And the disarray of the comments also does not help anything :)

  • 1

    because of this I usually /* void */ in the empty places: for (a, b, c) { /* void */ }

0

To know which are the triangular numbers up to a certain position I 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 at the next position the result passes the amount of an integer value in the language C.

Browser other questions tagged

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