Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
192 views

Codes Final 2005

The document contains code examples for C/C++ programs. Example 1 shows a simple program that takes input from the user and displays it. Example 2 adds two integer numbers. Example 3 solves a quadratic equation. The examples demonstrate basic input/output operations, if/else conditions, loops, functions etc. Later examples show temperature conversion, calculator operations, checking vowels, random number guessing games and more.

Uploaded by

mjrahimi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
192 views

Codes Final 2005

The document contains code examples for C/C++ programs. Example 1 shows a simple program that takes input from the user and displays it. Example 2 adds two integer numbers. Example 3 solves a quadratic equation. The examples demonstrate basic input/output operations, if/else conditions, loops, functions etc. Later examples show temperature conversion, calculator operations, checking vowels, random number guessing games and more.

Uploaded by

mjrahimi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 93

CSE 223: C Examples

Code 1-1: /******************************************************************************* * EXAMPLE 1.1: THIS PROGRAM WILL DISPLAY SIMPLE INPUT & OUTPUT * * AUTHOR: RAFIUL HOSSAIN * * DATE: April, 2004 * *******************************************************************************/ #include<iostream.h> //#include<iostream> //using namespace std; // C Style // // C++ Style //

int main() { int myRoll, myYear, mySemester; // Define input data type char firstName[100], lastName[100], myDept[100]; // Define input data type cout << "Enter your first name\t:\t"; // Print message on the screen cin >> firstName; // Put the 1st input cout << "Enter your last name\t:\t"; // Print message on the screen cin >> lastName; // Put the 2nd input cout << "Enter your roll number\t:\t"; // Print message on the screen cin >> myRoll; // Put the 3rd input cout << "Enter your year\t\t:\t"; // Print message on the screen cin >> myYear; // Put the 4th input cout << "Enter your semester\t:\t"; // Print message on the screen cin >> mySemester; // Put the 5th input cout << "Enter your dept name\t:\t"; // Print message on the screen cin >> myDept; // Put the 6th input return 0; // Default return } /* Note: Can't handle space(blank) in array input */ /* Note: Requires correct inputs. No check for incorrect inputs. */ /* Note: cin generates a new line */ Output in Visual C++ 6:

Code 2-1: /************************************************************************** * EXAMPLE 2.1: THIS PROGRAM WILL ADD TWO INTEGER NUMBERS * * AUTHOR: RAFIUL HOSSAIN * * DATE: April, 2004 * **************************************************************************/ #include<iostream.h> int main() { int num1,num2; int sum; cout << "Addition of two integer numbers:" << endl; //cout << "Addition of two integer numbers:" << "\n"; //cout << "Addition of two integer numbers:\n"; cout << "Enter first number\t:num1 = "; cin >> num1; cout << "Enter second number\t:num2 = "; cin >> num2; sum = num1 + num2; cout << "The sum of two numbers\t:sum = " << sum << endl; return 0; } Output in Visual C++ 6:

// Define input data type // Define output data type // Print message on the screen // Alternate choice for new line // Alternate choice for new line // Print message on the screen // Put the first input // Print message on the screen // Put the second input // Add two numbers // Print message on the screen // Default return

Code 3-1: /*************************************************************** * EXAMPLE 3.1: SOLVING QUADRATIC EQATIONS * * AUTHOR: RAFIUL HOSSAIN * * DATE: April, 2004 * ***************************************************************/ #include<iostream.h> #include<math.h> int main() { double a, b, c; // Define input data type double x1, x2; // Define output data type cout << "Solving a quadratic equation of x:" << endl;// Print message on the screen cout << "Enter first coefficient: a = "; // Print message on the screen cin >> a; // Give first input cout << "Enter second coefficient: b = "; // Print message on the screen cin >> b; // Give second input cout << "Enter third coefficient: c = "; // Print message on the screen cin >> c; // Give second input double sqrd = sqrt(pow(b,2) - 4*a*c); // Add two numbers x1 = (-b + sqrd) / (2*a); // Get the first root x2 = (-b - sqrd) / (2*a); // Get the second root cout << "The solutions are:" << endl; // Print message on the screen cout << "\tx1 = " << x1 << endl; // Print the first root cout << "\tx2 = " << x2 << endl; // Print the second root return 0; // Default return } // Note: b^2 - 4*a*c must not be less than zero // Note: sqrt return double data type. Use of float will give warning. Output in Visual C++ 6:

Code 4-0: /******************************************************************************** Example 4.0: This Program will find bigger number from two inter numbers Author: Rafiul Hossain Date: April, 2004 ********************************************************************************/ #include<iostream.h> int main() { int num1, num2; cout << "Finding the bigger number from two integer numbers" << endl; cout << "----------------------------------------------------------------" << endl << endl; cout << "Enter the first number\t: "; cin >> num1; cout << "Enter the second number\t: "; cin >> num2; int flag, biggerNum; flag = 1; if(num1>num2) biggerNum = num1; else if(num2>num1) biggerNum = num2; else { cout << "\n*** Numbers are EQUAL! ***" << endl; // check numbers are equal flag = 0; } if(flag) cout << "\nBigger number is\t: " << biggerNum << endl << endl; return 0; } Output in Visual C++ 6: // check num1 is bigger // check num2 is bigger

Code 4-0a: // Nested if Example. Max of 3 different integer numbers #include<iostream.h> int main() { int num1, num2, num3; cout << "Enter 1st number : "; cin >> num1; cout << "Enter 2nd number : "; cin >> num2; cout << "Enter 3rd number : "; cin >> num3; if(num1 > num2) if(num1 > num3) cout << "Maximum number is: " << num1 << endl; else cout << "Maximum number is: " << num3 << endl; else if(num2 > num3) cout << "Maximum number is: " << num2 << endl; else cout << "Maximum number is: " << num3 << endl; return 0; }

Code 4-0b: // Odd or EVEN Example. #include<iostream.h> int main() { int N; cout << "Enter the final value: "; cin >> N; cout << endl <<"Enter \"O\" for sum of odd numbers" << endl; cout << "Enter \"E\" for sum of even numbers" << endl << endl; char choice; cout << "Enter your choice: "; cin >> choice; int start; if(choice == 'O' || choice == 'o') { start = 1; cout << "Sum of ODD numbers: "; } else if(choice == 'E' || choice == 'e') { start = 0; cout << "Sum of EVEN numbers: "; } else { cout << "Invalid CHOICE !!!" << endl; cout << "This is GARBAGE => "; } int sum =0; for(int i = start; i <= N; i+=2) sum = sum + i; cout << sum << endl; return 0; }

Code 4-0c: // Odd and EVEN Example. #include<iostream.h> int main() { int N; cout << "Enter the final value: "; cin >> N; int start; for(int j = 0; j < 2; j++) { if(j == 0) { start = 1; cout << "Sum of ODD numbers: "; } else { start = 0; cout << "Sum of EVEN numbers: "; } int sum = 0; for(int i = start; i <= N; i+=2) sum = sum + i; cout << sum << endl; } return 0; }

Code 4-1: #include<iostream.h> int main() { int choice; double temperature; cout << "Enter temperature in Farenheit or Celsius: "; cin >> temperature; cout << "Type 1 to convert Farenheit to Celsius" << endl; cout << "Type 2 to convert Celsius to Farenheit" << endl; cout << endl << "Enter your choice: "; cin >> choice; if(choice == 1) { cout << "Temperature in Farenheit: " << temperature << endl; cout << "Temperature in Celsius: " << (temperature- 32.0)*5.0/9.0 << endl; } else { cout << "Temperature in Celsius: " << temperature << endl; cout << "Temperature in Farenheit: " << (9.0/5.0)*temperature + 32 << endl; } return 0; } Output in Visual C++ 6:

Code 4-2: #include<iostream.h> int main() { char oper, choice; double num1, num2, ans; do{ cout << "Enter first number, operator, second number: "; cin >> num1 >> oper >> num2; switch(oper) { case '+': ans = num1 + num2; break; case '-': ans = num1 - num2; break; case '*': ans = num1 * num2; break; case '/': ans = num1 / num2; break; default: "Invalid Operator!"; } cout << "ans = " << ans << endl; cout << "Try again (Enter 'y' or 'n')? "; cin >> choice; }while(choice != 'n'); return 0; } Output in Visual C++ 6:

10

Code 4-3: // Simple Vowel or Consonant #include<iostream.h> int main() { char myChar; do { cout << "Enter any chracter: "; cin >> myChar; }while (myChar < 'a' || myChar > 'z'); switch(myChar) { case 'a': cout << myChar << " => vowel" << endl; break; case 'e': cout << myChar << " => vowel" << endl; break; case 'i': cout << myChar << " => vowel" << endl; break; case 'o': cout << myChar << " => vowel" << endl; break; case 'u': cout << myChar << " => vowel" << endl; break; default : cout << myChar << " => consonant" << endl; } return 0; } Output in Visual C++ 6:

Output: Enter any character: 1 Enter any character: A Enter any character: p p => consonant Press any key to continue

11

Code 4-4: // Vowel or Consonant #include<iostream.h> #include<stdlib.h> int main() { char myChar, tempChar; do { cout << "Enter any chracter: "; cin >> myChar; tempChar = myChar; if(myChar >='A' && myChar <='Z') myChar = tolower(myChar); }while (myChar < 'a' || myChar > 'z'); int flag = 0; switch(myChar) { case 'a': case 'e': case 'i': case 'o': case 'u': flag = 1; } if(flag) cout << tempChar << " => VOWEL" << endl; else cout << tempChar << " => CONSONANT" << endl; return 0; } Output in Visual C++ 6:

12

Code 5-1: /******************************************************************************** Example 5.1: This Program will check you luck - Version 1 Author: Rafiul Hossain Date: April, 2004 ********************************************************************************/ #include<iostream.h> #include<stdlib.h> int main() { int magic, guess; cout << "Guess the MAGIC number" << endl; cout << "===================" << endl << endl; magic = rand()%99; cout << "Enter the number you guessed\t: "; cin >> guess; cout << "Magic number\t: " << magic << endl; cout << "Your number\t: " << guess << endl; if(magic == guess) { cout << "*** You are RIGHT ***" << endl << endl; } else { cout << "!!! You are WRONG !!!" << endl << endl; } return 0; } Output in Visual C++ 6: // Correct guess

// Incorrect guess

13

Code 5-2: /******************************************************************************** Example 5.2: This Program will check you luck - Version 2 Author: Rafiul Hossain Date: April, 2004 ********************************************************************************/ #include<iostream.h> #include<stdlib.h> int main() { int magic, guess; cout << "Guess the MAGIC number" << endl; cout << "======================" << endl << endl; for(int i=0; i<=2; i++) { magic = rand()%99; cout << "Enter the number you guessed\t: "; cin >> guess; cout << "Magic number\t: " << magic << endl; cout << "Your number\t: " << guess << endl; if(magic == guess) { cout << "*** You are RIGHT ***" << endl << endl; } else { cout << "!!! You are WRONG !!!" << endl << endl; } } return 0; } // Guess three times

14

Output in Visual C++ 6:

15

Code 5-3: /******************************************************************************** Example 5.3: This Program will check you luck - Version 3 Author: Rafiul Hossain Date: April, 2004 ********************************************************************************/ #include<iostream.h> #include<stdlib.h> int main() { int magic, guess; char yesNo; cout << "Guess the MAGIC number" << endl; cout << "===================" << endl; int flag = 1; while(flag) { magic = rand()%99; cout << "\nEnter the number you guessed\t: "; cin >> guess; cout << "Your number\t: " << guess << endl; cout << "Magic number\t: " << magic << endl; if(magic == guess) { cout << "*** You are RIGHT ***" << endl << endl; //flag =0; exit (0); // Alternate } else { cout << "!!! You are WRONG !!!" << endl << endl; cout << "Try AGAIN ? [Y/N]: "; cin >> yesNo; //if(yesNo == 'Y' || yesNo == 'y') flag = 1; if(yesNo == 'Y' || yesNo == 'y') continue; // Alternate //else flag = 0; else exit(0); // Alternate } } return 0; 16 // Random number less than 100 // Guessed number

} Output in Visual C++ 6:

