Wednesday, May 19, 2010

Freezing and Boiling Points - Using Class

File -- > Temperature.h


#pragma once

class Temperature {

    public: // Programmer Interface (programmer can access/use these).

        Temperature (void); // Default constructor.
      
        void setTemperature (int); // Sets the temperature value.
        int getTemperature (void); // Returns the temperature value.
      
        // Returs true if the condition matches or else false.
        bool isEthylFreezing (int);
        bool isEthylBoiling (int);
        bool isOxygenFreezing (int);
        bool isOxygenBoiling (int);
        bool isWaterFreezing (int);
        bool isWaterBoiling (int);    

       ~Temperature (void); // Destructor.

    private: // Data members not accessible by programmer.
        int elementTemp;

};

File --> Temperature.cpp


#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "Temperature.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Define member functions for class Temperature.

Temperature::Temperature (void) {  // Default constructor.
     elementTemp = 0; // Setting temperature defined by class to 0.
}
//---------------------------------------------------------------------------
void Temperature::setTemperature (int programmerInput) {
     elementTemp = programmerInput; // Setting programmer input to class temperature.  
}
//------------------------------------------------------------------------------
int Temperature::getTemperature (void) {
    return elementTemp; // Returning to new value.
}
//------------------------------------------------------------------------------
bool Temperature::isEthylFreezing(int programmerInput) {
     // Checking the input from the programmer is true or false.
     bool Result = false;
     if (programmerInput <= -173) {
          Result = true;
     }
     return Result;  
}
//------------------------------------------------------------------------------
bool Temperature::isEthylBoiling(int programmerInput) {
     bool Result = false;
     if (programmerInput >= 172) {
          Result = true;
     }
     return Result;
}
//------------------------------------------------------------------------------
bool Temperature::isOxygenFreezing(int programmerInput) {
     bool Result = false;
     if (programmerInput <= -362) {
          Result = true;
     }
     return Result;  
}
//------------------------------------------------------------------------------
bool Temperature::isOxygenBoiling(int programmerInput) {
     bool Result = false;
     if (programmerInput >= -306) {
          Result = true;
     }
     return Result;
}
//------------------------------------------------------------------------------
bool Temperature::isWaterFreezing(int programmerInput) {
     bool Result = false;
     if (programmerInput <= 32) {
          Result = true;
     }
     return Result;
}
//------------------------------------------------------------------------------
bool Temperature::isWaterBoiling(int programmerInput) {
     bool Result = false;
     if (programmerInput >= 212) {
          Result = true;
     }
     return Result;
}
//---------------------------------------------------------------------------  
Temperature::~Temperature (void) {  // Destructor.

}
//---------------------------------------------------------------------------

File --> Main.


// Programming Environment: Bloodshed
// Program Description: 
// This is a simple program to demonstrate the use of class. The program asks the
// user to enter a temperature and it displays a list of substance that will 
// freeze at that temperature and those that will boil at that temperature. 
// It uses simple class with default constructor to perform the operation.
//------------------------------------------------------------------------------
// Date/Time: 5/12/2010  12:48:14 AM
//------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "extras.h"
#include "Temperature.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Structure Declarations
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Function Prototypes
//---------------------------------------------------------------------------

bool Do_Again (void);
//---------------------------------------------------------------------------
int main (void) {

    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);


    do {  
          int elementTemperature;
          cout << endl << "FREEZING AND BOILING POINTS OF ELEMENTS";
          cout << endl << "---------------------------------------";
          cout << endl << endl << "Enter TEMPERATURE: ";
          cin >> elementTemperature;
                   
          Temperature Elements; // Creating object of Temperature class.
          // Setting the temperature to user's entered temperature.
          Elements.setTemperature(elementTemperature); 
          
          cout << endl << "----------------------------------------------";
          cout << endl << "Properties of Elements @ " << Elements.getTemperature()
                         << " Degrees Fahrenheit";
          cout << endl << "----------------------------------------------";
          
          // Using if statement to figure out of validity of each methods and 
          // displaying it if it matches the condition.
          if (Elements.isEthylFreezing(elementTemperature)) {
              cout << endl << "ETHYL ALCOHOL WILL FREEZE.";
          }
          if (Elements.isEthylBoiling(elementTemperature)) {
              cout << endl << "ETHYL ALCOHOL WILL BOIL.";
          } 
          if (Elements.isOxygenFreezing(elementTemperature)) {
              cout << endl << "OXYGEN WILL FREEZE.";
          }
          if (Elements.isOxygenBoiling(elementTemperature)) {
              cout << endl << "OXYGEN WILL BOIL.";
          }
          if (Elements.isWaterFreezing(elementTemperature)) {
              cout << endl << "WATER WILL FREEZE.";
          }
          if (Elements.isWaterBoiling(elementTemperature)) {
              cout << endl << "WATER WILL BOIL.";
          }
          
    } while (Do_Again ());
    return 0;
}
//------------------------------------------------------------------------
// Function Definitions
//------------------------------------------------------------------------
bool Do_Again (void) {

    (void) fflush (stdin);
    cout << endl << endl << "\aDo Again? (y/n): ";
    return static_cast(tolower (_getch ())) == 'y';
}

