How Do I Improve My Solution for K&R Exercise 1-9?

0
24
Asked By CuriousCoder42 On

I'm working on Exercise 1-9 from K&R, which asks us to write a program that copies input to output but replaces sequences of blank spaces with a single space. I got a bit stuck and checked the next chapter, where I found the && operator and the concept of a 'state' variable, which helped me devise a solution. However, I'm unsure how I could approach the problem without relying on these tools. Any suggestions? Here's my code:

```c
#include
int main(){
int c, b;
b = 0;
while((c=getchar()) != EOF){
if(c != ' '){
printf("%c", c);
b = 1;
}
if(c == ' ' && b == 1){
printf("%c", ' ');
b = 0;
}
}
}
```

2 Answers

Answered By CodeWiz123 On

Your use of the && operator is fine, and it's not strictly necessary since you can restructure the logic a bit. Instead of using a boolean variable to track the state, consider using nested if-statements for clarity. This way, the program 'remembers' if the last character was a space without needing an explicit state variable. Also, combine control flow to skip multiple spaces with a while loop. It may not be as elegant, but it works. Just a tip: using `putchar(c)` might be more efficient than `printf("%c", c)` as it avoids additional overhead.

Answered By DevGuru99 On

While it's true you can avoid using a state variable, having one simplifies understanding what your code is doing at a glance. Try renaming your `b` variable to something more descriptive, like `previousCharacterNotSpace`. This way, you can make your intentions clearer without complicating the logic. A positive flag, like `previousCharacterSpace`, might also help here, making it obvious when you want to skip additional spaces.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.