|< C & C++ Functions 3 | Main | C Formatted I/O 1 >| Site Index | Download |


 

 

 

 

MODULE 4c

FINAL PART C/C++ FUNCTIONS PROGRAMMING 4

Receive nothing, return nothing-receive nothing, return something-
receive something, return something-receive something, return nothing
And they do something.  That is a function!

 

 

 

 

 

 

 

 

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 and lab worksheet 4.

 

The C and C++ skills that supposed to be acquired:

 

  • Able to understand and do the C/C++ function programming.

  • Able to find predefined/built-in standard and non-standard functions resources.

  • Able to understand and use predefined/built-in standard and non-standard functions.

  • Able to understand and use the variadic functions.

 

Example #13 – Using Functions In User Defined Header file

  • This part will show you the process of defining function, storing in header files and using this function and header file.

  • Assume that we want to create simple functions that do the basic calculation: addition, subtraction, division and multiplication of two operands.

  • Firstly, we create the main() program, then we create header file named arithmet.h to store these frequently used function.

  • Note the steps of this simple program development.  Firstly we create a simple program skeleton.  Compile and run.  Make sure there is no error; warning is OK because this just as an exercise.

// 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;
}

 

Output:

 

C/C++ user defined header file

// 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);
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

C/C++ user defined function and header file

// 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);

}

C/C++ user defined function and header file

// 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);

}

// 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;

}

C/C++ user defined function and header file

// 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;

}

 

Output:

 

C/C++ user defined function and header file

// 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;

 }

 

Output:

 

C/C++ user defined function and header file

 

-----------------------------------------------------------

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Example #14 – Recursive function

 

// 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));

}

 

Output:

 

C/C++ factorial a recursive function

 

Example #15 – Another recursive function

 

// 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));

}

 

Output:

 

C/C++ fibonacci a recursive function

 

Example #16 – Using predefined function

 

// 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;

}

 

Output:

 

C/C++ standard header file example random()

 

Example #17 – Using predefined function

 

// 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;

}

 

Output:

 

C/C++ function from standard header file time and date

 

 

Example #18 – Using predefined function

 

// 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;

}

 

Output:

 

C/C++ function from standard header file time and date

 

Example #19 – Using predefined function

 

// 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;

}

 

Output:

 

C/C++ function from standard header file time and date

#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;

}

 

Output:

 

C/C++ function from standard header file time and date

/*** 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()...

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

Related C and C++ further reading and digging:

 

  1. Check the best selling C / C++ books at Amazon.com.
  2. For this Module purpose, you can check the standard libraries of these various standards of C / C++.  Explore and compare the standard functions and their variation if any in the libraries.  You can download or read online the specification at the following links. (ISO/IEC is covering ANSI and is more general):
  1. ISO/IEC 9899 (ISO/IEC 9899:1999) - C Programming languages.
  2. ISO/IEC 9945:2002 POSIX standard.
  3. ISO/IEC 14882:1998 on the programming language C++.
  4. ISO/IEC 9945:2003, The Single UNIX Specification, Version 3.
  5. Get the GNU C library information here.

  6. Read online the GNU C library here.

 

 

 

 

 

|< C & C++ Functions 3 | Main | C Formatted I/O 1 >| Site Index | Download |


C and C++ Functions:  Part 1 | Part 2 | Part 3 | Part 4 |