17

Code 6-1: /******************************************************************************** Example 6.1: This Program for Simple Menu using if-else block - Version 1 Author: Rafiul Hossain Date: April, 2004 ********************************************************************************/ #include<iostream.h> int main() { float num1, num2; int choice; char try_again; try_again='y'; cout << "Simple Math Operation of two numbers" << endl; cout << "============================" << endl << endl; cout << "Instruction 1: Enter two integer numbers first.\n"; cout << "Instruction 2: Choose a number from 1 to 4 for the desired math operation.\n\n"; while(try_again=='y') { cout << "Enter the first number\t: "; cin >> num1; cout << "Enter the Second number\t: "; cin >> num2; cout << "\n||||||< MENU >||||||\n\n"; cout << "[1]. Addition\n"; cout << "[2]. Subtraction\n"; cout << "[3]. Multiplication\n"; cout << "[4]. Division\n\n"; cout << "Choose the desired option [1/2/3/4]: "; cin >> choice; float result; if(choice == 1) { result = num1+num2; cout << endl << num1 << " + " << num2 << " = " << result; } else if(choice == 2) { result = num1-num2; cout << endl << num1 << " - " << num2 << " = " << result; } else if(choice == 3) { 18

result = num1*num2; cout << endl << num1 << " * " << num2 << " = " << result; } else if(choice == 4) { result = num1/num2; cout << endl << num1 << " / " << num2 << " = " << result; } else { cout << "\nInvalid choice. Try again !"; } cout << "\n\nDo you want to continue? [Y/N]: "; cin >> try_again; } return 0; } Output in Visual C++ 6:

19