"Car Speed - Using Class"

File ---> "Car.h"

#pragma once

class Car {

    public: // Programmer Interface (programmer can access/use these).
      
        Car (void); // Default constructor.
      
        Car (int, char*, int); // Constructor
        Car (int, char*);  
      
        // Accesors
        int getYearmodel(void) const;
        char* getMake (void) const;
        int getSpeed (void) const;
      
        void accelerate (void); // accelerate() method
        void brake (void); // brake() method

       ~Car (void); // Destructor.

    private: // Data members not accessible by programmer.
        int yearModel;
        char* Make;
        int Speed;

};



File ---> "Car.cpp"

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "Car.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------
const int MAKE_SIZE = 20; // Defining Max size for make of the car.
const int MAX_SPEED = 140;
//---------------------------------------------------------------------------
// Define member functions for class Car.

Car::Car (void) {  // Default constructor. Assigning zero to all.
         yearModel = 0; 
         Make = new char [MAKE_SIZE];
         *Make = '\0'; 
         Speed = 0;        
}

Car::Car(int year, char* car_name, int speed) { // Constructor taking 3-parameters.
         yearModel = year;
         Make = new char [strlen(car_name) + 1];
         strcpy (Make, car_name);
         Speed = speed;                      
}

Car::Car(int year, char* car_name) {
         yearModel = year;
         Make = new char [strlen(car_name) + 1];
         strcpy(Make, car_name);
         Speed = 0;

int Car::getYearmodel(void) const { // Returns year of car.
        return yearModel;    
}

char* Car::getMake(void) const {  // Return make of car.      
        return Make;
}

int Car::getSpeed(void) const { // Return speed of car
         return Speed;
}

void Car::accelerate(void) { // Adds 5 to speed variable.
         Speed += 5; 
         if (Speed > MAX_SPEED) {
             Speed = MAX_SPEED;  
         }
}

void Car::brake(void) { // Subtracts 5 to speed variable.
         Speed -= 5;
         if (Speed < 0) {
             Speed = 0;
         }
}
//---------------------------------------------------------------------------
Car::~Car (void) {  // Destructor.
delete [] Make;
}
//---------------------------------------------------------------------------

File --> Main



//------------------------------------------------------------------------------
// Date/Time: 5/3/2010  11:53:09 AM
//------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "extras.h"
#include "Car.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------
const int CAR_SIZE = 20; // Defining Max size for make of the car.
//---------------------------------------------------------------------------
// Structure Declarations
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Function Prototypes
//---------------------------------------------------------------------------

bool Do_Again (void);
//---------------------------------------------------------------------------
int main (void) {

    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);

    do {        
        char typeCar[CAR_SIZE]; // Character Array.
        int yearCar; // Integer variable.
        int speedCar;
        int userInput = 0;
        char userResponse;
      
        cout << endl << endl << "Simple Mechanics";
        cout << endl << "----------------";
        cout << endl << "Enter Car Type: ";
        cin.getline(typeCar, CAR_SIZE); // Getting car type in an array.
      
        cout << endl << "Enter Car Year: ";
        cin >> yearCar; // Getting year of the car.
      
        cout << endl << "Enter Car Speed: ";
        cin >> speedCar; // Getting Speed of the car.
        while (speedCar < 0) {
              // Unless the user types valid speed it prompts the user to type in
              // the speed of car in infinite loop.
              cout << endl << "Invalid Car Speed :: Enter Positive Car Speed: ";
              cin >> speedCar;
        }
      
        Car CarObject(yearCar, typeCar, speedCar);
        // Creating the object of a Car Class.
      
        cout << endl << "Do you want to increase the speed of your car? " << endl;
        cout << "Press Y or y to increse you speed or PRESS ANY KEY not to...."
             << endl;
        cin >> userResponse;
      
        while (userResponse == 'y' || userResponse == 'Y') {
                    if (userInput >= 0 || userInput <= 100) {
                    cout << endl << "How many times you want to accelarate you car?" << endl;      
                    cin >> userInput;
                    for (int i = 0; i < userInput; ++i) {
                        CarObject.accelerate();
                    }
                    // Displaying the Current speed of the car after acceleration.
                    cout << endl << "Current Speed :: After Acceleration: "
                         << CarObject.getSpeed() << " Miles/Hr";
                    cout << endl << endl << "Do you want to increase the speed of your car?";
                    cout << endl << "Press Y or y to increse you speed or PRESS ANY KEY...." << endl;
                    cin >> userResponse;
              }          
        }    
        cout << endl << "Do you want to use the BREAK? " << endl;
        cout << "Press Y or y to use the BREAK or PRESS ANY KEY not to...."
             << endl;
        cin >> userResponse;
      
        while (userResponse == 'y' || userResponse == 'Y') {
                    if (userInput >= 0 || userInput <= 100) {
                    cout << endl << "How many times you want to use BREAK?" << endl;      
                    cin >> userInput;
                    for (int i = 0; i < userInput; ++i) {
                        CarObject.brake();
                    }
                    // Displaying the Current speed of the car after acceleration.
                    cout << endl << "Current Speed :: After BREAK Applied: "
                         << CarObject.getSpeed() << " Miles/Hr";
                    cout << endl << endl << "Do you want to use the BREAK?";
                    cout << endl << "Press Y or y to use the BREAK or PRESS ANY KEY not to...." << endl;
                    cin >> userResponse;
              }    
          
        }
            
        cout << endl << endl << "Vehicle Information!";
        cout << endl <<  "--------------------";
        // Displaying Car Information typed by user.
        cout << endl << "CAR TYPE: " << CarObject.getMake();
        cout << endl << "CAR YEAR: " << CarObject.getYearmodel();
        cout << endl << "CURRENT CAR SPEED: " << CarObject.getSpeed() << " Miles/Hr";    

    } while (Do_Again ());
    return 0;
}
//------------------------------------------------------------------------
// Function Definitions
//------------------------------------------------------------------------
bool Do_Again (void) {

    (void) fflush (stdin);
    cout << endl << endl << "\aDo Again? (y/n): ";
    return static_cast(tolower (_getch ())) == 'y';
}

