| My Training Period: xx hours
This is a final part and a continuation from the previous Module. The source code for this Module is:C/C++ functions source codes. and the lab worksheets for your practice:Function lab worksheet 1,lab worksheet 2,lab worksheet 3 andlab worksheet 4.
The C and C++ skills that supposed to be acquired:
Example #13 – Using Functions In User Defined Header file
// a user defined function and header file, a simple arithmetic functions #include <iostream> using namespace std; // a function prototype float AddNum(float, float); // a main program void main(void) { cout<<"The function body..."<<endl; cout<<"This just program skeleton..."<<endl; } // a function definition float AddNum(float , float) { float x = 0; return x; }
|
Next, add other functionalities.
// a user defined function and header file
#include <iostream>
using namespace std;
// a function prototype
float AddNum(float, float);
void main(void)
{
// a global (to this file) scope variables
float p, q, r;
// prompt for user input
cout<<"Enter two numbers separated by space: "<<endl;
cin>>p>>q;
// a function call
r = AddNum(p, q);
// display the result
cout<<"Addition: "<<p <<" + "<<q<<" = "<<r<<endl;
}
// a function definition
float AddNum(float p, float q)
{
return (p + q);
}
Then, compile and run this program.
Next, if there is no error, we add other functionalities to complete our program.
// a user defined function and header file, a simple arithmetic functions
#include <iostream>
using namespace std;
// function prototypes
float AddNum(float, float);
float SubtractNum(float, float);
float DivideNum(float, float);
float MultiplyNum(float, float);
void main(void)
{
// local (to this file) scope variables
float p, q, r, s, t, u;
// prompt for user input
cout<<"Enter two numbers separated by space: "<<endl;
cin>>p>>q;
// function call
r = AddNum(p, q);
s = SubtractNum(p, q);
t = DivideNum(p, q);
u = MultiplyNum(p, q);
// display the result and quit
cout<<"Addition: "<<p <<" + "<<q<<" = "<<r<<endl;
cout<<"Subtraction: "<<p <<" - "<<q<<" = "<<s<<endl;
cout<<"Division: "<<p <<" / "<<q<<" = "<<t<<endl;
cout<<"Multiplication: "<<p <<" * "<<q<<" = "<<u<<endl;
cout<<"Press Enter key to quit."<<endl;
}
// function definition
float AddNum(float p, float q)
{
return (p + q);
}
float SubtractNum(float p, float q)
{
return (p - q);
}
float DivideNum(float p, float q)
{
// do some checking here to avoid divide by 0
if (q == 0)
return 0;
else
return (p / q);
}
float MultiplyNum(float p, float q)
{
return (p * q);
}
Re-compile and re-run.
Our next task is to create header file, let named it arithmet.h and put all the function declaration and definition in this file and save it in same folder as the main program.
No need to compile or run this file, just make sure no error here.
// a user defined function and header file, a simple arithmetic functions
// this is an arithmet.h header file, no need to compile or run.
// The variable also has been change to x and y respectively.
// The important one are parameter type, number and return type must be matched
#include <iostream>
using namespace std;
// global variables
float x, y;
// function prototypes
float AddNum(float, float);
float SubtractNum(float, float);
float DivideNum(float, float);
float MultiplyNum(float, float);
float AddNum(float x, float y)
{
return (x + y);
}
float SubtractNum(float x, float y)
{
return (x - y);
}
float DivideNum(float x, float y)
{
// divide by 0 check
if(y==0)
return 0;
else
return (x / y);
}
float MultiplyNum(float x, float y)
{
return (x * y);
}
Now, our new main() program becomes:
// a user defined function and header file, a simple arithmetic functions
// a new main program
#include <iostream>
using namespace std;
#include "arithmet.h" // notice this!
// global variables because need the external access
float p, q;
void main(void)
{
// local scope (to this file) variables…
int r, s, t, u;
cout<<"Enter two numbers separated by space: "<<endl;
cin>>p>>q;
r = AddNum(p, q);
s = SubtractNum(p, q);
t = DivideNum(p, q);
u = MultiplyNum(p, q);
cout<<"Addition: "<<p <<" + "<<q<<" = "<<r<<endl;
cout<<"Subtraction: "<<p <<" - "<<q<<" = "<<s<<endl;
cout<<"Division: "<<p <<" / "<<q<<" = "<<t<<endl;
cout<<"Multiplication: "<<p <<" * "<<q<<" = "<<u<<endl;
}
Compile and run this main program, you will get the same output but this main() program is simpler and our header file arithmet.h can be reusable.
The following program example is a partial function call.
// a user defined function and header file, a simple arithmetic functions
// the new main program with partial function call
#include <iostream>
using namespace std;
#include "arithmet.h"
// global variables need access from external
float p, q;
void main(void)
{
// local scope (to this file) variables…
int t, u;
cout<<"Enter two numbers separated by space: "<<endl;
cin>>p>>q;
// r = AddNum(p, q);
// s = SubtractNum(p, q);
t = DivideNum(p, q);
u = MultiplyNum(p, q);
// cout<<"Addition: "<<p <<" + "<<q<<" = "<<r<<endl;
// cout<<"Subtraction: "<<p <<" - "<<q<<" = "<<s<<endl;
cout<<"Division: "<<p <<" / "<<q<<" = "<<t<<endl;
cout<<"Multiplication: "<<p <<" * "<<q<<" = "<<u<<endl;
}
By storing the preprocessor directive #include "arithmet.h" under the C:\BC5\INCLUDE (Borland® C++ - the default INCLUDE folder or subfolder – you have to check your compiler documentation), you can enclose the header file in the normal angle brackets < >.
// a user defined function and header file, a simple arithmetic functions
// the new main program
#include <iostream>
using namespace std;
#include <arithmet.h>
// using <arithmet.h> instead of "arithmet.h"
// global variables, because need access from external
float p, q;
void main(void)
{
// local scope (to this file) variable
int t, u;
cout<<"Enter two numbers separated by space: "<<endl;
cin>>p>>q;
// r = AddNum(p, q);
// s = SubtractNum(p, q);
t = DivideNum(p, q);
u = MultiplyNum(p, q);
// cout<<"Addition: "<<p <<" + "<<q<<" = "<<r<<endl;
// cout<<"Subtraction: "<<p <<" - "<<q<<" = "<<s<<endl;
cout<<"Division: "<<p <<" / "<<q<<" = "<<t<<endl;
cout<<"Multiplication: "<<p <<" * "<<q<<" = "<<u<<endl;
}
-----------------------------------------------------------
If we want to add functionalities, add them in header file once and then, it is reusable.
How to debug the functions if you have to create many independent functions stored in many header files other than directly include the functions in our main program?
Firstly create the function with their own specific task independently as main() program, compile and run the main() function independently.
Then, when you have satisfied with the result of the independent main() program, convert each main() program to respective function and call all the functions from one main() program.
The main problems encountered here normally related to the passing the improper arguments, returning the improper value, mismatch types and variables scope.
Remember that the main() program just a normal function but with execution point.
We cannot define function within function, but we can call the same function within that function. A recursive function is a function that calls itself either directly or indirectly through another function.
Classic example for recursive function is factorial, used in mathematics.
For example:
// demonstrates recursive function, a recursive factorial function
// the formula, n! = n*(n-1)!
#include <iostream>
using namespace std;
// function prototype, receive long type, return also long type
long factor(long);
int main()
{
int p;
cout<<"Calculating factorial using recursive function"<<endl;
cout<<"----------------------------------------------\n"<<endl;
// let do some looping for 10 numbers
for(p = 1; p<10; p++)
cout<<p<<"! = "<<p<<"*("<<(p-1)<<")!"<<" = "<<factor(p)<<"\n";
return 0;
}
// recursive function definition
long factor(long number)
{
// for starting number, that <= 1, factorial = 1
if(number<=1)
return 1;
// number > 1
else
// return and call itself
return (number * factor(number-1));
}
Another example using recursive function, Fibonacci.
// demonstrates recursive Fibonacci function
// the formula, fibonacci(n) = fibonacci(n-1)+fibonacci(n-2)
#include <iostream>
using namespace std;
long fibonacci(long);
int main()
{
int p;
cout<<"Simple fibonacci using recursive function"<<endl;
cout<<"-----------------------------------------\n"<<endl;
// looping for 15 numbers
for(p = 0; p<30; p=p+2)
cout<<"Fibonacci("<<p<<") = "<<fibonacci(p)<<"\n";
return 0;
}
// recursive fibonacci function definition
long fibonacci(long number)
{
// for starting number, 0, 1, fibonacci = number
if(number == 0 || number == 1)
return number;
// other number...
else
// return and call itself
return (fibonacci(number-1) + fibonacci(number-2));
}
// rand() and random() from stdlib.h
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c;
// generating random number
printf("10 random numbers:\n");
for(c = 0; c <10; c++)
printf("%d ", rand());
printf("\n");
// num has a value between 0 and 99
int num = random(100);
printf("\nRandom number less than 100 = %d\n", num);
// using lower bound and upper bound
int num1 = 200 + random(700-200);
printf("\nRandom number between 200 700 = %d\n", num1);
// floating-point random numbers...
float num3 = rand()/33000.0;
printf("\nfloating-point random number = %f\n", num3);
// floating-point random numbers...
printf("\nAnother floating-point random numbers:\n");
for(c = 0; c <10; c++)
printf("%f\n", rand()/33000.0);
printf("\n");
return 0;
}
// a simple time and date manipulation
#include <stdio.h>
// for time and date related functions
#include <time.h>
// for sleep() function
#include <dos.h>
#include <stdlib.h>
int main(void)
{
struct tm *time_now;
time_t secs_now;
time_t t;
char str[80];
time(&t);
// display current time and date...using ctime()
printf("Today's date and time: %s", ctime(&t));
// formatting the time for output...using strftime()
tzset();
time(&secs_now);
time_now = localtime(&secs_now);
strftime(str, 80,"It is %M minutes after %I o'clock, %A, %B %d 20%y", time_now);
printf("%s\n",str);
// computes the difference between two times...using difftime()
time_t first, second;
// gets system time
first = time(NULL);
// waits 5 secs
sleep(5);
// gets system time again
second = time(NULL);
printf("The difference is: %f seconds\n", difftime(second, first));
// wait for 10 seconds...
sleep(10);
return 0;
}
// converting the date and time to Greenwich Mean Time (GMT)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <dos.h>
// Pacific Standard Time & Daylight Savings
char *tzstr = "TZ=PST8PDT";
int main(void)
{
time_t t;
struct tm *gmt, *area;
putenv(tzstr);
tzset();
t = time(NULL);
area = localtime(&t);
printf("The local time is: %s", asctime(area));
gmt = gmtime(&t);
printf("The GMT is: %s", asctime(gmt));
// wait 10 seconds...
sleep(10);
return 0;
}
// converting time to calendar format...checking the day...
#include <stdio.h>
#include <time.h>
// for sleep() function
#include <dos.h>
// using array to store days' strings
char *wday[ ] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Unknown"};
int main()
{
struct tm time_check;
int year, month, day;
printf("WHAT DAY?...Enter any year, month and day\n");
printf("Year format-YYYY, Month format-MM, Day format-DD\n");
// input a year, month and day to find the weekday for...
printf("Year: ");
scanf("%d", &year);
printf("Month: ");
scanf("%d", &month);
printf("Date: ");
scanf("%d", &day);
// load the time_check structure with the data
time_check.tm_year = year - 1900;
time_check.tm_mon = month - 1;
time_check.tm_mday = day;
time_check.tm_hour = 0;
time_check.tm_min = 0;
time_check.tm_sec = 1;
time_check.tm_isdst = -1;
// call mktime() to fill in the weekday field of the structure...
if(mktime(&time_check) == -1)
time_check.tm_wday = 7;
// print out the day of the week...
printf("That day is a %s\n", wday[time_check.tm_wday]);
sleep(10);
return 0;
}
Program example compiled usingVC++ andVC++ .Net compiler (using C++ wrappers so that we can use C header files/libraries)
#include <cstdio>
#include <ctime>
int main(void)
{
struct tm *time_now;
time_t secs_now;
time_t t;
char str[80];
time(&t);
// display current time and date...using ctime()
printf("Today's date and time: %s\n", ctime(&t));
// formatting the time for output...using strftime()
tzset();
time(&secs_now);
time_now = localtime(&secs_now);
strftime(str, 80,"It is %M minutes after %I o'clock, %A, %B %d 20%y\n", time_now);
printf("%s\n", str);
// computes the difference between two times...using difftime()
time_t first, second;
// gets system time
first = time(NULL);
// waits 5 secs
getchar();
// gets system time again
second = time(NULL);
printf("The difference is: %f seconds\n", difftime(second, first));
// wait for 10 seconds...
getchar();
return 0;
}
/*** function skeleton example, function.c ***/
#include <stdio.h>
/* function prototypes and their variations... */
/* In C++ it is required by standard */
/* notice and remember these variations... */
void FunctOne(void);
double FunctTwo();
int FunctThree(int);
void FunctFour(int);
/* main program... */
int main()
{
printf("-----PLAYING WITH A FUNCTION-----\n");
printf("All call by value ONLY!!!\n");
printf("Starting: I'm in main()...\n");
/* function call, go to FunctOne without any argument...*/
FunctOne();
printf("\nBack in main()...\n");
/* function call, go to FunctTwo() without any argument...*/
double q = FunctTwo();
printf("Back in main()...\n");
/* display the returned value... */
printf("The returned value = %.4f\n", q);
/* function call, go to FunctThree with an argument...*/
int y = 100;
int x = FunctThree(y);
printf("Back in main()...\n");
/* display the returned value... */
printf("Display the returned value from FunctThree = %d\n", x);
int r = 50;
FunctFour(r);
printf("Finally back in main()...\n");
return 0;
}
void FunctOne()
{
/* do nothing here just display the following text...*/
printf("\nNow I'm in FunctOne()!...\n");
printf("Receives nothing, return nothing...\n");
/* return to main, without any returned value */
}
double FunctTwo()
{
/* receive nothing but do some work here... */
double p = 10.123;
printf("\nNow I'm in FunctTwo()!\nmay do some work here..."
"\nReceives nothing but returns something"
"\nto the calling function...\n");
/* and return something... */
return p;
}
int FunctThree(int z)
{
/* receive something...do some work... and return the something...*/
int a = z + 100;
printf("\nThen, in FunctThree()!...\n");
printf("Receives something from calling function\ndo some work here and"
"\nreturn something to the calling function...\n");
/* then return to main, with return value */
return a;
}
void FunctFour(int s)
{
/* received something but return nothing... */
int r = s - 20;
printf("\nNow, in FunctFour()...\n");
printf("Received something, but return nothing...\n");
printf("The value processed here = %d\n", r);
printf("Then within FunctFour, call FunctOne()...\n");
FunctOne();
printf("Back in FunctFour()....\n");
}
[bodo@bakawali ~]$ gcc function.c -o function
[bodo@bakawali ~]$ ./function
-----PLAYING WITH A FUNCTION-----
All call by value ONLY!!!
Starting: I'm in main()...
Now I'm in FunctOne()!...
Receives nothing, return nothing...
Back in main()...
Now I'm in FunctTwo()!
may do some work here...
Receives nothing but returns something
to the calling function...
Back in main()...
The returned value = 10.1230
Then, in FunctThree()!...
Receives something from calling function
do some work here and
return something to the calling function...
Back in main()...
Display the returned value from FunctThree = 200
Now, in FunctFour()...
Received something, but return nothing...
The value processed here = 30
Then within FunctFour, call FunctOne()...
Now I'm in FunctOne()!...
Receives nothing, return nothing...
Back in FunctFour()....
Finally back in main()...
Related C and C++ further reading and digging:
- ISO/IEC 9899 (ISO/IEC 9899:1990) - C Programming languages.
- ISO/IEC 9899 (ISO/IEC 9899:2018) - C Programming languages.
- ISO/IEC 9945-1:2003 POSIX Part 1 Base Definition.
- ISO/IEC 14882:1998 on the programming language C++.
- Latest, ISO/IEC 14882:2017 on the programming language C++.
- ISO/IEC 9945:2018, The Single UNIX Specification, Version 4.
- Get the GNU C library information here.
- Read online the GNU C library here.