C language code print pairs from one to fifty

Asked

Viewed 61 times

-2

Programming exercise in C: Statement: "Write a program that prints all pairs between 2 and 50. To know if the number is even, just see if the rest of the division by 2 is equal to 0."

what I did:

#include <stdio.h>
int main() {
for(int n = 2; n <= 50; n++){
    int rest = n % 2;
    if(rest == 0){
        printf("%d", n);
       }
}
}

What you have printed: 2468101214161820222426283032343638404244464850

  • Detail that you can do the for skipping 2 by 2: for(int n = 2; n <= 50; n += 2) - then you don’t even have to test the rest of the division, because all the numbers will surely be even (unless, of course, the exercise requires you to do one on one and use the operator %)

  • Thank you very much! Your reply and helped in another exercise!!!

1 answer

1

Your logic is correct, and the result too, it turns out that you did not give spaces or did a line break between the results, so all even numbers were printed next to each other.


You can edit your printf to give space:

printf("%d ", n);

Or a line break:

printf("%d\n", n);

Even a horizontal tab:

printf("%d\t", n);

Your final code will look like this:

#include <stdio.h>

int main() {
    for(int n = 2; n <= 50; n++){
        int rest = n % 2;

        if(rest == 0) {
            printf("%d\n", n);
        }
    }
}

See online: https://repl.it/@Dadinel/ColorfulMinorSequel

  • 1

    Man, thank you so much, bro!!!!

  • Imagine if I’d done it all! D

Browser other questions tagged

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