Advertisement: 

Contact us for Software Development, AI, and SEO Marketing - I Code Mind LLC

Drink Machine Simulator

// Programming Environment: Bloodshed
// Program Description:
// This program uses struct to create structure of data so that we could use it
// for efficient programming experience. It creates an array of five structures
// with drink name, drink cost and number in machine. It lists the number of
// drinks, its costs and type of drink. The user is allowed to either pick a
// drink or leave the program by pressing any key except for the keys assigned
// for the respective drinks. The program takes amount from user for particular
// drink and then gives the output to the user about their change or informs user
// if the fund is insufficient. It only accepts amount >= zero and Less than
// equal to one. If the drinks are sold out then the user is informed to select
// other available drinks and can't choose sold out drinks. The program is designed
// to serve more than one transaction by one user untill they want to quit the
// program. Finally, the user is informed the updated result of all the transaction
// including the amount of money the machine earned from the user.        
//------------------------------------------------------------------------------        
// Date/Time: 4/29/2010  5:17:39 AM
//------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "extras.h"
#include "Generic_Class.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------
const int DRINK_SIZE = 27;
const int NUM_DRINKS = 5; // Valid for 5 drinks.
const char INPUT_PATH_FILE[] =
    "C:\\c++ 242\\Assignments\\assignment4\\drink_machine_input.txt";
//---------------------------------------------------------------------------
// Structure Declarations
//---------------------------------------------------------------------------
struct Drink_Structure {
       // Creating structure of Drink_Name, Cost and Quantity.
       char Drink_Name[DRINK_SIZE];
       double Cost;
       int Quantity;
       };
//---------------------------------------------------------------------------
// Function Prototypes
//---------------------------------------------------------------------------
void Simulator(Drink_Structure[], int);

bool Do_Again (void);
//---------------------------------------------------------------------------
int main (void) {

    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);

    do {
    ifstream InFile; // Input file stream.
    InFile.open (INPUT_PATH_FILE); // Opening the file.
    if (InFile) { // Performing operations if the input file is open.
        // Input file opened successfully.              
        Drink_Structure machine[NUM_DRINKS];
        //Creating an array of Drink_Structure type with NUM_DRINKS number
        // of structures        
        int index = 0;      
        while (InFile >> machine[index].Drink_Name >> machine[index].Cost
                      >> machine[index].Quantity) {
    // Replace underscore characters in drink name with spaces.
               for (int i = 0; i < strlen (machine[index].Drink_Name); ++i) {
                   if (machine[index].Drink_Name[i] == '_') {
                       machine[index].Drink_Name[i] = ' ';
                   }    
               }
               if (++index == NUM_DRINKS) {
               // if increasing index value reaches NUM_DRINKS then it breaks
               // out of the loop.
               break;    
               }    
        }        
        InFile.close();      
        Simulator(machine, NUM_DRINKS);
        // Calling the function to simulate the tasks.    
    
        } else {
        cout << endl << "\a Error::Cannot Open Input File";
        // Displays error if the program can't open the input file.    
    }
  
    } while (Do_Again ());
    return 0;
}
//------------------------------------------------------------------------
// Function Definitions
//------------------------------------------------------------------------
bool Do_Again (void) {

    (void) fflush (stdin);
    cout << endl << endl << "\aDo Again? (y/n): ";
    return static_cast(tolower (_getch ())) == 'y';
}

