I'm new to programming and tried hard to figure this out by myself, but I'm confused about how to write this.
I need to write a program that displays a block of characters. The number or rows, columns, and which character used is all user-defined. I need to call a function twice to display the number of rows and columns based on what the user entered.
I'm confused about where to place the loop and what goes in it. Here is my attempt. The functions readChar and getNum are needed per the instructions.
The function getNum() should read one number and return that one number.
Call getNum() twice: once to get the number of rows and then a second time to get the number of columns.
The function getNum() should read one number and return that one number.
That's something I fixed in the second code I showed. I ended up changing it to 'i' like you did because I wasn't sure if I could use 'num'. I'm still getting the error saying I need to declare return.
int main()
{
// these variables are uninitialised
int num, rows, cols;
char c;
// ...
// values returned by readChar, getNum are discarded without being used
// ...
printBox(rows, cols, c); // still uninitialised: no values have been assigned to rows, cols and c
}
Why are they being discarded? I thought once a value is returned from a function, it goes back to main and continues . Do I need to move my cout statements from main to the other functions?
> Why are they being discarded?
> I thought once a value is returned from a function, it goes back to main and continues.
It does get back (return to) main, but the value it returns is not being used in main.
1 2 3 4
int rows ; // uninitialised
cout << "Enter the number of rows: ";
getNum(); // the value returned by getNum() is discarded.
// there is no change to the uninitialised state of the variable rows
1 2 3
int rows ; // uninitialised
cout << "Enter the number of rows: ";
rows = getNum() ; // the variable rows now holds the value returned by getNum()
1 2
cout << "Enter the number of rows: ";
constint rows = getNum() ; // the variable rows is initialised with the value returned by getNum()
Do I need to move my cout statements from main to the other functions?
The short answer is no. It' not working for the reason I gave above.
While not mandatory, it's not always the best policy to use functions for cout's etc. Functions are best when they process and return values, strings etc rather than tie your program down to specific console use. That way they can be easily re-used elsewhere on other (eg windows based) platforms.