Reputation: 1
I have a question:
With this while
loop I only get this output: XXX
#include <unistd.h>
void print(int x, int y) {
while (y > 2) {
while ((x - 1) > 1) {
write(1, "X", 1);
x--;
}
y--;
}
}
int main(void) {
print(5, 5);
return (0);
}
But shouldn't it be this:
XXX
XXX
XXX
Upvotes: 0
Views: 46
Reputation: 181
You're not resetting x after it reaches 2. The problem is that when the inner while loop finishes, x is equal to 2 (so x-1 is 1 and the inner loop ends), and by not setting it to the previous value, the other outer loop is basically useless.
The correct code to get the output "XXX XXX XXX" is something like the one below:
#include <unistd.h>
void print(int x, int y) {
int c = x;
while(y > 2) {
while((x - 1) > 1) {
write(1, "X", 1);
x--;
}
write(1, " ", 1);
x = c;
y--;
}
}
int main(void) {
print(5,5);
return(0);
}
Upvotes: 1