void Simulator(Drink_Structure Machine[], int numDrinks) {
     // This function defination takes the input from the user on which drink they
     // like to drink and gives the change or asks for additional amount if insufficient.
     // If the user chooses to quit the program then it displays the updated
     // situation of the number of drinks in the machine and the amount of money
     // earned by the machine.
     char choice; // Choice as 1 to 5 drinks user want to have.
     double amountInserted = 0.0; // Amount of money user enters at first.
     double changeAmount = 0.0; // Amount of money user gets back or is in need.
     double totalSales = 0.0; // Total sales amount for the machine.
  
     do {
         // Displaying the Drink Machine information.
     cout << endl << endl << "Welcome to College Vending Machine Simulator!";
     cout << endl << "---------------------------------------------" << endl;
     cout << endl << "Options\t" << "Drink Name\t" << "Cost\t" << "Number in Machine";
     cout << endl << "-------\t" << "----------\t" << "----\t" << "-----------------";
     for (int j = 0; j < numDrinks; ++j) {
         cout << endl << setw (4) << char (j + 49) << "\t" << Machine[j].Drink_Name
              << "\t" << Machine[j].Cost << setw (13) << Machine[j].Quantity;
     }
  
     cout << endl << endl << "Enter Drink Option or PRESS ANY KEY to QUIT: ";
     cin >> choice;  
  
     if (choice >= '1' && choice <= '5') {
     // If the choice is in between 1 to 5 then the following code executes.
              
        while (Machine[choice - 49].Quantity == 0) { // If drink number is "0".
              cout << endl << "Oops.....Sold Out!! ";
              cout << endl << endl << "Enter other DRINK OPTIONS except, "
                   << Machine[choice - 49].Drink_Name << ": ";
              cin >> choice; // User is forced to choose drinks except the one
              // which is already sold out.          
        }
      
        cout << endl << "INSERT Amount of Money FOR "
             << Machine[choice - 49].Drink_Name << ": " ;
        cin >> amountInserted; // User's input.
        while (amountInserted < 0 || amountInserted > 1) {
              // Validating input.
              cout << endl << "INVALID AMOUNT!" << endl
                   << "INSERT Amount > $0 or <= $1: ";
              cin >> amountInserted;            
        }
            
        changeAmount = amountInserted - Machine[choice - 49].Cost;
        // Calculation change amount.      
        while (changeAmount < 0.0) {
              // If change amount is negative perform the following.
              cout << endl << "Insufficient Fund!!" << endl << "You are Short:  "
                   << "$" << fabs (changeAmount);
              cout << endl << "Please INSERT this short fund: ";
              cin >> amountInserted;
                  while (amountInserted < 0.0 || amountInserted > 1.0) {
                          // Again validating the input.
                    cout << endl << "Invalid Amount" << endl
                         << "INSERT Amount > $0 or <= $1: ";
                    cin >> amountInserted;
                  }
                  changeAmount = changeAmount + amountInserted;                              
        }
        cout << endl << "Your Change: " << "$" << changeAmount;
        // Displaying the change amount.
        totalSales += Machine[choice - 49].Cost;
        // Calculating the total sales.
        --Machine[choice - 49].Quantity;
        // Decreasing the number of drinks in machine.      
      }      
     }      
     while (choice >= '1' && choice <= '5');
      
        // After the user selects to QUIT the program, displaying the changes
        // in drink_structure called as machine.
        cout << endl << endl << "CLOSING TRANSACTIONS............";
        cout << endl << endl << "Remaining Drinks in College Vending Machine Simulator!";
        cout << endl << "------------------------------------------------------"
             << endl;
        cout << endl << "Drink Name\t" << "Cost\t" << "Number in Machine";
        cout << endl << "----------\t" << "----\t" << "-----------------";
        for (int j = 0; j < numDrinks; ++j) {
            cout << endl << Machine[j].Drink_Name
                 << "\t" << Machine[j].Cost << setw (13) << Machine[j].Quantity;
        }
        cout << endl << "\nTotal Amount of Sales: " << "$" << totalSales;
        // Displaying the total amount of sales done by soft drink machin.    
}

The input file "drink_machine_input.txt" looks like this,
Coca_Cola    0.75  0
Root_Beer    0.75  20
Lemon_Lime   0.75  20
Grape_Soda   0.80  2
Cream_Soda   0.80  20

Tuesday, May 18, 2010

Phone Number List

// Programming Environment: Bloodshed
// Program Description:
   // This program asks the user to input the name or partial name and it
   // searches the database in a file to give the user with the record that
   // contains some or all of the records that was matched during the search
   // process. It takes input from a file and transfers the information to an
   // array and performs its search operation using a function. This function
   // basically converts both the user input and the input from the file to
   // lower case so that it wouldn't have an effect on the search. When the
   // search actually find the records then it again displayes the record that
   // was not converted to lowercase. Hence, it uses smart techniques to search
   // the names and its corresponding phone numbers to act as a Phone Diary.
