void function

Hello guys. can you explain to me?
why void function cannot be placed after main function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 #include <iostream>

using namespace std;

const int WIDTH = 20;

int main() {
	int j, numRows;
	cout << "Enter number of rows: ";
	cin >> numRows;
	if (numRows > 0) {
		for (j = 0; j < numRows; j++) {
			drawLine('.', '-');
			drawLine('@', ' ');
		}
		drawLine('.', '-');	
	}
	
	system("PAUSE");
	return 0;
}

void drawLine(char ch1, char ch2) {
	int i;
	cout << ch1;
	for (i=0; i < WIDTH; i++)
		cout << ch2;
	cout << ch1 << endl;
}
it can but you need to use a function prototype.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

using namespace std;
void drawLine(char ch1, char ch2);

const int WIDTH = 20;

int main() {
	int j, numRows;
	cout << "Enter number of rows: ";
	cin >> numRows;
	if (numRows > 0) {
		for (j = 0; j < numRows; j++) {
			drawLine('.', '-');
			drawLine('@', ' ');
		}
		drawLine('.', '-');
	}

	system("PAUSE");
	return 0;
}

void drawLine(char ch1, char ch2) 
{
	int i;
	cout << ch1;
	for (i = 0; i < WIDTH; i++)
		cout << ch2;
	cout << ch1 << endl;
}
oh ya i forget to put the function prototype.
Thanks Yanson.

Yanson , Should the function protoype must put in the sequence?
Yes, it must be "visible" at that point. Many reasons behind this, you will learn them while going deeper.
why the function prototype look like different as usuall.
Can I know what is difference and how to use it.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "prog06.4b.h"

using namespace std;

int main() {
int generatedNum, guess;
generatedNum = generateNumber();
do {
guess = getGuess();
} while (!isCorrect(guess, generatedNum));

system("PAUSE");
return 0;
}

int generateNumber() {
srand((unsigned)time(0)); // seed the random generator
return (rand() % 100)+1; // generate a random number and return it
}

int getGuess() {
int number;
cout << "Enter a number between 1 and 100: ";
cin >> number;
return number;
}

bool isCorrect(int number_guess, int number_target) {
if (number_guess == number_target) {
cout << "Well done!" << endl;
return true;
}
else if (number_guess < number_target)
cout << "Higher!" << endl;
else
cout << "Lower!" << endl;
return false;
}
why the function prototype look like different as usuall.
Can I know what is difference and how to use it.


The function prototype must match the function implementation exactly. Otherwise when the compiler encounters a call to your function, it will not know how to call your function because it has not seen yet.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
http://v2.cplusplus.com/articles/jEywvCM9/
It makes it easier to read your code and it also makes it easier to respond to your post.
Hint: You can edit your previous post, highlight your code and press the <> formatting button.
Topic archived. No new replies allowed.