I need to have a for loop counter that should replace the number with a text when it's divisible by a set of numbers. I already have the loop and the code working, but the '\r' in my printf function does not work someone else's compiler.
Here is my code and outputs from different compilers so you can identify the issue better.
#include <stdio.h>
void hey(void)
{
for (int i = 50; i <= 100; i++)
{
printf("%d", i);
if (i % 5 == 0)
{
printf("\rHEY1 ");
}
if (i % 40 == 0)
{
printf("\rHEY2 ");
}
if (i % 40 == 0 && i % 5 == 0)
{
printf("\rHEY3 ");
}
printf("\n");
}
}
int main(void)
{
hey();
return 0;
}
This's the result on my compiler, which is how I exactly want:
and this one is how it appears on the online compiler that my teacher uses to mark:
For some reason, it doesn't remove the number to replace with 'Hey' in the other compiler. Instead, prints it on a new line.
How do I fix this? It should remove the number and print the letters instead of it as it's on the first screenshot. TIA.
I suspect that your teacher does not expect you to use '\r' and instead expects you to figure out how NOT to output the number in the first place and instead right away print the "HEY". That would be reliable in all environments.
Her is how you can do that. Note that I used else if
and that I reordered the checks, in order to get what I am sure is what you want for case 80.
I also simplified the 80 condition, because the reordering allows that.
I chose the "HEY3" option for 80. You will never find "HEY2" AND "HEY3" in an output of this code, because anythign divisible by 40 is always also divisible by 5.
#include <stdio.h>
void hey(void)
{
for (int i = 50; i <= 100; i++)
{
if (i % 40 == 0 /* && i % 5 == 0 */)
{
printf("HEY3 ");
} else if (i % 5 == 0)
{
printf("HEY1 ");
} /* else if (i % 40 == 0)
{
printf("HEY2 ");
} */ else
{
printf("%d", i);
}
printf("\n");
}
}
int main(void)
{
hey();
return 0;
}
Output:
HEY1
51
52
53
54
HEY1
56
57
58
59
HEY1
61
62
63
64
HEY1
66
67
68
69
HEY1
71
72
73
74
HEY1
76
77
78
79
HEY3
81
82
83
84
HEY1
86
87
88
89
HEY1
91
92
93
94
HEY1
96
97
98
99
HEY1