//------------------------------------------------------------------------------        
// Date/Time: 4/12/2010  2:42:29 AM
//------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "extras.h"
#include "Generic_Class.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------
const int NAME_SIZE = 50; // Setting name size for user input.
const char INPUT_PATH_FILE[] =
    "C:\\c++ 242\\Assignments\\assignment3\\assign3_with_functions\\phone_num.txt";
    // Path for the database to be accessed by the programmer.
const int LENGTH = 256; // Setting database record limit to 256 records.
const int WIDTH = 50; // Setting each record length limit 50.
//---------------------------------------------------------------------------
// Structure Declarations
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Function Prototypes
//---------------------------------------------------------------------------
void SearchList(char[][WIDTH], int, char[]); // To Search name out of database.
bool Search_Again (void);
//---------------------------------------------------------------------------
int main (void) {

    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);

    do {  
  
    char name [NAME_SIZE];
    cout << endl << endl << "PHONE DIARY Ver. 1.3";
    cout << endl << endl << "Search: ";
    cin.getline (name, NAME_SIZE); // Getting the input from the user.
    for (int j = 0; j < strlen (name); ++j) {
        name[j] = tolower (name[j]); // Converting input from user to lower case.
    }
        
    ifstream InFile; // Input file stream.
    InFile.open (INPUT_PATH_FILE); // Opening the file.
    if (InFile) { // Performing operations if the input file is open.
        // Input file opened successfully.      
        char people_information[LENGTH][WIDTH]; // Creating 2-D Array.            
        int count = 0;
        // Creating integer variable so that we could store the number of
        // records there are in our file. If the user inputs more data to the
        // file then we could keep track of how many records are there in our file.                
        while(InFile.getline(people_information[count], WIDTH)) {
            // Reading records in file till the end of the file.        
            ++ count; // Counting the records.                          
        }        
        InFile.close();
        // Closing the file as we have already transfered the records from file
        // to 2-D Array called people_information[][].
      
        cout << endl << "Database Contains " << count  << " Records!!" << endl;
        cout << "------------------------------" << endl << endl;;
        // Informing user the number of records that the notepad file contains!  
      
        SearchList(people_information, count, name);
        // Invoking the function SearchList() to search the name or partial name
        // to get the full name or the phone number out of the database in
        // notepad file.    
                  
    } else {
        cout << endl << "\aCannot Open Input File";    
    }
      
} while (Search_Again ());
    return 0;
}
//------------------------------------------------------------------------
// Function Definitions
//------------------------------------------------------------------------
bool Search_Again (void) {

    (void) fflush (stdin);
    cout << endl << endl << "\aSearch Again? (y/n): ";
    return static_cast(tolower (_getch ())) == 'y';
}

void SearchList(char people_information[][WIDTH], int count, char name[]){
     // This funtion defination takes the information stored in array called
     // people_information[], copies it to a duplicate array called
     // Duplicate_Array[] by converting it to lower case so that when user
     // performs search operation then it won't affect whether they enter lower
     // case or upper case name or partial name.
  
     char Duplicate_Array[LENGTH][WIDTH]; // Creating Duplicate Array.              
     for (int i = 0; i < count; ++i) {
         // Performs loop for number of records we have in our database. If the
         // database is updated and user adds another record in the phone book
         // then this loop would update itself to loop that many times.
         strcpy(Duplicate_Array[i], people_information[i]);
         // Copies all the information from array people_information[] to
         // Duplicate_Array[].                          
         for (int j = 0; j < count; ++j) {
             // Converts the elements of Duplicate_Array[][] to lower case
             // First it converts all the elements of row 1  to lower case and
             // so on  untill it reaches the last records of the array.                                                          
             Duplicate_Array[i][j] = tolower(Duplicate_Array[i][j]);          
         }
     }
              
     bool found = false; // Setting found as false.
     char* strptr; // Creating a character pointer.
     for (int i = 0; i < count; ++i) {  
         // Searches the whole record to find the match.
         strptr = strstr(Duplicate_Array[i], name);
         // Points to the address where the name is matched to the user input.        
         if(strptr) {
              // If the strptr is true then it displays the record that is found.
              // Hence, we now only write people_information[i] so that only that
              // record is displayed and the original record that is not
              // converted to lower case is displayed.
              cout << endl << "Found: " << people_information[i] << endl;      
              found = true; // Setting found as true as we find record.        
         }
     }
          
     if(!found) {
         // If the record is not found then bool variable is set to false and
         // if its true then we inform the user that the record in not found.
         cout << endl << "Data Not Found!!";
         cout << endl << "Add This Data In File Named Phone_Num.txt";
     }
     delete strptr;
     // Deleting the strptr pointer as it has no use now at this
     // point of the program.
}




This is the text file named "phone_num.txt" looks like,