Code 6-2: /******************************************************************************** Example 6.2: This Program for Simple Menu using switch-case block - Version 2 Author: Rafiul Hossain Date: April, 2004 ********************************************************************************/ #include<iostream.h> int main() { float num1, num2; int choice; char try_again; try_again='y'; int valid; cout << "Simple Math Operation of two numbers" << endl; cout << "============================" << endl << endl; cout << "Instruction 1: Enter two integer numbers first.\n"; cout << "Instruction 2: Choose a number from 1 to 4 for the desired math operation.\n"; while(try_again=='y') { cout << "\nEnter the first number\t: "; cin >> num1; cout << "Enter the Second number\t: "; cin >> num2; cout << "\n||||||< MENU >||||||\n\n"; cout << "[1]. Addition\n"; cout << "[2]. Subtraction\n"; cout << "[3]. Multiplication\n"; cout << "[4]. Division\n\n"; valid=1; while(valid) { cout << "Choose the desired option [1/2/3/4]: "; cin >> choice; float result; switch(choice) { case 1: result = num1+num2; cout << endl << num1 << " + " << num2 << " = " << result; valid=0; break; case 2: 20

result = num1-num2; cout << endl << num1 << " - " << num2 << " = " << result; valid=0; break; case 3: result = num1*num2; cout << endl << num1 << " * " << num2 << " = " << result; valid=0; break; case 4: result = num1/num2; cout << endl << num1 << " / " << num2 << " = " << result; valid=0; break; default: cout << "\nInvalid choice. Try again !\n\n"; valid=1; break; } } cout << "\n\nDo you want to continue? [Y/N]: "; cin >> try_again; } return 0; } Output in Visual C++ 6:

21

Code 7-1: /**************************************************************** * Example 7.1: Simple one dimensional array * Author: Rafiul Hossain * Date: May 2004 ****************************************************************/ #include <iostream.h> int main() { int myArray [10]; int i; for(i=0; i<10; i++) myArray[i] = i; cout << "The contents of the array are: " << endl; for(i=0; i<10; i++) cout << "myArray[" << i << "] = " << myArray[i] <<endl; return 0; } Output in Visual C++ 6:

22

Code 7-2: /**************************************************************** * Example 7.2: Simple two dimensional array * Author: Rafiul Hossain * Date: May 2004 ****************************************************************/ #include <iostream.h> int main() { int myArray[3][4]; int i,j; for(i=0; i<3; i++) for(j=0; j<4; j++) myArray[i][j] = i*4 + j +1; cout << "The contents of the array are:" << endl; for(i=0; i<3; i++) for(j=0; j<4; j++) cout << "\tmyArray[" << i << "][" << j << "] = " << myArray[i][j] <<endl; return 0; } Output in Visual C++ 6:

23

Code 7-3: /**************************************************************** * Example 7.3: Simple three dimensional array * Author: Rafiul Hossain * Date: May 2004 ****************************************************************/ #include <iostream.h> int main() { int myArray[3][4][3]; int i,j,k; for(k=0; k<3; k++) for(i=0; i<3; i++) for(j=0; j<4; j++) myArray[i][j][k] = k*12 + i*4 + j + 1; cout << "The contents of the array are:" << endl; for(i=0; i<3; i++) for(j=0; j<4; j++) for(k=0; k<=3; k++) if(k == 3) cout << endl; else cout << "\tmyArray[" << i << "][" << j << "][" << k << "] = " << myArray[i][j] [k]; return 0; } Output in Visual C++ 6:

24

Code 7-4: /* Use of Array */ #include <iostream.h> int main() { int age1, age2, age3, age4, age5; cout << "Calculate Average age of five persion:" << endl; cout << "Enter person 1 age: "; cin >> age1; cout << "Enter person 2 age: "; cin >> age2; cout << "Enter person 3 age: "; cin >> age3; cout << "Enter person 4 age: "; cin >> age4; cout << "Enter person 5 age: "; cin >> age5; float avgAge; avgAge = (age1 + age2 + age3 + age4 + age5)/5; //int totalAge = age1 + age2 + age3 + age4 + age5; cout << "Average age is: " << avgAge << endl; //cout << "Average age is: " << totalAge/5 << endl; return 0; } Output in Visual C++ 6: // warning: conversion from 'int' to 'float' // int / int produces int result

25

Code 7-5: /* Use of Array */ #include <iostream.h> int main() { float age[5]; float totalAge = 0; cout << "Calculate Average age of five persion:" << endl; for(int i=0; i<5; i++) { cout << "Enter person " << i+1 <<" age: "; cin >> age[i]; totalAge = totalAge + age[i]; } float avgAge = totalAge/5; cout << "Average age is: " << avgAge << endl; return 0; } Output in Visual C++ 6:

26

Code 7-6: #include<iostream.h> int main() { float age[100]; float sum, avg; int n, i; cout << "How many PERSONS: "; cin >> n; cout << endl << "Enter individual person's AGE below: " << endl << endl; sum = 0; for(i=0; i<n; i++) { cout <<"Enter person " << i+1 << " age: " ; cin >> age[i]; sum = sum + age[i]; } avg = sum / n; cout << endl <<"AVERAGE age is: " << avg << endl; float diffAge; int m; cout << endl <<"At what AGE: "; cin >> m; cout << endl << "Person at the AGE of " << m <<" YEARS: " << endl << endl; for(i=0; i<n; i++) { if(age[i] > m) { diffAge = age[i] - m; cout << "Person " << i+1 << ": " << diffAge << " Years back" << endl; } else if(age[i] == m) cout << "Person " << i+1 << ": Just " << m << " Years" << endl; else { diffAge = m - age[i]; cout << "Person " << i+1 << ": " << diffAge << " Years later" << endl; } } 27

return 0; } Output in Visual C++ 6:

28

Code 7-7: /**************************************************************** * Example 7.4: Sorting using array - Ver 1 * Author: Rafiul Hossain * Date: May 2004 ****************************************************************/ #include <iostream.h> #include <stdlib.h> int main() { int myArray[10]; int i, j; int temp; for(i=0; i<10; i++) myArray[i] = rand()%9; cout << "The random numbers are:" << endl; for(i=0; i<10; i++) cout << myArray[i] << endl; for(i=0; i<10; i++) for(j=i+1; j<10; j++) if(myArray[i] > myArray[j]) { temp = myArray[j]; myArray[j] = myArray[i]; myArray[i] = temp; } cout << "The sorted numbers are:" << endl; for(i=0; i<10; i++) cout << myArray[i] << endl; return 0; }

29

Output in Visual C++ 6:

30

Code 7-8: /**************************************************************** * Example 7.5: Sorting using array - Ver 2 * Author: Rafiul Hossain * Date: May 2004 ****************************************************************/ #include <iostream.h> #include <stdlib.h> int main() { int myArray[100]; int i, j; int temp; for(i=0; i<100; i++) myArray[i] = rand()%99; cout << "The random numbers are:" << endl <<endl; for(i=0; i<100; i++) if((i+1)%10 == 0) cout << myArray[i] << endl; else cout << myArray[i] << "\t"; for(i=0; i<99; i++) for(j=i+1; j<100; j++) if(myArray[i] > myArray[j]) { temp = myArray[j]; myArray[j] = myArray[i]; myArray[i] = temp; } cout << endl <<"The sorted numbers are:" << endl << endl; for(i=0; i<100; i++) if((i+1)%10 == 0) cout << myArray[i] << endl; else cout << myArray[i] << "\t"; return 0; }

