=============================MODULE4======================================= | | | The program examples' source codes have been arranged in the same | | order that appeared in the Tutorial. This is unedited and unverified | | compilation. Published as is basis for educational, reacretional and | | brain teaser purposes. All trademarks, copyrights and IPs, wherever | | exist, are the sole property of their respective owner and/or | | holder. Any damage or loss by using the materials presented in this | | tutorial is USER responsibility. Part or full distribution, | | reproduction and modification is granted to any body. | | Copyright 2003-2005 © Tenouk, Inc. All rights reserved. | | Distributed through http://www.tenouk.com | | | | | =========================================================================== Originally programs compiled using Borland C++. Examples compiled using VC++/VC++ .Net and gcc or g++ are given at the end of every Module. For example if you want to compile C++ codes using VC++/VC++ .Net, change the header file accordingly. Just need some modification for the header files...: ------------------------------------------------- #include //for system() #include ... { C++ codes... } ------------------------------------------------- should be changed to: ------------------------------------------------- #include //use C++ wrapper to call C functions from C++ programs... #include using namespace std; ... { C++ codes... } ------------------------------------------------- In VC++/VC++ .Net the iostream.h (header with .h) is not valid anymore. It should be C++ header, so that it comply to the standard. In older Borland C++ compiler this still works, but not proper any more... and for standard C/C++ the portability should be no problem or better you read Module23 at http://www.tenouk.com/Module23.html to get the big picture...For C codes, they still C codes :o) ========================================================================= ========================================================================= //Demonstrate a simple function //header files used to call predefined functions needed in //this program such as printf() #include #include //function prototype, explained later long cube(long); void main() { long input, answer; printf("\n--Calculating cube volume--\n"); printf("Enter a positive integer, for cube side (meter): "); scanf("%d", &input); //calling cube function answer = cube(input); //%ld is the conversion specifier for a long decimal //integer, more on this in another Module printf("\nCube with side %ld meter, is %ld cubic meter.\n", input, answer); system("pause"); } //function definition, define what the function will do long cube(long x) { //local scope (to this function) variable long x_cubed; //do some calculation x_cubed = x * x * x; //return a result to calling program return x_cubed; } -------------------------------------------------------------------------------------------------------------------------- //Demonstration the difference between //arguments and parameters //header files, used for predefined functions in the //standard library #include #include //main() function void main() { float x = 3.5, y = 65.11, z; float half_of (float); //In this call, x is the argument to half_of(). z = half_of(x); printf("The function call statement is z = half_of(x)\n"); printf("where x = 3.5 and y = 65.11...\n\n"); printf("Passing argument x\n"); printf("The value of z = %f \n", z); //In this call, y is the argument to half_of() z = half_of(y); printf("\nPassing argument y\n"); printf("The value of z = %f \n\n", z); //using predefined function system() in stdlib.h system("pause"); } //function definition float half_of(float k) { //k is the parameter. Each time half_of() is called, //k has the value that was passed as an argument. return (k/2); } ------------------------------------------------------------------------------------------------------------------------- //Using multiple return statements in a function #include #include //Function prototype int larger_of(int, int); void main() { int x, y, z; puts("Enter two different integer values,"); puts("separated by space. Then press Enter key: "); scanf("%d%d", &x, &y); //function call z=larger_of(x, y); printf("\nThe larger value is %d.", z); printf("\n"); system("pause"); } //Function definition int larger_of(int a, int b) { //return a or b if(a > b) return a; else return b; } --------------------------------------------------------------------------------------------------------------- //For C++ codes using VC++/VC++ .Net, change the header files accordingly //#include //#include //using namespace std; #include #include //function prototype void prt(int); //the main function definition int main() { //declare an integer variable int x=12; //calls prt() and passes/bring along x prt(x); cout< #include /*variadic function's prototype, count variable is the number of arguments*/ int sum_up(int count,...) { va_list ap; int i, sum; /*Initialize the argument list.*/ va_start (ap, count); sum = 0; for (i = 0; i < count; i++) /*Get the next argument value.*/ sum += va_arg (ap, int); /*Clean up.*/ va_end (ap); return sum; } int main(void) { /*This call prints 6.*/ printf("%d\n", sum_up(2, 2, 4)); /*This call prints 16.*/ printf("%d\n", sum_up(4, 1, 3, 5, 7)); return 0; } --------------------------------------------------------------------------------------------------------------- //function skeleton example //passing by values #include #include //function prototypes and their variations... //notice and remember these variations... void FunctOne(void); double FunctTwo(); int FunctThree(int); void FunctFour(int); //main program... void main() { cout<<"I'm in main()..."<> widthOfYard; cout<< "\nThe long of your yard(meter)? "; cin>> lengthOfYard; //function call areaOfYard = FindTheArea(lengthOfYard, widthOfYard); cout<< "\nYour yard is "; cout<< areaOfYard; cout<< " square meter\n\n"; system("pause"); return 0; } USHORT FindTheArea(USHORT l, USHORT w) { return (l * w); } ------------------------------------------------------------------------------------------------------------------- #include #include //function prototype float Convert(float); int main() { float TempFer; float TempCel; cout<<"Please enter the temperature in Fahrenheit: "; cin>>TempFer; //function call TempCel = Convert(TempFer); cout<<"\n"; cout< #include //function prototype void myFunction(); //global scope variables int x = 5, y = 7; int main() { cout<<"x = 5, y = 7, global scope\n"; cout<<"\nx within main: "< #include //function prototype void myFunc(); int main() { int x = 5; cout<<"\nIn main x is: "< #include //function prototype void swap(int x, int y); int main() { int x = 5, y = 10; cout<<"In main. Before swap, x: "< #include //function prototype long int Doubler(long int AmountToDouble); long int main() { long int result = 0; long int input; cout<<"Enter a number to be doubled: "; cin>>input; cout<<"\nBefore Doubler() is called... "; cout<<"\ninput: "< 10000, see the output...\n"; system("pause"); return 0; } long int Doubler(long int original) { if (original <= 10000) return (original * 2); else { cout<<"Key in less than 10000 please!\n"; return -1; } } ----------------------------------------------------------------------------------------------------------------------- //Demonstrates the use of //default parameter values #include #include //function prototype //width = 25 and height = 1, are default values int AreaOfCube(int length, int width = 25, int height = 1); int main() { //Assigning new values int length = 100; int width = 50; int height = 2; int area; //function call area = AreaOfCube(length, width, height); cout<<"First time function call, area = "< #include //inline function, no need prototype here //directly declares and defines the function inline int Doubler(int target) {return (2*target);} int main() { int target; cout<<"Enter a number to work with: "; cin>>target; cout<<"\n"; //function call target = Doubler(target); cout<<"First time function call, Target: "< #include #include int main() { int i; cout<<"Ten random numbers from 0 to 99\n\n"; //loop, learn later for(i=0; i<10; i++) { //random number function generator cout< #include //function prototype float AddNum(float, float); //main program void main(void) { cout<<"The function body..."< #include //function prototype float AddNum(float, float); void main(void) { //global (to this file) scope variables float p, q, r; //Prompt for user input cout<<"Enter two numbers separated by space: "<>p>>q; //function call r = AddNum(p, q); //Display the result cout<<"Addition: "<

