-
problem with functions
Hello,
I am trying to make a program that prints out a square with width defined by the user. The program compiles, and asks user for width, but after that nothing happens. What am I doing wrong?
Code:
#include<stdio.h>
/*Prompts user to enter width*/
int getwidth(int width);
/*Prints out a square*/
char printsquare (void);
int
main(void)
{
int width;
char printsquare;
width = getwidth(width);
printsquare;
return(0);
}
/*Function that prompts user to enter width */
int getwidth (int width)
{
printf("Enter width for the house, it must be odd number bigger than 5> ");
scanf("%d", &width);
return width;
}
/*Function that prints out a square */
char printsquare(void)
{
/* prints out top of the square */
int width;
int count = 0;
while(count < width)
{
printf("%c", '*');
count=count+1;
}
printf("\n");
/* prints out left and right walls of the square*/
int count1 = 0;
while(count1 < width-2)
{
printf("%c", '*');
int count2 = 0;
while(count2 < width-2) {
printf("%c", ' ');
count2=count2+1;
}
printf("%c", '*');
printf("\n");
count1=count1+1;
}
/*prints out bottom of the square*/
int count3 = 0;
while(count3 < width)
{
printf("%c", '*');
count3=count3+1;
}
printf("\n");
}
I can't get what's wrong with this code. Do you see what's wrong with it?
-
You need parenthesis on your function call. Also you might as well get rid of that ambiguous character variable in main.
-
what do you mean by "ambiguous character in main"?
-
I mean you have a character variable in main that's of no use at all.
-
hmm, i wish i knew which one you are talking about.
-
...
...
... the only character variable in main.
-
-
I'm beginning to think you didn't write the code you posted in your original post. Besides... forgot about the character variable. It makes no difference to your program running. As I said, you need parenthesis after your printsquare function call.
You did it right with your other function, I don't know why you wouldn't do it there.
-
Also you want to pass "width" to printsquare()
edit:
You pass it to getwidth() but that isn't useful at all. If you declare "width" in getwidth() and return it, that's good enough; then you can just use this
Code:
printsquare (getwidth());
to call your function.
Explanation: C uses pass by value, and when you pass "width" to getwidth() you're passing the value of an uninitialized variable, which serves no purpose. You do get a useful value from getwidth(), but it's also just a copy.
You can name all the function scope variables you want "width" but they are not the same variable.
Also printsquare() should be declared to return void.