31

Output in Visual C++ 6:

32

Code 7-9: /* Arrays of strings */ #include <iostream.h> int main() { int size1 = 100; int size2 = 20; char myName[100], myDept[100]; char myRoll[20], myYear[20], mySemester[20]; cout << "Enter your name\t\t: "; cin.getline(myName, size1); cout << "Enter your roll\t\t: "; cin.getline(myRoll, size2); cout << "Enter your department\t: "; cin.getline(myDept, size1); cout << "Enter your year\t\t: "; cin.getline(myYear, size2); cout << "Enter your semester\t: "; cin.getline(mySemester, size2); return 0; } Output in Visual C++ 6:

33

Code 7-10: #include<iostream.h> #include<string.h> void reverse(char[]); int main() { const int MAX = 80; char str[MAX]; cout << "Enter a string: "; cin.get(str, MAX); reverse(str); cout << "Reverse string is: " << str << endl; return 0; } void reverse(char s[]) { int len = strlen(s); for(int i = 0; i < len/2; i++) { char temp = s[i]; s[i] = s[len - i -1]; s[len - i - 1] = temp; } } Output in Visual C++ 6:

34

Code 7-11: // Prime Number #include<iostream.h> int main() { int prime; int pby2; cout << "Enter your number: "; cin >> prime; if(prime % 2 == 0) pby2 = prime / 2; else pby2 = (prime - 1) / 2; int divisor[100]; int count = 0; for(int i = 2; i <= pby2; i++) { if(prime % i == 0) { divisor[count] = i; count++; } } if(count > 0) { cout << prime << " is not a prime number" << endl; cout << "The number is divisible by: "; for(i = 0; i < count; i++) cout << divisor[i] << " "; cout << endl; } else cout << prime << " is a prime number" << endl; return 0; } Output in Visual C++ 6:

35

Code 7-12 // Prime Number from a Range #include<iostream.h> int main() { int start, end; int middle; cout << "Enter the start number: "; cin >> start; cout << "Enter the end number: "; cin >> end; int prime[1000]; int count = 0; int flag; for(int j = start; j < end; j++) { flag = 1; if(j % 2 == 0) middle = j / 2; else middle = (j - 1) / 2; for(int i = 2; i <= middle; i++) if(j % i == 0) flag = 0; if(flag) { prime[count] = j; count++; } } cout << "The prime numbers are:" << endl; for(int k = 0; k < count; k++) { if(k % 5 == 0) cout << endl; cout << prime[k] << "\t"; } cout << endl; return 0; } 36

Output in Visual C++ 6:

37

Code 8-1: // Simple function: Areas of Circles #include <iostream.h> double CircleArea(float r); int main() { float MyRadius1; cout << "Enter radius: "; cin >> MyRadius1; double Area1 = CircleArea(MyRadius1); cout << "Circle 1 has area: " << Area1 << endl; float MyRadius2 = 2*MyRadius1; double Area2 = CircleArea(MyRadius2); cout << "Circle 2 has area: " << Area2 << endl; return 0; } double CircleArea(float r) { const double Pi = 3.14; double Area = Pi * r * r; return Area; } Output in Visual C++ 6: // Function declaration

// Function invocation/calling // Function invocation/calling

// Function definition // Local variable. r doesn't change MyRadius1

38

Code 8-1b # Reverse an array #include<iostream.h> #include<stdlib.h> void reverse(int a[], int n); int main() { int myArray[100]; int i; cout << "How many elements in the Array: "; cin >> i; for(int j=0; j<i; j++) { myArray[j] = rand()%99; } cout << "The original array:" << endl; for(j=0; j<i; j++) { cout << myArray[j] << endl; } reverse(myArray, i); cout << endl << "The reverse array:" << endl; for(j=0; j<i; j++) { cout << myArray[j] << endl; } return 0; } void reverse(int a[], int n) { int head = 0; // index of first element int tail = n-1; // index of last element while (head < tail) { int temp = a[head]; a[head] = a[tail]; a[tail] = temp; head++; tail--; 39

} return; } Output in Visual C++ 6:

40

Code 8-2: // Simple function: Lower case upper case conversion #include <iostream.h> char lowerToUpper(char c1); int main() { char lower, upper; cout << "Enter a lower case character: "; cin >> lower; upper = lowerToUpper(lower); cout << "The upper-case equivalent is: " << upper << endl; return 0; } /*char lowerToUpper(char c1) { if(c1 >= 'a' && c1 <= 'z') return ('A' + c1 - 'a'); else return (c1); }*/ char lowerToUpper(char c1) // Alternate way: Conditional operator { char c2; c2 = (c1 >= 'a' && c1 <= 'z') ? ('A' + c1 - 'a') : c1; return (c2); } Output in Visual C++ 6:

41

Code 8-3: // Simple function: Calculate factorial #include <iostream.h> long factorial(int n); int main() { int n; cout << "n = "; cin >> n; cout << "The factorial is: " << factorial(n) << endl; return 0; } /*long factorial(int n) { int i; long prod = 1; if(n>1) for(i=2; i<=n; i++) prod *= i; return (prod); }*/ long factorial(int n) // Alternate: Function recursion { if(n<=1) return (1); else return (n * factorial(n - 1)); } Output in Visual C++ 6:

42

Code 8-4: // Get Day of Week for any Date #include<iostream.h> int dayofweek( int year, int month, int day); int main() { int yy, mm, dd; cout << "Enter Year[yyyy] Month[mm] Day[dd]: "; cin >> yy >> mm >> dd; int thisDay = dayofweek(yy, mm, dd); switch(thisDay) { case 0: cout << "Sunday" << endl; break; case 1: cout << "Monday" << endl; break; case 2: cout << "Tueday" << endl; break; case 3: cout << "Wednesday" << endl; break; case 4: cout << "Thursday" << endl; break; case 5: cout << "Friday" << endl; break; case 6: cout << "Saturday" << endl; break; default: cout <<"The D Day" << endl; } return 0; } int dayofweek( int year, int month, int day) /* 0=sunday, 1=monday, etc. */ { int a = (14-month) / 12; int y = year - a; int m = month + 12*a - 2; return (day + y + y/4 - y/100 + y/400 + (31*m)/12) % 7; } Output in Visual C++ 6:

43

Code 8-5: // Convert Decimal to Binary [Max 8-bit binary] #include<iostream.h> #include<stdio.h> void binaryOp(int byte); int main() { int byte; cout << "Enter a decimal integer number (<256): "; cin >> byte; binaryOp(byte); return 0; } void binaryOp(int byte) { int count = 8; int MASK = 1 << (count-1); /* Print a byte in binary*/ /* Print a byte in binary*/

/* Number of bits in a byte*/

while(count--) { /*AND the high order bit (the left one) If the bit is set print a ONE*/ cout << (( byte & MASK ) ? 1 : 0); /* Move all the bits LEFT*/ byte <<= 1; } cout << endl; } Output in Visual C++ 6:

44

Code 8-6: //*************************************** // Payroll program // This program computes each employee's // wages and the total company payroll //*************************************** #include <iostream.h> #include <fstream.h> // For file I/O void CalcPay( float, float, float& ); // Maximum normal work hours const float MAX_HOURS = 40.0; // Overtime pay rate factor const float OVERTIME = 1.5; //***************************************** int main() { float payRate; // Employee pay rate float hours; // Hours worked float wages; // Wages earned float total; // Total payroll int empNum; // Employee ID number ofstream payFile; // Payroll file payFile.open("payfile.txt"); payFile << "E. ID\t" << "P. Rate\t" << "Hours\t" << "Wages" << endl; payFile << "-----\t" << "-------\t" << "-----\t" << "-----" << endl << endl; total = 0.0; cout << "Enter employee number: "; cin >> empNum; while (empNum != 0) { cout << "Enter pay rate: "; cin >> payRate; cout << "Enter hours worked: "; cin >> hours; CalcPay(payRate, hours, wages); total = total + wages; payFile << empNum << "\t" << payRate << "\t" << hours << "\t"<< wages << endl; cout << "Enter employee number: "; cin >> empNum; } payFile << endl <<"Total payroll is: " << total << endl; return 0; } //***************************************** 45

void CalcPay( /* in */ float payRate, // Employee rate /* in */ float hours, // Hours worked /* out */ float& wages ) // Wages earned // CalcPay computes wages from the // employee's pay rate and the hours // worked, taking overtime into account { // Is there overtime? if (hours > MAX_HOURS) wages = (MAX_HOURS * payRate) + (hours - MAX_HOURS) * payRate * OVERTIME; else wages = hours * payRate; } // End of Payroll program Text file: E. ID P. Rate Hours Wages ----- ------- ----- ----1 2 3 10 15 20 60 50 40 700 825 800

Total payroll is: 2325 Output in Visual C++ 6:

46

Code 9-1: #include <iostream.h> #include <ctype.h> void scanLine(char line[], int *pv, int *pc, int *pd, int *pw, int *po); int main() { char line[100]; int vowel = 0; int consonant = 0; int digit = 0; int whiteSpace = 0; int other = 0; cout << "Enter a line of text: "; cin.getline(line, 100); scanLine(line, &vowel, &consonant, &digit, &whiteSpace, &other); cout << "Number of vowel: " << vowel << endl; cout << "Number of consonant: " << consonant << endl; cout << "Number of digit: " << digit << endl; cout << "Number of white space: " << whiteSpace << endl; cout << "Number of other: " << other << endl; return 0; } void scanLine(char line[], int *pv, int *pc, int *pd, int *pw, int *po) { char c; int count = 0; while((c = toupper(line[count])) != '\0') { if(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') ++ *pv; else if(c >= 'A' && c <= 'Z') ++ *pc; else if(c >= '0' && c<= '9') ++ *pd; else if(c == ' ' || c == '\t') ++ *pw; else ++ *po; ++count; } } 47

Output in Visual C++ 6:

48

Code 9-3: #include <iostream.h> int main() { int x[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int i; for(i = 0; i <=9; i++) cout << i << "\t" << x[i] << "\t" << *(x+i) << "\t" << &x[i] << "\t" << (x+i) << endl; return 0; } Output in Visual C++ 6:

49

Code 9-4: #include <iostream.h> #include <stdlib.h> int main() { int i, n, *x; void sorting(int n, int *x); cout << "How many number to be sorted: "; cin >> n; x = (int *) malloc(n * sizeof(int)); for(i = 0; i < n; i++) { cout << "Number " << i+1 << "\t: "; cin >> *(x + i); } sorting(n, x); for(i = 0; i < n; i++) cout << "Sorted Number " << i+1 << "\t: " << *(x + i) << endl; return 0; } void sorting(int n, int *x) { int i, j, temp; for(i = 0; i < n-1; i++) for(j = i+1; j < n; j++) if(*(x+j) < *(x+i)) { temp = *(x+i); *(x+i) = *(x+j); *(x+j) = temp; } } // x is the address. No need of & like array // x is the addresses like in array

50

Output in Visual C++ 6:

51

Code 9-4: #include <iostream.h> #include <stdlib.h> #include <string.h> void sorting(int n, char *x[]); int main() { int n = 0; char *x[10]; cout << "Enter each string on a separate line." << endl; cout << "Type \"END\" when done." << endl << endl; do { x[n] = (char *)malloc(15 * sizeof(char)); // malloc returns void cout << "String " << n+1 << "\t: "; cin >> x[n]; } while (strcmp(x[n++], "END")); sorting(--n, x); cout << endl <<"Reordered list of strings:" << endl << endl; for(int i = 0; i < n; i++) cout << "String " << i+1 << "\t: " << x[i] << endl; return 0; } void sorting(int n, char *x[]) { char *temp; int i, j; for(i = 0; i < n - 1; i++) for(j = i + 1; j < n; j++) if(strcmp(x[i], x[j]) > 0) { temp = x[i]; x[i] = x[j]; x[j] = temp; } }

52

Output in Visual C++ 6:

53

Code 10-0 // ADD, SUB, MUL, DIV Complex Numbers #include<iostream.h> typedef struct {float r,i;} fcomplex; fcomplex Cadd( fcomplex a, fcomplex b); fcomplex Csub(fcomplex a, fcomplex b); fcomplex Cmul(fcomplex a, fcomplex b); fcomplex Cdiv(fcomplex a, fcomplex b); int main() { fcomplex cnum1, cnum2; char c1, c2; cout << "Enter the first complex number [a+jb]: "; cin >> cnum1.r >> c1 >> c2 >> cnum1.i; if(c1 == '-') cnum1.i = -cnum1.i; cout << "Enter the second complex number [c+jd]: "; cin >> cnum2.r >> c1 >> c2 >> cnum2.i; if(c1 == '-') cnum2.i = -cnum2.i; fcomplex d = Cadd(cnum1, cnum2); fcomplex e = Csub(cnum1, cnum2); fcomplex f = Cmul(cnum1, cnum2); fcomplex g = Cdiv(cnum1, cnum2); c1 = '+'; // c1 may be kept - from above cin if(d.i < 0) { c1 = '-'; d.i = -d.i; } cout << "Sum = " << d.r << c1 << c2 << d.i << endl; c1 = '+'; // c1 may be kept - from above if block if(e.i < 0) { c1 = '-'; e.i = -e.i; } 54

cout << "Sub = " << e.r << c1 << c2 << e.i << endl; c1 = '+'; // c1 may be kept - from above if block if(f.i < 0) { c1 = '-'; f.i = -f.i; } cout << "Mul = " << f.r << c1 << c2 << f.i << endl; c1 = '+'; // c1 may be kept - from above if block if(g.i < 0) { c1 = '-'; g.i = -g.i; } cout << "Div = " << g.r << c1 << c2 << g.i << endl; return 0; } fcomplex Cadd(fcomplex a, fcomplex b) { fcomplex c; c.r = a.r + b.r; c.i = a.i + b.i; return c; } fcomplex Csub(fcomplex a, fcomplex b) { fcomplex c; c.r = a.r - b.r; c.i = a.i - b.i; return c; } fcomplex Cmul(fcomplex a, fcomplex b) { fcomplex c; 55

c.r = a.r * b.r - a.i * b.i; c.i = (a.r * b.i) + (a.i * b.r); return c; } fcomplex Cdiv(fcomplex a, fcomplex b) { fcomplex c, neu, bcon; bcon.r = b.r; bcon.i = -b.i; float den = (b.r*b.r)+(b.i*b.i); neu = Cmul(a, bcon); c.r = neu.r/den; c.i = neu.i/den; return c; } Output in Visual C++ 6:

