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

0

I can not 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 me how?

    
asked by anonymous 02.03.2016 / 02:03

2 answers

3

To display the first 5 numbers just count the number of numbers divisible by 3, when the number equals 5 closes 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;
}

Output:

  

3
  6
  9   12   15

    
02.03.2016 / 02:22
1

You need to use a flag to check if you have already printed all 5 first 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;
}
    
02.03.2016 / 02:22