Question for in C (I’m still learning)

Asked

Viewed 40 times

-1

#include <stdio.h>

int main (){
    
    int i, n;
    
    printf("Digite um numero: ");
    scanf("%d", &n);
    
    int a;
    a = n;
    
    for ( ; a>=0; a--){
        if(n%a==0){
            i++;
        }
    }
    printf("%d", i);
}

This is my code, it’s not working. His goal is to type a number and he calculates how many divisors that number has. It’s not going, I’m still learning and I have no idea what I did wrong. According to my logic it should be working.

  • 1

    You have to initialize i with zero, otherwise it starts with any value (the so-called "junk" memory). And the condition of the for must be a > 0, because if use >= you will end up making a division by zero and will give error.

  • 1

    Another detail is that you don’t need to loop all the numbers. Every integer is divisible by 1 and by itself, so testing these is redundant. Tip: https://ideone.com/XeqveD - and see the explanation of the algorithm here: https://answall.com/a/486325/112052

1 answer

1

I made a small refactoring in your code. The biggest problem is the fact that it is dividing by zero at the end of the loop for:

#include <stdio.h>


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

    printf("Digite um numero: ");
    scanf("%d", &n);
    
    // No "for", não deixe a >= 0 ou o "if" na repetição ao final
    // da execução ficará como (caso o usuário tenha inserido o numero "2"):
    // if (2 % 0 == 0)
    // Como não é possível dividir por zero, o programa não termina sua execução.
    for (int a = n; a > 0; a--)
    {
        if(n % a == 0)
        {
            i++;
        }
    }
    
    printf("%d\n", i);
}

If you run the program from the above code by inserting 3 as input, we will have the exit:

Digite um numero: 3
2

Browser other questions tagged

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