FUNCTIONS in C++

The function is a self-contained block of statements that performs a given task. The programs we were writing until now had only one function i.e. the main function. A function is invoked by a function call. The function call specifies the function name and provides information that the called function needs to do its job. A common analogy for this is the hierarchical form of management. A Boss(Calling function or caller) asks a worker (the called function) to perform a task and return the result when the task is done. The boss function does not know how the worker function performs its designated tasks. The worker might call another worker functions; the boss will be unaware of this.

The syntax of a function is given below:

return_type function_name(argument_list)
{
-
-
statements;
-
-
}

Example for function in C++

#include<iostream>
using std::cout;
using std::endl;
int square(int);
int main()
{
for(int x=1;x<=10;x++)
cout<<square(x)<<" ";
cout<<endl;
return 0;
}
int square(int y)
{
return y*y;
}

OUTPUT:

1 4 9 16 25 36 49 64 81 100

Function prototype

One of the most important features of C++ is the function prototype. A function prototype tells the compiler the name of a function, the type of data returned by that function, the number of parameters that function expects to receive, the types of those parameters and the order in which the parameters of those types are expected. The compiler uses function prototypes to validate function calls. Early versions of the C programming language did not perform this kind of checking, so it was possible to call C functions with incorrect arguments and compilers would not detect the errors. Such calls could result in fatal execution time errors or nonfatal errors that caused subtle logic errors that were difficult to detect. Function prototypes correct this deficiency. The header files we include in the C++ program contain function prototypes, which enable the compiler to ensure that a program uses functions correctly.

Function prototypes are required in C++.Use #include preprocessor directives to obtain function prototypes for the standard library functions from the header files for the appropriate libraries.Also use #include to obtain header files containing function prototypes used by you or your group members

Important Point on function in C/C++

  • Forgetting the semicolon at the end of a function prototype is a syntax error
  • A function call that does not match the function prototype is a syntax error
  • Forgetting a function prototype when a function is not defined before it is first invoked is a syntax error
  • Although parameter names in function prototypes are optional many programmers use these

Game using Function in C++

Random Number Generation

1.Rolling a six-sided die 6000 times using the function

#include<iostream>
using std::cout;
using std::endl;
#include<iomanip>
using std::setw;
#include<cstdlib>
int main()
{
int frequency1=0,frequency2=0,frequency3=0,frequency4=0,frequency5=0,frequency6=0;
int face;
//loop 6000 times and summarize results
for(int roll=1;roll<=6000;roll++)
{
face=1+rand()%6;
switch(face)
{
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
default:
cout<< "Invalid choice";
}
}
cout<<"Face"<<setw(13)<<"Frequency"
    <<"\n    1"<<setw(13)<< frequency1
    <<"\n    2"<<setw(13)<< frequency2
    <<"\n    3"<<setw(13)<< frequency3
    <<"\n    4"<<setw(13)<< frequency4
    <<"\n    5"<<setw(13)<< frequency5
    <<"\n    6"<<setw(13)<< frequency6<<endl;
return 0;         

}

OUTPUT:

Face   Frequency
1        1003
2        1017 
3        983
4        994
5        1004
6         999

As the program output shows, we can simulate the rolling of a six-sided die by scaling and shifting the values produced by rand. Note that the program should never get to the default case provided in the switch structure because of the switch’s controlling expression(face) always has value in the range 1-6; however, we provide the default case as a matter of good practice. The function rand actually generates pseudo-random numbers. Calling rand repeatedly produces a sequence of numbers that appears to be random. However, the sequence repeats itself each time the program executes. Once a program has been thoroughly debugged, it can be conditioned to produce a different sequence of random numbers for each execution. This is called randomizing and is accomplished with the standard library function srand. Function srand takes an unsigned integer argument and seeds the rand function to produce a different sequence of random number for each execution of the program

2. One of the most popular games of chance is a dice game known as “craps,” which is played in casinos and back alleys worldwide.

Rules:

A player rolls two dice. Each die has six faces. These faces contain 1,2,3,4,5 and 6 spots. After the dice have come to rest, the sum of the spots on the two upwards faces is calculated. If the sum is 7 or 11 on the first roll, the player wins. If the sum is 2,3 or 12 on the first roll(called “craps”), the player loses. If the sum is 4,5,6,8,9 or 10 on the first roll, then that sum becomes the player’s “point”.To win, you must continue rolling the dice until you “make your point.” The player loses by rolling a 7 before making the point

#include<iostream>
using std::cout;
using std::endl;
#include<cstdlib>
#include<ctime>
int rollDice(void);
int main()
{
enum Status{CONTINUE,WON,LOST};
int sum;
int myPoint;
Status gameStatus;
srand(time(0));
sum=rollDice();
switch(sum)
{
case 7:
case 11:
gameStatus=WON;
break;
case 2:
case 3:
case 12:
gameStatus=LOST;
break;
default:
gameStatus=CONTINUE;
myPoint=sum;
cout<<"Point is"<<myPoint<<endl;
break;
}
while(gameStatus==CONTINUE)
{
sum==rollDice();
if(sum==myPoint)
gameStatus=WON;
else
if(sum==7)
gameStatus=LOST;
}
if(gameStatus==WON)
cout<<"Player wins"<<endl;
else
cout<<"Player loses"<<endl;
return 0;
}
int rollDice(void)
{
int die1;
int die2;
int workSum;
die1=1+rand()%6;
die2=1+rand()%6; 
workSum=die1+die2;
//display the result
cout<<"Player rolled"<<die1<<"+"<<die2
    <<"="<<workSum<<endl;
return workSum;
}

OUTPUT:

Player rolled 2+5=7
Player wins

The game is reasonably involved. The player may win or lose on the first roll or may win or lose on any subsequent roll. The program uses variable game status to keep track of this. Variable game status is declared to be of a new type Status. In the program, a user-defined type called an enumeration is introduced by the keyword enum and followed by type name is a set of integer constants represented by identifiers. The values of these enumerations constant start at, 0 unless specified otherwise, and increment by 1. In the preceding enumeration, the constant CONTINUE has value 0, WON has the value 1 and LOST has the value 2. The identifiers in an enum must be unique, but separate enumeration constant can have the same integer value.

Learn Function Related Topics

Learn function call and return in Details:

Click ME

Learn Functions With Empty Parameter Lists in C++:

Click ME

Learn Inline Function In C++:

Click ME

Learn Default Argument In C++:

Click ME

Learn Unary Scope Resolution In C++:

Click ME

Translate »