Becky Warren, 555-1223
Joe Looney, 555-0097
Geri Palmer, 555-8787
Lynn Presnell, 555-1212
Holly Gaddis, 555-8878
Sam Wiggins, 555-0998
Bob Kain, 555-8712
Tim Haynes, 5557676
Warren Gaddis, 555-9037
Jean James, 555-4939
Ron Palmer, 555-2783
Praj Shrestha, 720-233-2603
James Bond, 777-888-7777
Raj, 232-232-2442
Ram, 3234232
James Bond, 777-777-7777
Collen Farrel, 720-234-6421
Winnona Raider, 303-223-1023
Ujjwal Shrestha, 302-332-1234

Thursday, April 22, 2010

Programming Puzzle



1. Declare a double variable named Velocity and a pointer variable named PtrVelocity, and make PtrVelocity refer (point) to variable Velocity.

double Velocity;
double *PtrVelocity;
PtrVelocity = &Velocity;


2. Given this definition: int X_Array[] = {10, 20, 30, 40, 50, 60, 70, 80}; 
What is the meaning or, if applicable, the value of:

a. X_Array 
The address of the first element of the X_Array[] which holds 10 in our case.


b. X_Array + 2 
The address of the third element of the X_Array[] which holds 30 in our case.


c. *X_Array
Since an array is a pointer in itself, *X_Array gives us the value of the first element of the X_Array[] and the value is 10.



d. *X_Array + 2
Since an array is a pointer in itself, *X_Array + 2 adds the value of the first element of the X_Array[] + 2 Hence, the value is 12.



e. *(X_Array + 2)
Since an array is a pointer in itself, *(X_Array + 2) gives us the value of third element of the X_Array[] which is 30 because it is the value in the position that is two bytes ahead of where X_Array starts.





3. A program contains the following declarations and statements.

char u;
char v = 'A';
char* pu;
char* pv = &v;

*pv = v + 1;

u = *pv + 1;

pu = &u;

If the address of u is 5000 and the address of v is 5001, then (next page):


Columbia College - Aurora Campus
CISS 242 Midterm Exam

(a) [2] What value is stored at &v?        _5001 ________


(b) [2] What value is assigned to pv?      _5001_________


(c) [2] What value is represented by *pv?  _65  _________


(d) [2] What value is assigned to u?       _66___________


(e) [2] What value is stored at &u?        _5000_________


(f) [2] What value is assigned to pu?      _5000_________


(g) [2] What value is represented by *pu?  _66___________



4. Write a C-string function named strrev that uses exclusively pointer notation and reverses the elements of a given string. As is the convention of most C-string functions, have your function return the address of the given string.

int strrev (char*);

int strrev (char* str) {
   char* p = str + strlen (str) – 1;
   while (p >= str) {
      cout << *p;
      --p;
   }
   return &str;
}
  


CISS 242 Midterm Exam


5. Write a C-string function named strsum that uses exclusively pointer notation and calculates and returns the sum of the ASCII values of all characters in a given string.


int strsum(char*);

int strsum(char* str)
{
     int num = 0;
     int sum = 0;
     while (str[num] != '\0') {    
         sum += str[num];      
         ++num;
     }
     return sum;
}



6. Write a C-string function named strsumd that uses exclusively pointer notation and calculates and returns the sum of digits embedded within a given string. For example, if the given string were “ab2c38d4e27fg” then the sum would be 26 since 2 + 3 + 8 + 4 + 2 + 7 = 26. (Note: A more difficult function would be to calculate and return the sum of embedded numerical substrings; i.e., for the example given, the sum would be 71 since 2 + 38 + 4 + 27 = 71. Are there any takers for some extra credit?)


int strsumd (char*);

