Re: A simple program , need to see where's the mistake :)
- From: Andrew Poelstra <apoelstra@xxxxxxxxxx>
- Date: Wed, 25 Oct 2006 22:33:54 GMT
On Wed, 2006-10-25 at 12:34 -0700, Odinn wrote:
Greetings , This is my first year at programming and 3rd week at this<snip code, which I've already commented on>
so count me as a pure newbie.
I am trying to make a program that gets a number and prints out starts
as this:
For input 3 :
*
**
***
For input 6:
*
**
***
****
*****
******
Here's my version of your program:
#include <stdio.h>
void print_stars(int num) {
int i;
for(i = 0; i < num; i++)
putchar('*');
putchar('\n');
}
int main(void) {
int num, ctr;
scanf(&num);
for(ctr = 0; ctr < num; ctr++)
print_stars(ctr);
return 0;
}
Consider the following:
The function name clearly shows what it does, and the argument is
named clearly. By simply reading the prototype, one can figure out
exactly what the function does and how to use it.
I've used putchar() instead of printf() for a number of reasons. The
first is that putchar() is tailor-made for printing one character, and
therefore can be much more efficient than printf(). Another reason is
that printf() needs to scan each character and check for format strings.
putchar() eliminates this overhead. Thirdly, putchar() shows my intent
more clearly.
I moved the printing of the newline into the print_stars() function,
which is where it logically belongs.
Notice also that I formatted consistently and didn't rely on implicit
return values. On those functions that /did/ return something, I made
sure to include a return statement.
My final comment is that you shouldn't be using scanf() for user input,
as it's very unfriendly and doesn't handle erroneous input properly.
Better to write your own get_int() function using fgets() or fgetc(). I
recommend that as your next project.
--
Andrew Poelstra <http://www.wpsoftware.net/projects/>
.
- Follow-Ups:
- Re: A simple program , need to see where's the mistake :)
- From: Christopher Benson-Manica
- Re: A simple program , need to see where's the mistake :)
- References:
- Prev by Date: Re: fclose then fopen equivalent for stdout?
- Next by Date: Re: Strange Behaviour of this function
- Previous by thread: Re: A simple program , need to see where's the mistake :)
- Next by thread: Re: A simple program , need to see where's the mistake :)
- Index(es):
Relevant Pages
|