C++ Programming : Function

This tutorial will show you how to use function in C++. We will make a simple function to write text in our console. This is the function standard format :

output function_name(input1, input2, …)

{

// write your code here

return output

}

Now we will create function to write a string in a specific coordinate in our console.

Add this to your .cpp header

#include <Windows.h>

Now write this in your .cpp

// A function to go to point (x, y) on console
void goTo(int xLine, int yLine)
{
COORD coord = {xLine, yLine};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// A function to write a text on specific point on console
void writeText(int xLine, int yLine, string text)
{
goTo(xLine, yLine);
cout << text << flush;
}
// main function
int main(int argc, char** argv)
{
int key;
string text = “Hello World!”;
writeText(20, 10, text); // write text in point (20, 10)
writeText(40, 30, “Hello World!!”); // write text in point (40, 30)
cin >> key;
return 0;
}

This is the result

fuction