int strsumd (char* str) {
   int sum = 0;
   char* p = str;
   while (*p) {
      if (isdigit (*p)) {
         sum = sum + *p – ‘0’;
      }
   ++p;
   }
   return sum;


7. A challenging “fill-in-the-blanks” take-home problem (next/last page):
MEMORY LOCATIONS - Byte Addresses Shown: Hex Value (Decimal Value)

// Fill in the bits according to the declarations at the bottom.

0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 1 0 1 1 1
0 (0)             1 (1)             2 (2)             3 (3)

1 1 1 1 1 1 1 1   1 1 1 1 1 1 1 1   1 1 1 1 1 1 1 1   1 0 1 0 1 0 1 1
4 (4)             5 (5)             6 (6)             7 (7)

0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0
8 (8)             9 (9)             A (10)            B (11)

0 1 0 0 0 0 1 0   1 0 0 0 0 0 1 0   1 1 1 1 0 1 0 1   1 1 0 0 0 0 1 1
C (12)            D (13)            E (14)            F (15)

1 1 0 0 0 0 0 0   0 0 1 1 1 0 1 1   0 1 1 0 0 0 1 1   1 1 0 1 0 1 1 1
10 (16)           11 (17)           12 (18)           13 (19)

0 0 0 0 1 0 1 0   0 0 1 1 1 1 0 1   0 1 1 1 0 0 0 0   1 0 1 0 0 0 1 1
14 (20)           15 (21)           16 (22)           17 (23)

0 0 1 1 1 1 1 1   0 1 1 1 0 0 1 0   0 1 0 1 0 0 1 0   0 1 0 1 0 0 1 0
18 (24)           19 (25)           1A (26)           1B (27)

0 1 1 0 1 1 1 1   0 1 1 0 1 1 1 0   0 0 0 0 0 0 0 0   0 1 0 0 1 0 0 0
1C (28)           1D (29)           1E (30)           1F (31)

0 1 1 0 0 0 0 1   0 1 1 1 0 0 1 0   0 1 1 1 0 1 0 0   0 0 0 0 0 0 0 0
20 (32)           21 (33)           22 (34)           23 (35)

0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 1 0 0
24 (36)           25 (37)           26 (38)           27 (39)

0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 1 1 0 0
28 (40)           29 (41)           2A (42)           2B (43)

0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 1 1 1 1 1
2C (44)           2D (45)           2E (46)           2F (47)

0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 1 0 1 1 0 0
30 (48)           31 (49)           32 (50)           33 (51)

_ _ _ _ _ _ _ _   _ _ _ _ _ _ _ _   _ _ _ _ _ _ _ _   _ _ _ _ _ _ _ _
34 (52)           35 (53)           36 (54)           37 (55)

      int Index = 23, Value = -85; // sizeof(int) is 4; 2s-complement for
      long FlightSeconds = 0L;     //                   negative integers.   
      float Velocity = 65.48; // sizeof(float) is 4; this already done.
      double Temp = -27.39; // sizeof(double) is 8; this already done too.
      char Ch = '?', Letter1 = 'r', Letter2 = 'R';
      char FirstName[] = "Ron";   // How many bytes?
      char LastName[]  = "Hart";  // How many bytes?
      int* Valueptr = &Value; // Use 4 bytes for pointer variables.
      float* VelocityPoint = &Velocity;
      char* ByteAddr = LastName;
      char** PointToPoint = &ByteAddr;

Monday, April 12, 2010

Pointer Puzzle



//----------------------
// Variable Definitions
//----------------------

int* pi;
int* pj;
int* pk;

int t;

double* pd;

//-----------------
// Some Statements
//-----------------

*pd += static_cast(*pi);

pi = &t;

*pi = *pk;

pj = pi;

*pj /= 3;

++pj;

++*pj;

//-----------------------------------------------------------------------------
// Assuming the following initial configuration of memory (on the left side),
// what is the resulting configuration of memory (on the right side) after the
// above statements execute?
//-----------------------------------------------------------------------------

                   BEFORE             AFTER

                 __________         __________
                |                        |       |                    |
       1100 |     9                 |       |          9        |
                |__________|       |__________|

                 __________         __________
                |                      |        |                      |
pi     1300|   1100           |        |    1350          |
                |__________|        |__________|

                 __________         __________
                |                       |       |                    |
t      1350 |    14              |       |       2            |
                |__________|       |__________|
                |                      |       |                     |
                |    20              |       |   21              |
                |__________|       |__________|

                 __________         __________
                |                      |        |                      |
pj     1380|   1100           |        |   1354           |
                |__________|       |__________|

                 __________         __________
                |                      |         |                      |
pk    1400|   1410           |         | 1410             |
                |__________|       |__________|

                 __________         __________
                |                      |        |                      |
       1410 |              7      |        |     7               |
                |__________|       |__________|

                 ____________________         ___________________
                |                                                |      |                                        |
       1430 |        0.0                                   |      |     9.0                              |
                |____________________|       |___________________|

                 __________         __________
                |                      |         |                      |
pd    1440|   1430           |         |1430              |
                |__________|        |__________|






Sunday, April 11, 2010

Movie Statistics

// Programming Environment: Bloodshed
// Professor: Ronald J Hart
// Program Description: This program can be used to gather the statical data
// about the number of movies college students see in a month. The program
// asks the user on how many students were survayed and then taking that integer
// value, it dynamically allocates memory as directed by user as an array of
// that many elements (integers). It also validates the user input limiting
// them to enter negative values. It uses a seperate function to display what
// the user has input for each student's movie watch behaviour. Then, it uses
// a seperate function (with pointer as an argument to it) to calculate the
// average, median, and mode of the values entered.
// Date/Time: 4/2/2010  6:51:27 AM
//------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "extras.h"
#include "Generic_Class.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Structure Declarations
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Function Prototypes
double Get_Average(int*, int);
void Display_Array(int*, int);
double Get_Median (int*, int);
void Sort_Array (int*, int);
int Get_Mode (int*, int);
//---------------------------------------------------------------------------

bool Do_Again (void);
//---------------------------------------------------------------------------
int main (void) {

    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);
        
    do {
  
    int num_students = 0;  
    while (num_students <= 0) {
    cout << endl << "Enter the number of students survayed: ";
    cin >> num_students;
    }
    // Dynamically allocating  pointer named student_array that holds
    // num_students.
    int* student_array = new int[num_students];  
    for(int i = 0; i < num_students; ++i) {
         // Now storing the values in the student_array.
         cout << endl << "Enter the number of movies seen by student " << i+1
                      << " : ";
         cin >> student_array[i];
         while (student_array[i] < 0) {
         // Validating the user's input to student array for non-zero entries.
         cout << endl << "Invalid Entry!!"
                      << "Re-enter the number of movies seen by student " << i+1
                      << " : ";
         cin >> student_array[i];
         }        
    }
    cout << endl;
  
    Display_Array(student_array, num_students);
    // This function displays the contents of the student_array.  
    double average = Get_Average(student_array, num_students);
    // Average variable gets average from Get_Average function.
    cout << endl << "The average number of movies college students see per month: "
         << average; // Displays the Average.      
      
    Sort_Array(student_array, num_students);
    // Sorting the elements of student_array as we need the sorted array to
    // calculate the median of the of the elements in the array.
    cout << endl << endl << "The number of movies seen by each students (Sorted): ";
    for (int i = 0; i < num_students; ++i) {
        // Displaying the sorted array elements just for the shake of
        // information to the users.
        cout << student_array[i] << " ";
    }
    // The median variable gets the median from Get_Median().  
    double median = Get_Median(student_array, num_students);
    cout << endl << "The median of number of movies college students see per month: "
         << median; // displays the median.
  
    // The variable mode gets the mode from Get_Mode().
    int Mode = Get_Mode (student_array, num_students);
    // If it finds the mode then it will display the mode else it would disply
    // that the mode doesn't exists.
if (Mode > 0) {
    cout << endl << "The Mode of number of movies college students see per month: " << Mode;
} else {
         cout << endl << "No Mode Exists";
}

    } while (Do_Again ());
    return 0;
}
//------------------------------------------------------------------------
// Function Definitions

