Re: A simple program , need to see where's the mistake :)



On Wed, 2006-10-25 at 12:34 -0700, Odinn wrote:
Greetings , This is my first year at programming and 3rd week at this
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:
*
**
***
****
*****
******
<snip code, which I've already commented on>


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/>

.



Relevant Pages

  • Re: how to print out the return of time()?
    ... > nick wrote: ... > int main ... the first argument to *printf unless you want them to be ... interpreted as format strings -- they might contain characters ...
    (alt.comp.lang.learn.c-cpp)
  • Re: HELP!! Two questions from <>
    ... int flag=1; ... else if (flag == 0) ... printf(" "); ... putchar; ...
    (comp.lang.c)
  • Re: HELP!! Two questions from <>
    ... int flag=1; ... else if (flag == 0) ... printf(" "); ... putchar; ...
    (comp.lang.c)
  • Re: read and write columns
    ... current version of putchar, it has the whole history of it, including ... The current version isn't shy about the non-standard headers: ...
    (comp.lang.c)
  • Re: why doesnt this recurse
    ... You should fix your formatting, ... int main ... You can see that in the second example, putchar() is always executed, as ... you have an if clause and nothing else. ...
    (comp.lang.c)