#include //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: "<>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: "<

#include 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); } ------------------------------------------------------------------------------------------------------ //user defined function and header file //Simple arithmetic functions //New main program #include #include #include "arithmet.h" //notice this! //global variables, need 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: "<>p>>q; r = AddNum(p, q); s = SubtractNum(p, q); t = DivideNum(p, q); u = MultiplyNum(p, q); cout<<"Addition: "<

#include #include "arithmet.h" //global variable 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: "<>p>>q; //r = AddNum(p, q); //s = SubtractNum(p, q); t = DivideNum(p, q); u = MultiplyNum(p, q); //cout<<"Addition: "<

#include //using instead of "arithmet.h" #include //global variables 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: "<>p>>q; //r = AddNum(p, q); //s = SubtractNum(p, q); t = DivideNum(p, q); u = MultiplyNum(p, q); //cout<<"Addition: "<

#include //function prototype, receives long type //returns also long type long factor(long); int main() { int p; cout<<"Calculating factorial using recursive function"< 1 else //return and call itself return (number * factor(number-1)); } ------------------------------------------------------------------------------------------------------------------- //Demonstrates recursive Fibonacci function //the formula, fibonacci(n) = fibonacci(n-1)+fibonacci(n-2) #include #include long fibonacci(long); int main() { int p; cout<<"Simple fibonacci using recursive function"< #include main() { int c; //generating random number printf("10 random numbers:\n"); //loop 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"); system("pause"); return 0; } ------------------------------------------------------------------------------------------------------------------- //Simple time and date… #include //for time and date #include //for sleep() #include int main(void) { //structure data type, learnt in another Module struct tm *time_now; time_t secs_now; time_t t; char str[80]; time(&t); //dispaly current time and date... //using ctime() printf("Today's date and time: %s", ctime(&t)); //Formating 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; } ---------------------------------------------------------------------------------------------------------------------- //Converts the date and time to Greenwich Mean Time (GMT) #include #include #include #include //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 #include //for sleep() #include //a pointer to an array of string, learnt later char *wday[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Unknown"}; int main() { //structure data type, learnt later 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; } ------------------------------------------------VC++/VC++ .Net---------------------------------------- //C run-time Microsoft C example #include #include int main(void) { struct tm *time_now; time_t secs_now; time_t t; char str[80]; time(&t); //dispaly current time and date... //using ctime() printf("Today's date and time: %s\n", ctime(&t)); //Formating 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; } --------------------------------------------------gcc------------------------------------------------------ /***function skeleton example, function.c***/ #include /*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"); } ===========================================================================================================