double Get_Average(int* array_num_movies, int student_num) {
       // This function calculates the average number of movies that the students
       // saw by returning a double to main which is the average number of movies
       // that the student who were survayed and stored in array saw.
       double average_num_movies = 0.0;
       for (int i = 0; i < student_num; ++i) {
           average_num_movies += array_num_movies[i];    
       }
       average_num_movies /=  student_num;
       return average_num_movies;
       }

void Display_Array(int* dynamic_array, int num_elements) {
     // This function uses the definations to display the contents of the array
     // loaded dynamically.
     cout << endl << "The number of movies seen by each students: ";
     for(int i = 0; i < num_elements; ++i) {
            cout << dynamic_array[i] << " ";
    }
}
 
double Get_Median (int* in_array, int num_elements) {
    // This function definations returns the median to main. If the num_elements is greater
    // than 1 then it sorts the array so that it could give median for odd as well
    // as even num_elements.
    double median;

if (num_elements > 1) {
Sort_Array (in_array, num_elements);
}
if (num_elements % 2 == 1) {
        // Odd number of elements.
median = static_cast(in_array[num_elements/2]);
} else {
// Even number of elements.
median = (in_array[num_elements/2 - 1] +
in_array[num_elements/2]) / 2.0;
}
    return median;
}

void Sort_Array (int* in_array, int num_elements) {
     // This function definations would sort the array for further calculations
     int temp;
     bool swapped = true;
     while(swapped) {
          swapped = false;
          for (int i = 0; i < num_elements; ++i) {
              if (in_array[i] > in_array[i + 1]) {
                   temp = in_array[i];
                   in_array[i] = in_array[i + 1];
                   in_array[i + 1] = temp;
                   swapped = true;                
              }
          }  
     }
}

int Get_Mode (int* in_array, int num_elements) {

// Function receives two parameters: first is the address
// on an integer array; second is the number of elements
// in the given array. This function returns the statistical
// mode of the given array of integers. (Note: We assume
// either one mode value exists or not; i.e., bi-modal and
// multi-modal situations are not considered.)

   int frequency;
   int greatest_frequency = 0;
   int mode;

   for (int i = 0; i < num_elements; ++i) { // For each array element...
    frequency = 0;
  for (int j = 0; j < num_elements; ++j) {
  if (in_array[i] == in_array[j]) {
               ++frequency;
  }
  }
  if (frequency > greatest_frequency) {
  greatest_frequency = frequency;
  mode = in_array[i];
  }
   }
   if (greatest_frequency == 1) {
       mode = -1;
   }
   return mode;
}

//------------------------------------------------------------------------
bool Do_Again (void) {

    (void) fflush (stdin);
    cout << endl << endl << "\aDo Again? (y/n): ";
    return static_cast(tolower (_getch ())) == 'y';
}