56

Code 10-1: // Version 1: Using array #include <iostream.h> struct date { int day; int month; int year; }; struct account { char name[100]; char street[100]; char city[20]; int accountNumber; char accountType; float oldBalance; float newBalance; float payment; struct date lastPayment; } customer[100]; /* Alternate way typedef struct { int day; int month; int year; } date; typedef struct { char name[100]; char street[100]; char city[20]; int accountNumber; char accountType; float oldBalance; float newBalance; float payment; date lastPayment; } account; account customer[100]; date lastPayment; 57

*/ int main() { int i, n; void readInput(int i); void writeOutput(int i); cout << "******** CUSTOMER BILLING SYSTEM *********" << endl << endl; cout << "How many customers are there? "; cin >> n; for(i = 0; i < n; i++) { readInput(i); if(customer[i].payment > 0) customer[i].accountType = (customer[i].payment < 0.1*customer[i].oldBalance) ? 'O' : 'C'; else customer[i].accountType = (customer[i].oldBalance > 0) ? 'W' : 'C'; customer[i].newBalance = customer[i].oldBalance - customer[i].payment; } for(i = 0; i < n; i++) writeOutput(i); return 0; } void readInput(int i) { char slash; cout << endl << "Customer No. " << i + 1 << endl; cout << "Name: "; cin >> customer[i].name; cout << "Street: "; cin >> customer[i].street; cout << "City: "; cin >> customer[i].city; cout << "Account Number: "; cin >> customer[i].accountNumber; cout << "Previous balance: "; cin >> customer[i].oldBalance; cout << "Current payment: "; cin >> customer[i].payment; cout << "Payment day (dd/mm/yyyy): "; cin >> customer[i].lastPayment.day >> slash >> customer[i].lastPayment.month >> slash >> customer[i].lastPayment.year; 58

} void writeOutput(int i) { cout << endl << "Name: " << customer[i].name; cout << "\tAccount number: " << customer[i].accountNumber << endl; cout << "Street: " << customer[i].street << endl; cout << "City: " << customer[i].city << endl << endl; cout << "Old balance: " << customer[i].oldBalance << endl; cout << "Current payment: " << customer[i].payment; cout << "\tPayment date: " << customer[i].lastPayment.day << "/" << customer[i].lastPayment.month << "/" << customer[i].lastPayment.year << endl; cout << "New balance: " << customer[i].newBalance << endl << endl; cout << "Account status: "; switch(customer[i].accountType) { case 'C': cout << "CURRENT" << endl; break; case 'O': cout << "OVERDUE" << endl; break; case 'W': cout << "WITHHELD" << endl; break; default: cout << "*** ERORR !!! ***" << endl; } }

Output in Visual C++ 6: 59

60

Code 10-2: // Version 2: Using pointer #include <iostream.h> #include <stdlib.h> typedef struct { int day; int month; int year; } date; typedef struct { char name[100]; char street[100]; char city[20]; int accountNumber; char accountType; float oldBalance; float newBalance; float payment; date lastPayment; } account; account customer, *pc; int main() { int i, n; void readInput(int i); void writeOutput(int i); cout << "******** CUSTOMER BILLING SYSTEM *********" << endl << endl; cout << "How many customers are there? "; cin >> n; pc = &customer; pc = (account *) malloc(n * sizeof(account)); for(i = 0; i < n; i++) { readInput(i); if((pc+i)->payment > 0) (pc+i)->accountType = ((pc+i)->payment < 0.1*(pc+i)->oldBalance) ? 'O' : 'C'; 61

else (pc+i)->accountType = ((pc+i)->oldBalance > 0) ? 'W' : 'C'; (pc+i)->newBalance = (pc+i)->oldBalance - (pc+i)->payment; } for(i = 0; i < n; i++) writeOutput(i); return 0; } void readInput(int i) { char slash; cout << endl << "Customer No. " << i + 1 << endl; cout << "Name: "; cin >> (pc+i)->name; cout << "Street: "; cin >> (pc+i)->street; cout << "City: "; cin >> (pc+i)->city; cout << "Account Number: "; cin >> (pc+i)->accountNumber; cout << "Previous balance: "; cin >> (pc+i)->oldBalance; cout << "Current payment: "; cin >> (pc+i)->payment; cout << "Payment day (dd/mm/yyyy): "; cin >> (pc+i)->lastPayment.day >> slash >> (pc+i)->lastPayment.month >> slash >> (pc+i)>lastPayment.year; } void writeOutput(int i) { cout << endl << "Name: " << (pc+i)->name; cout << "\tAccount number: " << (pc+i)->accountNumber << endl; cout << "Street: " << (pc+i)->street << endl; cout << "City: " << (pc+i)->city << endl << endl; cout << "Old balance: " << (pc+i)->oldBalance << endl; cout << "Current payment: " << (pc+i)->payment; cout << "\tPayment date: " << (pc+i)->lastPayment.day << "/" << (pc+i)->lastPayment.month << "/" << (pc+i)->lastPayment.year << endl; cout << "New balance: " << (pc+i)->newBalance << endl << endl; cout << "Account status: "; switch((pc+i)->accountType) { 62

case 'C': cout << "CURRENT" << endl; break; case 'O': cout << "OVERDUE" << endl; break; case 'W': cout << "WITHHELD" << endl; break; default: cout << "*** ERORR !!! ***" << endl; } }

63

Code 10-3: // file Calendar.cpp // Program Calendar will output a calendar for // any given year. #include <iostream.h> #include <iomanip.h> // ----------------------------------- Constants enum {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; // ---------------------------------- Prototypes void PrintMonth(int, int, int&); void PrintMonthHeader(int, int); int MonthDays(int, int); // ---------------------------------------- main int main() { int year; // calendar year int day; // number of the day of the week int month; // number of the month cout << "Enter year for calendar: "; cin >> year; cout << "Enter day of the week for January 1," << year <<"." << endl; cout << "Enter 0 for Sunday, 1 for Monday,etc.: "; cin >> day; month = JAN; while (month <= DEC) { PrintMonth(month, year, day); cout << endl; month++; } return 0; } // end main // ---------------------------------- PrintMonth void PrintMonth(int month, int year, int& startDay) { int daysInMonth; // number of days in month int day; // day of the week 64

