Display the first 5 divisional numbers by 3, discarding the number 0

Asked

Viewed 277 times

0

I’m not able to display the first 5 divisibles by 3, I put a counter variable, but it returns another number.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n = 20;
    for(int i=1; i<=n; i++) {
        if(i%3 == 0)
        printf("%d\n", i);
    }
    return 0;
}

Could someone explain to me how?

  • Is displaying the numbers 3 6 9 12 15 18, you want to show only the 3 6 9 12 15?

  • Yes, that’s right. the first 5.

  • Opa- take the opportunity to see in the answers the indentation styles of the code. It is much important to correctly indent all lines - helps you and others to read your own code much easier.

2 answers

3


To display the first 5 numbers just count the number divisible by 3, when the quantity is equal to 5 ends the loop, see the example:

#include <stdio.h>

int main(void)
{
    int cont = 0, numero = 0;

    while (1)
    {
        numero++;

        if (numero % 3 == 0)
        {
            printf("%d\n", numero);
            cont++;
        }

        if (cont == 5)
            break;
    }

    return 0;
}

Exit:

3
6
9
12
15

  • 1

    I understood how to do.

1

You need to use a flag to verify that you have printed all the first 5 numbers.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n = 20;
    int flag = 0;
    for(int i=1; i<=n; i++) {
        if(i%3 == 0) {
            flag++;
            printf("%d\n", i);
            if(flag == 5)
                return 0;
        }
    }
    return 0;
}
  • I’ve tried it this way, and it doesn’t work.

  • You tried wrong, I just ran this program and it worked.

  • Yes, it worked now, the order is wrong.

  • Just one comment, Renato, that has nothing to do with your solution - in general we call (and give the name of) "flag"" to variables that contain a meaning of "true" or "false". In this case, the variable keeps a count, so the best would be a name like "counter".

Browser other questions tagged

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