=============================MODULE6======================================= | | | 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) ========================================================================= ========================================================================= #include int main() { float rate = 5.0; int hours = 25; float pay = (float) hours * rate; printf("\nPay = $%.2f \n", pay); return 0; } --------------------------------------------------------------------------------------------------- //Chnage the header files accordingly for other C++ examples... //#include //#include //using namespace std; #include #include int main() { int job_code; double housing_allowance, entertainment_allowance, car_allowance; cout<<"Available job codes: 1 or non 1:\n"<>job_code; //if 1 is selected if(job_code==1) { car_allowance = 200.00; housing_allowance = 800.00; entertainment_allowance = 250.00; cout<<"--THE BENEFITS--\n"; cout<<"Car allowance: "< #include int main() { char job_title; int years_served, no_of_pub; cout<<"Enter data \n"; cout<<"Current job (Tutor-T, lecturer-L, Assoc prof-A): "; cin>>job_title; cout<<"Years served: "; cin>>years_served; cout<<"No of publication: "; cin>>no_of_pub; if(job_title == 'T') { if(years_served > 15) if(no_of_pub > 10) cout<<"\nPromote to lecturer"; else cout<<"\nMore publications required"; else cout<<"\nMore service required"; } else if(job_title == 'L') { if(years_served > 10) if(no_of_pub > 5) cout<<"\nPromote to Assoc professor"; else cout<<"\nMore publications required"; else cout<<"\nMore service required"; } else if(job_title == 'A') { if(years_served > 5) if(no_of_pub > 5) cout<<"\nPromote to professor"; else cout<<"\nMore publications required"; else cout<<"\nMore service required"; } cout<<"\n"; system("pause"); return 0; } ------------------------------------------------------------------------------------- #include #include int main() { int mark; cout<<"Enter student's mark: "; cin>>mark; if (mark < 40) cout<<"Student grade = F"; else if (mark < 50) cout<<"Student grade = E"; else if (mark < 60) cout<<"Student grade = D"; else if (mark < 70) cout<<"Student grade = C"; else if (mark < 80) cout<<"Student grade = B"; else cout<<"Student grade = A"; cout<<"\n"; system("pause"); return 0; } -------------------------------------------------------------------------------------- //Program example of if-else statement. This program //is to test whether a banking transaction is a deposit, //withdrawal, transfer or an invalid transaction, //and to take the necessary action. #include #include int main() { float amount; char transaction_code; cout<<"D - Cash Deposit, W - Cash Withdrawal, T - Cash Transfer\n"; cout<<"\nEnter the transaction code(D, W, T); "; cin>>transaction_code; if (transaction_code == 'D') { cout<<"\nDeposit transaction"; cout<<"\nEnter amount: "; cin>>amount; cout<<"\nPROCESSING....Please Wait"; cout<<"\nAmount deposited: "<>amount; cout<<"\nPROCESSING....Please Wait"; cout<<"\nAmount withdrawn: "<>amount; cout<<"\nPROCESSING....Please Wait"; cout<<"\nAmount transferred: "< #include int main() { char selection; cout<<"\n Menu"; cout<<"\n========"; cout<<"\n A - Append"; cout<<"\n M - Modify"; cout<<"\n D - Delete"; cout<<"\n X - Exit"; cout<<"\n Enter selection: "; cin>>selection; switch(selection) { case 'A' : {cout<<"\n To append a record\n";} break; case 'M' : {cout<<"\n To modify a record";} break; case 'D' : {cout<<"\n To delete a record";} break; case 'X' : {cout<<"\n To exit the menu";} break; //Other than A, M, D and X... default : cout<<"\n Invalid selection"; //No break in the default case } cout<<"\n"; system("pause"); return 0; } ----------------------------------------------------------------------------------- //A simple for statement #include #include void main() { int count; //display the numbers 1 through 10 for(count = 1; count <= 10; count++) printf("%d ", count); printf("\n"); system("pause"); } ----------------------------------------------------------------------------------- //program to show the nested loops #include #include int main() { //variables for counter… int i, j; //outer loop, execute this first... for(i=1; i<11; i++) { cout<<"\n"< #include //function prototype void DrawBox(int, int); void main() { //row = 10, column = 25... //function call DrawBox(10, 25); } void DrawBox(int row, int column) { int col; //row, execute outer for loop... //start with the preset value and decrement //until 1 for( ; row > 0; row--) { //column, execute inner loop... //start with preset col, decrement until 1 for(col = column; col > 0; col--) //print #.... printf("#"); //decrement by 1 for inner loop... //go to new line for new row... printf("\n"); } //decrement by 1 for outer loop...then repeat... system("pause"); } -------------------------------------------------------------------------------------- //Demonstrates a simple while statement #include #include int main() { int calculate; //print the numbers 1 through 12 //set the initial value... calculate = 1; //set the while condition... while(calculate <= 12) { //display... printf("%d ", calculate); //increment by 1...repeats calculate++; } printf("\n"); system("pause"); return 0; } -------------------------------------------------------------------------------------- //Nested while statements #include #include //this program have some array variable //that you will learn in another module... void main() { //array variable... int arrange[5]; //normal variable int count = 0, number = 0; printf("\Prompting you for 5 numbers\n"); printf("Each number should be from 1 to 10\n"); //while condition... while(count<5) { //set the initial condition... number = 0; //another while condition... while((number < 1) || (number > 10)) { printf("Enter number %d of 5: ", count + 1); scanf("%d", &number); } //inner while loop stop here... arrange[count] = number; count++; } //outer while loop stop here... //start the for loop for printing the result... for (count = 0; count < 5; count++) printf("\nValue %d is %d", count + 1, arrange[count]); printf("\n"); system("pause"); } -------------------------------------------------------------------------------------- //program to illustrate a do…while loop #include #include int main() { int selection; do { cout<<"\n Menu"<<"\n"; cout<<"\n 0. Exit"; cout<<"\n 1. Append"; cout<<"\n 2. Delete"; cout<<"\n 3. Modify"; cout<<"\n\n Enter selection: "; cin>>selection; }while((selection > 0) && (selection < 4)); //true for 1, 2 and 3 ONLY, then repeat //false for other numbers including 0, then stop... //the do loop is repeated if the while expression is true. system("pause"); return 0; } ------------------------------------------------------------------------------------ //another do…while statement example #include #include int get_menu_choice(void); void main() { int choice; choice = get_menu_choice(); printf("You have chosen Menu #%d\n", choice); printf("\n"); system("pause"); } int get_menu_choice(void) { int selection = 0; do { printf("1 - Add a record"); printf("\n2 - Change a record"); printf("\n3 - Delete a record"); printf("\n4 - Quit"); printf("\nEnter a selection: "); scanf("%d", &selection ); } while ((selection < 1) || (selection > 4)); return selection; } ---------------------------------------------------------------------------------- //example of the continue #include #include void main() { //declare storage for input, an array //and counter variable char buffer[81]; int ctr; //input and read a line of text using //puts() and gets() are pre defined functions //in stdio.h puts("Enter a line of text and press Enter key,"); puts("all the vowels will be discarded!:\n"); gets(buffer); //go through the string, displaying only those //characters that are not lowercase vowels for(ctr=0; buffer[ctr] != '\0'; ctr++) { //If the character is a lowercase vowel, loop back //without displaying it //this if statement must be in one line if((buffer[ctr]=='a')||(buffer[ctr]=='e')|| (buffer[ctr]=='i')||(buffer[ctr]=='o')||(buffer[ctr]=='u')) continue; //If not a vowel, display it putchar(buffer[ctr]); } printf("\n"); system("pause"); } ----------------------------------------------------------------------------------- //demonstrate the goto statement #include #include void main() { int n; start: ; puts("Enter a number between 0 and 10: "); scanf("%d", &n); if ((n < 0) || (n > 10)) goto start; else if (n == 0) goto location0; else if (n == 1) goto location1; else goto location2; location0: ; { puts("You entered 0."); } goto end; location1: ; { puts("You entered 1."); } goto end; location2: ; { puts("You entered something between 2 and 10."); } end: ; system("pause"); } ---------------------------------------------------------------------------------- #include #include //function prototypes... void cleanup1(void); void cleanup2(void); void main() { atexit(cleanup2); atexit(cleanup1); //end of main } void cleanup1(void) { //dummy cleanup..... printf("\nThis is the demonstration...\n"); printf("cleanup....\n"); printf("You computer is SHUTTING DOWN!!!"); getchar(); } void cleanup2(void) { //another dummy cleanup... printf("\nAnother cleanup..."); printf("\nWINDOWS 20000 is closing the entire program..."); printf("\nPlease WAIT..."); printf("\nSHUTTING DOWN IN PROGRESS...\n"); getchar(); } ----------------------------------------------------------------------------------- //Demonstrate the exit() and atexit() functions #include #include #include #define DELAY 1500000 //function prototypes void cleanup(void); void delay(void); void main() { int reply; //register the function to be called at exit atexit(cleanup); puts("Enter 1 to exit, any other to continue."); scanf("%d", &reply); if(reply == 1) exit(EXIT_SUCCESS); //pretend to do some work for(reply = 0; reply < 5; reply++) { puts("WORKING..."); delay(); } }//end of main //function definition... void cleanup(void) { puts("\nPreparing for exit"); delay(); } //function definition void delay(void) { long x; for(x = 0; x < DELAY; x++) ; system("pause"); } ----------------------------------------------------------------------------------- //Demonstrates the system() function #include #include void main() { //Declare a buffer to hold input char input[40]; while (1) { //get the user command puts("\nInput the desired DOS command, blank to exit"); gets(input); //Exit if a blank line was entered if(input[0] == '\0') exit(0); //execute the command system(input); } } ---------------------------------------------------------------------------------- //program showing function definition, declaration, call and //the use of the return statement #include #include int main() { float y1, y2, avgy; //A prototype for the function avg() //that main() is going to call float avg(float, float); y1=5.0; y2=7.0; //calling the function avg() i.e. control passes //to avg() and the return value is assigned to avgy avgy = avg(y1, y2); cout<<"\ny1 = "< #include int main() { float y1, y2, avgy; //function prototype... //display-avg() is declared to be of type void void display_avg(float); y1 = 5.0; y2 = 7.0; cout<<"\ny1 = "< int main() { int x; for(x = 1; x <= 10; x++) { //break loop only if x == 5 if (x == 5) break; printf("%d ", x); } printf("\nBroke out of loop at x == %d\n", x); getchar(); return 0; } ------------------------------------------------------------------------------------- //using the continue statement in a for structure #include #include int main() { int x; for(x = 1; x <= 10; x++) { //skip remaining code in loop only if x == 5 if(x == 5) continue; printf("%d ", x); } printf("\nUsed continue to skip printing the value 5\n"); system("pause"); return 0; } ------------------------------------------------------------------------------------ //using for statement to calculate compound interest #include #include #include //for pow() function int main() { int year; double amount, principal = 1000.0, rate = 0.05; printf("%4s%21s\n", "Year", "Amount on deposit"); for(year = 1; year <= 10; year++) { amount = principal * pow(1.0 + rate, year); printf("%4d%21.2f\n", year, amount); } system("pause"); return 0; } ------------------------------------------------------------------------------------- //Counting letter grades using while, switch //and multiple case #include #include int main() { int grade; int aCount=0,bCount=0,cCount=0,dCount=0,eCount=0,fCount = 0; printf("Enter the letter grades. \n"); printf("Enter the EOF character, ctrl-c or\n"); printf("ctrl-z, etc to end input.\n"); while((grade = getchar()) != EOF) { //switch nested in while switch(grade) { //grade was uppercase A or lowercase a case 'A': case 'a': ++aCount; break; //grade was uppercase B or lowercase b case 'B': case 'b': ++bCount; break; //grade was uppercase C or lowercase c case 'C': case 'c': ++cCount; break; //grade was uppercase D or lowercase d case 'D': case 'd': ++dCount; break; //grade was uppercase E or lowercase e case 'E': case 'e': ++eCount; break; //grade was uppercase F or lowercase f case 'F': case 'f': ++fCount; break; //ignore these input case '\n': case ' ': break; //catch all other characters default: {printf("Incorrect letter grade entered.\n"); printf("Enter a new grade.\n");} break; } } //Do the counting... printf("\nTotals for each letter grade are:\n"); printf("\A: %d\n", aCount); printf("\B: %d\n", bCount); printf("\C: %d\n", cCount); printf("\D: %d\n", dCount); printf("\E: %d\n", eCount); printf("\F: %d\n", fCount); system("pause"); return 0; } ----------------------------------------------VC++/VC++ .Net-------------------------------------------------- //using for statement to calculate compound interest #include //for pow() function #include int main() { int year; double amount, principal = 1000.0, rate = 0.05; printf("%4s%21s\n", "Year", "Amount on deposit"); for(year = 1; year <= 10; year++) { amount = principal * pow(1.0 + rate, year); printf("%4d%21.2f\n", year, amount); } return 0; } --------------------------------------------GCC on fedora---------------------------------------------------- #include int main() { char job_title; int years_served, no_of_pub; printf(" ---Enter data---\n"); printf("Your current job (Tutor-T, Lecturer-L or Assoc. Prof-A): "); scanf("%s", &job_title); printf("Years served: "); scanf("%d", &years_served); printf("No of publication: "); scanf("%d", &no_of_pub); if(job_title == 'A') if(years_served > 5) if(no_of_pub > 7) printf("\nCan be promoted to Professor\n"); else printf("\nMore publications required lol! \n"); else printf("\nMore service required lol\n"); else printf("\nMust become Associate Professor first\n"); return 0; } ------------------------------------------------------------------------------------------- /*-----forloop.c-----------*/ /*-----First triangle-------*/ #include int main() { int i, j, k, l; printf("Triangle lol!\n"); /*first for loop, set the rows...*/ for(i=15; i>=0; i--) { /*second for loop, set the space...*/ for(j=15; j>=1+i; j--) printf(" "); /*third for loop, print the characters...*/ for(j=1; j<=2*i+1; j++) /*print the character...*/ printf("H"); /*go to new line...*/ printf("\n"); } /*Another inverse triangle*/ for(k=1; k <= 16; k++) { for(l=1; l<=16-k; l++) printf(" "); for(l=1; l<=2*k-1; l++) printf("T"); printf("\n"); } return 0; } --------------------------------------------------------------------------------------------- /*-----------whilelol.c---------------*/ /*Demonstrates a simple while statement*/ #include int main() { int calculate, sum = 0; /*print the numbers 1 through 12*/ /*set the initial value...*/ calculate = 1; /*set the while condition...*/ while(calculate <= 10) { /*display...*/ printf("%d -->Sum = %d\n", calculate, sum); sum = sum + calculate; /*increment by 1...repeats*/ calculate++; } printf("\n"); return 0; } ----------------------------------------------------------------------------------------------- /*----- systemcall.c -------*/ /*Demonstrate the system() function*/ #include #include int main() { //Declare a buffer to hold input char input[40]; while (1) { //get the user command puts("\nInput the command, blank to exit"); gets(input); //Exit if a blank line was entered if(input[0] == '\0') exit(0); //execute the command system(input); } return 0; } ==========================================================================================================