PrintMonthHeader(month, year); daysInMonth = MonthDays(month, year); // output empty days in first line day = 0; while (day < startDay) { cout << " "; day++; } // output days for the month day = 1; while (day <= daysInMonth) { cout << setw(3) << day; startDay++; if (startDay % 7 == 0) // Saturday { cout << endl; startDay = 0; } day++; } cout << endl; } // end PrintMonth // ---------------------------- PrintMonthHeader void PrintMonthHeader(int month, int year) { cout << endl; if (month == JAN) cout << " January " << year << endl << endl; else if (month == FEB) cout << " February " << year << endl << endl; else if (month == MAR) cout << " March " << year << endl << endl; else if (month == APR) cout << " April " << year << endl << endl; else if (month == MAY) cout << " May " << year << endl << endl; else if (month == JUN) cout << " June " << year << endl << endl; 65

else if (month == JUL) cout << " July " << year << endl << endl; else if (month == AUG) cout << " August " << year << endl << endl; else if (month == SEP) cout << " September " << year << endl << endl; else if (month == OCT) cout << " October " << year << endl << endl; else if (month == NOV) cout << " November " << year << endl << endl; else if (month == DEC) cout << " December " << year << endl << endl; cout << " S M T W T F S " << endl; cout << " ------------------- " << endl; } // end PrintMonthHeader // ------------------------------------ MonthDays int MonthDays(int month, int year) { int days; // number of days in the month if (month == JAN || month == MAR || month == MAY || month == JUL || month == AUG || month == OCT || month == DEC) days = 31; else if (month == FEB) { // leap year is a year that is divisible // by 4 but is not divisible by 400, // unless it is divisible by 2000 if ( (year % 4 == 0) && ( (year % 400 != 0) || (year % 2000 == 0) ) ) days = 29; else days = 28; } else days = 30; return days; } // end MonthDays // end of file Calendar.cc 66

Output in Visual C++ 6:

67

Code 11-1: #include <iostream.h> #include <ctype.h> #include <stdio.h> int main() { FILE *ftp; char c; ftp = fopen("sample.txt", "w"); cout << "Enter a line below:" << endl; do putc(toupper(c = getchar()), ftp); while (c != '\n'); fclose(ftp); return 0; } Output in Visual C++ 6:

Output in text file:

68

Code 11-2: #include <iostream.h> #include <stdio.h> int main() { FILE *ftp; char c; ftp = fopen("sample.txt", "r"); if(ftp == NULL) cout << "Can not open file !" << endl; else { cout << "Reading from the file:" << endl; do putchar(c = getc(ftp)); while (c != '\n'); } fclose(ftp); return 0; } Output in Visual C++ 6:

69

Code 11-3: #include <iostream.h> #include <fstream.h> int main() { ifstream inFile; char ch; long totalAlphaChars = 0; inFile.open("payfile.txt"); if (!inFile) return 1; inFile.get(ch); while (inFile) // Read until EOF { cout << ch; // echo input if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) totalAlphaChars++; inFile.get(ch); } cout << endl << "There are " << totalAlphaChars << " characters in the file." << endl << endl; return 0; } Output in Visual C++ 6:

70

Code 12-1: Class and Object, Version 1 #include <iostream.h> class rectangle { float length; float width; float area; public: void getArea(float x, float y); void showData(); }; void rectangle :: getArea(float x, float y) { length = x; width = y; area = length * width; //area = x * y; // length & width have garbage } void rectangle :: showData() { cout << "Length\t: " << length << endl; cout << "Width\t: " << width << endl; cout << "Area\t: " << area << endl; } int main() { rectangle rect1; float length; // Not same as in Class float width; // Not same as in Class cout << "Enter length of rectangle\t: "; cin >> length; cout << "Enter width of rectangle\t: "; cin >> width; rect1.getArea(length, width); rect1.showData(); return 0; }

71

Output in Visual C++ 6:

72

Code 12-1: Class and Object, Version 2 #include <iostream.h> class rectangle { float length; float width; float area; public: void getData(); void getArea(); void showData(); }; void rectangle :: getData() { cout << "Enter length of rectangle\t: "; cin >> length; cout << "Enter width of rectangle\t: "; cin >> width; } void rectangle :: getArea() { area = length * width; } void rectangle :: showData() { cout << "Length\t: " << length << endl; cout << "Width\t: " << width << endl; cout << "Area\t: " << area << endl; } int main() { rectangle rect1; cout<< "THIS IS OBJECT 1:" << endl; rect1.getData(); rect1.getArea(); rect1.showData(); rectangle rect2; cout<< "THIS IS OBJECT 2:" << endl; rect2.getData(); rect2.getArea(); rect2.showData(); 73

return 0; } Output in Visual C++ 6:

74

Code 12-1.3: Class and Object, Version 3 (Constructor and Destructor) #include <iostream.h> class rectangle { float length; float width; float area; public: rectangle(float x, float y) { //cout << "This is CONSTRUCTOR" << endl; length = x; width = y; } /*~rectangle() { cout << "This is DESSTRUCTOR" << endl; }*/ void getArea(); void showData(); }; void rectangle :: getArea() { area = length * width; } void rectangle :: showData() { cout << "Length\t: " << length << endl; cout << "Width\t: " << width << endl; cout << "Area\t: " << area << endl; } int main() { rectangle rect1(15, 10); cout<< "THIS IS OBJECT 1:" << endl; rect1.getArea(); rect1.showData(); rectangle rect2(20, 12); cout<< "THIS IS OBJECT 2:" << endl; rect2.getArea(); rect2.showData(); 75

return 0; } Output in Visual C++ 6: Only Constuctor

Output in Visual C++ 6: Constructor and Destructor

76

Code 12-2: salesp.h file #ifndef SALESP_H #define SALESP_H class SalesPerson { public: SalesPerson(); void getSalesFromUser(); void setSales(int, double); void printAnnualSales(); private: double totalAnnualSales(); double sales[12]; }; #endif salespc.cpp file #include <iostream.h> #include "salesp.h" SalesPerson :: SalesPerson() { for(int i = 0; i < 12; i++) sales[i] = 0.0; } void SalesPerson :: getSalesFromUser() { double salesFigure; for(int i = 1; i <=12; i++) { cout << "Enter sales amount for month " << i << "\t\t: "; cin >> salesFigure; setSales(i, salesFigure); } } void SalesPerson :: setSales(int month, double amount) { if(month >= 1 && month <= 12 && amount > 0) sales[month -1] = amount; else 77

cout << "Invalid month or sales figure!" << endl; } void SalesPerson :: printAnnualSales() { cout << "The total annual sales are\t\t: " << totalAnnualSales() << endl; } double SalesPerson :: totalAnnualSales() { double total = 0.0; for(int i = 0; i <12; i++) total += sales[i]; return total; } salespm.cpp file #include "salesp.h" int main() { SalesPerson s; s.getSalesFromUser(); s.printAnnualSales(); return 0; } Output in Visual C++ 6:

78

