Prog in C stating whether x is divisible

0

Good afternoon guys, all right?

I'm continuing my C exercises, and I'm stuck in one more. Here is the statement of the same:

Write an algorithm that receives a number from the keyboard and tell whether it is divisible by 8, by 5, by 2, or if it is not divisible by any of these. Check for each of the numbers. Example: Number: 8 Divisible by 8 Divisible by 2

My code:

inicio

      escreva("Digite um número: ")
      leia(num)

      d2 <- (num%2)
      d5 <- (num%5)
      d8 <- (num%8)

      soma <- d2+d5+d8

      se (soma = 0) entao
         escreval("Número não é divisível por nenhuma das opções (2, 4 e 5)")
      senao
           se (d2 = 0) entao
              escreval("Número divisível por 2")
           senao
                se (d5 = 0) entao
                   escreval("Número divisível por 5")
                senao
                     se (d8 = 0) entao
                        escreval("Número divisível por 8")
                     fimse
                fimse
           fimse
      fimse

fimalgoritmo

Can anyone help me with this?

    
asked by anonymous 10.05.2018 / 19:02

1 answer

1

There are two problems with this algorithm. The first problem is relative to the first se :

se (soma = 0) entao

When the sum is zero, it means that it is divisible by all and not that it is not divisible by any.

The second problem is related to the interlacing of the se / senao. For example, when you say that:

se (d2 = 0) entao
    escreval("Número divisível por 2")
senao

That's what you're saying, get in that if something should happen, otherwise do it. However, se/senao should only be used when one condition influences the other, which is not the case in this situation. the fact that it is divisible by 2, does not make it non-divisible by 5 or 8, so those se s should not be nested.

    
10.05.2018 / 19:12