I tried a practice exercise where I had to write a C program that takes an integer input and prints that many asterisks. Here's my code, but I have this nagging feeling that it could be improved. I think the second variable might not be necessary, but I'm not sure. Here's what I've written:
```c
#include
int main() {
int stars;
int bers = 0;
scanf("%d", &stars);
while (bers < stars) {
printf("*");
bers++;
}
return 0;
}
```
5 Answers
You're right; you can simplify this by removing the second variable. Instead of using `bers`, you could just use the `stars` variable and keep decrementing it each loop. For example:
```c
while (stars > 0) {
printf("*");
stars--;
}
```
That way, you'd make your code a bit cleaner!
Yeah, if you're feeling like it needs to be more efficient, a `for` loop might be more suitable here. Instead of while, try:
```c
for (int i = 0; i < stars; i++)
printf("*");
```
This is clearer and easier to read. Also, having an extra variable isn't a massive issue, but simplifying your loops can make your code look nicer!
This was before I learned what for loops were, lmao!
It's also important to not stress too much about optimization with beginner tasks like this one. Many programs can be improved, but not all need that level of optimization right away. Focus on understanding the fundamentals first, and the efficiency will come with experience!
One big tip: printing in a loop like this can be slow. Instead, create a char array that matches the length of your output, fill it with asterisks, and print it all at once. This approach will speed things up significantly for larger inputs—try it with 100k asterisks to see the difference!
While it's great to focus on efficiency, remember that readability matters, too! Programming often involves writing code that others (or you in the future) can easily understand. So, while you can optimize later, the balance between performance and clarity is crucial. Keep coding and you'll find that balance!
I KNEW IT! For some reason, I just didn't think to decrement. Thanks!