Code 12-3: #include<iostream.h> class complex { double x; double y; public: complex () {} complex (double real, double img) { x = real; y = img; } complex operator + (complex c); void display(); }; complex complex :: operator + (complex c) { complex temp; temp.x = x + c.x; temp.y = y + c.y; return (temp); } void complex :: display() { cout << x << " + j" << y << endl; } int main() { complex C1(1.23, 2.34); complex C2(2.13, 3.21); complex C3; C3 = C1 + C2; cout << "C1 = "; C1.display(); cout << "C2 = "; C2.display(); cout << "C3 = "; C3.display(); return 0; }

79

Output in Visual C++ 6:

80

Code 12-4.1: #include <iostream.h> class Base { int a; public: int b; void set_ab(); int get_a(); void show_a(); }; class Derive : public Base { int c; public: void mul(); void display(); }; void Base :: set_ab() { a = 5; b = 10; } int Base :: get_a() { return a; } void Base :: show_a() { cout << "a = " << a << endl << endl; } void Derive :: mul() { c = b * get_a(); } void Derive :: display() { cout << "a = " << get_a() << endl; cout << "b = " << b << endl; cout << "c = " << c << endl << endl; } // Derive class: Can access Base Public data/members.

// b is accessed directly, a through member function.

// a instead of get_a() won't work

81

int main() { Derive d; d.set_ab(); d.show_a(); d.mul(); d.display(); d.b = 20; d.mul(); d.display(); return 0; } Output in Visual C++ 6:

// Object of derive class // Object can directly access public members

82

Code 12-4.2: #include <iostream.h> class Base { int a; public: int b; void set_ab(); int get_a(); void show_a(); }; class Derive : private Base { int c; public: void mul(); void display(); }; void Base :: set_ab() { cout << "Enter a and b:" << endl; cin >> a >> b; } int Base :: get_a() { return a; } void Base :: show_a() { cout << endl << "a = " << a << endl; } void Derive :: mul() { set_ab(); c = b * get_a(); } // Derive class: Can access Base Public data/members.

// b is accessed directly, a through member function.

void Derive :: display() { show_a(); //cout << "a = " << get_a() << endl;// a instead of get_a() won't work cout << "b = " << b << endl; 83

cout << "c = " << c << endl << endl; } int main() { Derive d; //d.set_ab(); //d.show_a(); d.mul(); d.display(); //d.b = 20; d.mul(); d.display(); return 0; } Output in Visual C++ 6:

// Object of derive class // Object cant directly access public members

84

Code 12-4.3: #include <iostream.h> class student { protected: int rollNumber; public: void getNumber(int r) { rollNumber = r; } void putNumber() { cout << "Roll number: " << rollNumber << endl; } }; class test : virtual public student { protected: float part1, part2; public: void getMarks(float x, float y) { part1 = x; part2 = y; } void putMarks() { cout << "Number obtained:" << endl; cout << "\tPart 1: " << part1 << endl; cout << "\tPart 2: " << part2 << endl; } }; class sport : virtual public student { protected: float score; public: void getScore(float s) { score = s; } void putScore() { cout << "Sport weight: " << score << endl; 85

} }; class result : public test, public sport { float total; public: void display(); }; void result :: display() { total = part1 + part2 + score; putNumber(); putMarks(); putScore(); cout << "Total marks: " << total << endl; } int main() { result std1; std1.getNumber(123); std1.getMarks(35.5, 40.0); std1.getScore(6.5); std1.display(); return 0; } Output in Visual C++ 6:

86

Code 12-5.1: #include<iostream.h> class item { int code; float price; public: void getdata(int a, float b) { code = a; price = b; } void showdata() { cout << "Code\t: " << code << endl; cout << "Price\t: " << price << endl; } }; const int size = 2; int main() { item *p = new item[size]; item *d = p; int i, x; float y; for(i = 0; i <size; i++) { cout << "Input code for item " << i+1 << "\t: "; cin >> x; cout << "Input price for item " << i+1 << "\t: "; cin >> y; p -> getdata(x,y); p++; } for(i = 0; i <size; i++) { cout << endl << "Item\t: " << i+1 << endl; d -> showdata(); d++; } return 0; }

87

Output in Visual C++ 6:

88

Code 12-5.2: #include<iostream.h> #include<string.h> class media { protected: char title[100]; float price; public: media(char* s, float a) { strcpy(title, s); price = a; } virtual void getdata(){}; virtual void display(){}; }; class book : public media { int page; public: book(char* s, float a, int p ): media(s, a) { page = p; } void getdata(); void display(); }; class tape : public media { float time; public: tape(char* s, float a, float t ): media(s, a) { time = t; } void getdata(); void display(); }; void book :: getdata() { cout << "Enter BOOK Details" << endl << endl; cout << "Title: "; cin >> title; cout << "Price: "; cin >> price; 89

cout << "Page: "; cin >> page; } void book :: display() { cout << "Display BOOK Details" << endl << endl; cout << "Title: " << title << endl; cout << "Pages: " << page << endl; cout << "Price: " << price << endl << endl; } void tape :: getdata() { cout << endl << "Enter TAPE Details" << endl << endl; cout << "Title: "; cin >> title; cout << "Price: "; cin >> price; cout << "Time: "; cin >> time; } void tape :: display() { cout << "Display TAPE Details" << endl << endl; cout << "Title: " << title << endl; cout << "Time: " << time << endl; cout << "Price: " << price << endl << endl; } int main() { char title[100] = { }; float price = 0.0; float time = 0.0; int page = 0; media* list[2]; book book1(title, price, page); tape tape1(title, price, time); /* book book1(" ", 0.0, 0); tape tape1(" ", 0.0, 0.0); */ list[0] = &book1; list[1] = &tape1; cout << "Get BOOK and TAPE Media Details:" << endl << endl; list[0] -> getdata(); list[1] -> getdata(); cout << endl << "Display BOOK and TAPE Media Details:" << endl << endl; list[0] -> display(); 90

list[1] -> display(); return 0; } Output in Visual C++ 6:

91

Misc 1: /* Method 1 #include <iostream.h> void low2up (char cArray[]); int main() { char cArray[5] = {'a', 'e', 'i', 'o', 'u'}; cout << "Lower case vowels are:"; for(int i = 0; i < 5; i++) cout << "\t" << cArray[i]; low2up(cArray); cout << endl << "Upper case vowels are:"; for(i = 0; i < 5; i++) cout << "\t" << cArray[i]; cout << endl; return 0; } void low2up (char cArray[]) { for(int i = 0; i < 5; i++) cArray[i] = cArray[i] - 'a' + 'A'; } */ // Method 2 #include <iostream.h> char low2up (char c); int main() { char cArray[5] = {'a', 'e', 'i', 'o', 'u'}; cout << "Lower case vowels are:"; for(int i = 0; i < 5; i++) cout << "\t" << cArray[i]; for(i = 0; i < 5; i++) cArray[i] = low2up(cArray[i]); cout << endl << "Upper case vowels are:"; for(i = 0; i < 5; i++) cout << "\t" << cArray[i]; cout << endl; 92

return 0; } char low2up (char c) { c = c - 'a' + 'A'; return c; }

93

You might also like