[Courses] C Programming For Absolute Beginners, Lesson 5A: All About Functions, Part 2
Leslie
leslie.brothers at verizon.net
Thu Apr 5 04:06:37 UTC 2012
On Sun, 2012-04-01 at 22:06 -0700, Carla Schroder wrote:
> HOMEWORK
>
> Take any of these examples and modify them to accept user input, just like we
> did in our previous lessons. Put as much functionality as possible into
> separate functions and then call them from main.
>
(1) This is a little simple, but here goes:
//partyplan.c
#include <stdio.h>
int numplates (int);
int galpunch (int);
int bagchips (int);
int funnyhats (int);
int main (void)
{
int guests=0;
printf( "How many people are you inviting to the party?\n");
scanf( "%d", &guests);
int a = numplates(guests);
int b = galpunch(guests);
int c = bagchips(guests);
int d = funnyhats(guests);
printf( "You'll need %d plates, so you'll have a few extra.\n", a);
printf( "You'll need %d gallons of punch.\n", b);
printf( "You'll need %d bags of chips.\n", c);
printf( "You'll need %d funny hats so everyone can have one.\n", d);
return 0;
}
int numplates (int a)
{
return(a+2);
}
int galpunch(int b)
{
return(b/3);
}
int bagchips(int c)
{
return(c/2);
}
int funnyhats(int d)
{
return(d);
}
(2) I tried to figure out a way to use 'puts' followed by one long
string, instead of those multiple printfs in main(), but I could not
find a way to make 'puts' work. Should I have been able to?
> What is the difference between:
>
> void functionname (void)
>
> and
>
> int functionname (void)
>
> Why is it OK to use 'void functionname (void)' for ordinary functions, but not
> OK to use 'void main (void)' ?
>
(3) Regarding the above, I looked at Sachin Divekar's answers and I
can't improve on them.
(4) I have a separate question relating to Jacinta's point: "If we open
a file, and then pass the file handle to a subroutine without checking
that the file opened successfully, then...the error will come from
within our subroutine.."
FILE *fh;
fh = fopen("somefile.txt", "r");// fopen returns a false value on
failure, we really should check it
My question is, can you give a short example of how to check for failure
to open?
Thank you!
-Leslie
>
More information about the Courses
mailing list