Wednesday, May 19, 2010

Addition and Subtraction; sounds easy? Its not.

PROBLEM: ADDITION USING CHARACTER ARRAY OF ANY LENGTH.

Summery: 

This program uses Adder Class to do the addition operation. It accepts the character from user and manipulates the character using ASCII to convert it to numeric and perform the addition operation and again gives out the equivalent output in characters. This program can add two numbers of any sizes. The Joe Programmer enjoys the facility of object, as he can use the class's public method called Adjust_Addends_Size() and type in any number in the parenthesis to get the sum of that many numbered Addends. This is done by dynamically allocating the memory space by the class Adder. Hence, when a Joe Programmer creates an object of the class then they can just call this method to set the addends for sum. The additions of two 20-digit numbers are performed using the default constructor as well as the constructor which takes two arguments. Using the default constructor, we have to set the addends by calling setAddent_1() and  setAddend_2() methods. The object is initiated for the class in a different manner than for the constructor which accepts two arguments. For the constructor, we don't need to set the addends as it is already done in the constructor itself. Hence, this program uses the class and its objects to get the sum of any number of addends very smartly.

Solution: Adder.h

#pragma once

class Adder {

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

    Adder (void); // Default constructor.
    Adder (char* , char*); // Constructor
    
    void setAddend_1 (char*);
    void setAddend_2 (char*);
    
    void getSum (char*); // To get the sum.
    
    // To display.
    void displayAddend_1(char*);
    void displayAddend_2(char*);
    
    void setZero(); // To set zero to the addends.
    void Adjust_Addends_Size(int); // Dynammic Allocation of memory as programmer
    // requests.
    void toNumericChar(char *); // Convert any non numeric characters to Zero.    
    
    ~Adder (void); // Destructor.   
    

    private: // Data members not accessible by programmer.
    char* Addend_1; // Addend one.
    char* Addend_2; // Addend Two.
    char* Sum; // Sum.
    int maxSize; // Maximum size allowed.
};


Solution: Adder.cpp

#include
#include iostream
#include iomanip
#include cctype
#include cstring
#include fstream
#include cmath
#include ctime
#include cstdlib
#include utility
#include conio.h
#include "Adder.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------
const int MAX = 20; // Maximum number of Addends.
const int MIN = 2; // Minimun number of Addends.
const int MAX_ARRAY = 150; // Setting maximum Array size.
//---------------------------------------------------------------------------
// Define member functions for class Adder.

Adder::Adder (void) {  // Default constructor.
      maxSize = MAX;      
      // Dynamically Allocating Memory.
      Addend_1 = new char [maxSize]; 
      Addend_2 = new char [maxSize];
      Sum = new char [maxSize + 1];
      setZero(); // Setting Addends value to zero for the time being.         
}
//---------------------------------------------------------------------------
Adder::Adder (char* addend_1, char* addend_2) { // Constructor 
      maxSize = MAX;
      // Dynamically Allocating Memory.
      Addend_1 = new char [maxSize];
      Addend_2 = new char [maxSize];
      Sum = new char [maxSize + 1];
      setZero(); // Setting Addends value to zero for the time being.
      
      // Setting Addents to convert any non-numeric characters to zero, right 
      // Justified, and filling every element of the array as zero and assigning 
      // value to the addends.
      setAddend_1 (addend_1); 
      setAddend_2 (addend_2);      
}
//---------------------------------------------------------------------------
void Adder::setAddend_1 (char* addend_1) {
     // Convert any non-numeric characters to zero, Right 
     // justified, and filling every element of the array as zero and assigning 
     // value to the addends. 
     if (strlen(addend_1) > maxSize) {
         addend_1[maxSize] = '\0'; // If the user inputs more characters than 
         // maxSize then it ignores it.
     }
     toNumericChar(addend_1); // Converts any non-numeric characters to zero.
     for (int i = 0; i < maxSize; ++i) {
         Addend_1[i] = '0';
     }
     // Load and Right Justification.
     int last_addend_1_index = strlen(addend_1)- 1;
     int last_Addend_1_index = maxSize - 1;
     
     for(int j = last_addend_1_index; j >= 0; --j, --last_Addend_1_index){
           Addend_1[last_Addend_1_index] = addend_1[j];
     }
}
//---------------------------------------------------------------------------
void Adder::setAddend_2 (char* addend_2) {
     // Convert any non-numeric characters to zero, Right 
     // justified, and filling every element of the array as zero and assigning 
     // value to the addends. 
     if (strlen(addend_2) > maxSize) {
         addend_2[maxSize] = '\0';
     }
     toNumericChar(addend_2); // Converts any non-numeric characters to zero.
     for (int i = 0; i < maxSize; ++i) {
         Addend_2[i] = '0';
     }
     // Load and Right Justification.
     int last_addend_2_index = strlen(addend_2)- 1;
     int last_Addend_2_index = maxSize - 1;
     
     for(int j = last_addend_2_index; j >= 0; --j, --last_Addend_2_index){
           Addend_2[last_Addend_2_index] = addend_2[j];
     }
}
//---------------------------------------------------------------------------
void Adder::getSum(char* sum) {
     // Calculates the sum of two character array and stores it to a third 
     // character array called sum.     
     int sum_digit;
     int carry = 0;       
     
     for (int i = maxSize - 1; i >= 0; --i) {
         sum_digit = (Addend_1[i] - '0') + (Addend_2[i] - '0') + carry;
         carry = sum_digit / 10; // Getting Carry.
         sum[i + 1] = (sum_digit % 10) + '0'; // Getting Sum.
     }
     sum[0] = carry + '0'; 
     
     char temp[MAX_ARRAY]; // Creating temp Array. 
     strncpy(temp, sum, maxSize + 1); // Loading the value of Sum in to the temp
     // array. 
     temp[maxSize + 1] = '\0'; // Putting string terminator for Sum.
     strcpy(sum, temp); // Copying the value from temp to Sum.         
}
//---------------------------------------------------------------------------
void Adder::displayAddend_1(char* addend_1) {
     // Displays the Addend.
     for (int i = 0; i < maxSize; ++i) {
         cout << Addend_1[i];
     }
}
//---------------------------------------------------------------------------
void Adder::displayAddend_2(char* addend_2) {
     // Displays the Addend.
     for (int i = 0; i < maxSize; ++i) {
         cout << Addend_2[i];
     }
}
//---------------------------------------------------------------------------
void Adder::setZero(){  
     // Setting zero the elements of Addends.   
     for (int i = 0; i < maxSize; ++i){
         Addend_2[i] = '0';
         Addend_1[i] = '0';
     }
}
//---------------------------------------------------------------------------
void Adder::Adjust_Addends_Size(int userSize) {
     // It allow the joe programmer to get the sum of any size of the addends.
     
     // Deleting the current value of addends and the sum. 
     delete [] Addend_1; 
     delete [] Addend_2;
     delete [] Sum;
     
     maxSize = userSize; // Changing the value to the programmer defined number.
     if (maxSize < MIN) {
        // If the size the programmer inputs is less than MIN then it will set it 
        // as a MIN.
        maxSize = MIN;
     }
     
     // Dynamically changing the size of addends to programmer defined size.
     Addend_1 = new char [maxSize];
     Addend_2 = new char [maxSize];
     // Dynamically changing the size of sum as well to reflect the change in 
     // addends.
     Sum = new char [maxSize + 1];
     setZero(); // Setting the addends value to zero.    
}
//---------------------------------------------------------------------------
void Adder::toNumericChar(char * NonNumericChar) {
     // Converting any value user enters except from 0 to 9 to ZERO.
     // Validating!
      for(int x = 0; x < strlen(NonNumericChar); ++x){
             if (!(NonNumericChar[x] >= '0' && NonNumericChar[x] <= '9')) {
                         NonNumericChar[x] = '0';
             }
      }
}           
//---------------------------------------------------------------------------
Adder::~Adder (void) {  // Destructor.
// Deleting the memory space taken as it is no more required. 
      delete [] Addend_1;
      delete [] Addend_2;
      delete [] Sum;
}
//---------------------------------------------------------------------------


Solution: Main
// Programming Assignment: # Final Assignment --> Adder.
// This program uses Adder Class to do the addition operation. It accepts the 
// character from user and manipulates the character using ASCII to convert it 
// to numeric and perform the addition operation and again gives out the
// equivalent output in characters. This program can add two numbers of any size.
// The Joe Programmer has facility, as he can use the class's public method called
// Adjust_Addends_Size() and type in any number in the parenthesis to get the 
// sum of that many numbered Addends. This is done by dynamically allocating the 
// memory space by the class Adder. Hence, when a Joe Programmer creates an object 
// of the class then they can just call this method to set the addends for sum.
// The addition of two 20-digit numbers are performed using the default constructor
// as well as the constructor which takes two argument. Using the default 
// constructor, we have to set the addends by calling setAddent_1() and 
// setAddend_2() methods. The object is inniciated for the class in a different 
// manner than for the constructor which accepts two arguments. For the 
// constructor, we don't need to set the addends as it is already done in the 
// constructor itself. Hence, this program uses the class and its objects to 
// get the sum of any number of addends very smartly.
//------------------------------------------------------------------------------
// Programming Environment: Bloodshed
// Program Description:
// Date/Time: 5/8/2010  6:08:57 AM
//------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "extras.h"
#include "Adder.h"
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------
const int MAX = 20; // Constant for Addend.
const int LOCAL_LENGTH = 150; //  Maximum array length for user.
//---------------------------------------------------------------------------
// Structure Declarations
//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------
int main (void) {

    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);   
    
    char My_Adder_1[MAX]; // 1st Addend Array with max element 20.
    char My_Adder_2[MAX]; // 2nd Addend Array with max element 20.
    char My_Sum[MAX + 1]; // Sum is one greater than the addends.
    
    // USING DEFAULT CONSTRUCTOR
    cout << endl << "ADDITION OPERATION OF 20 DIGIT NUMBERS Ver. 1.7";
    cout << endl << "-----------------------------------------------";
    cout << endl << "-----------USING DEFAULT CONSTRUCTOR-----------";
    cout << endl << "-----------------------------------------------";
    
    // User input
    cout << endl << endl << "Enter First Number to ADD: ";
    cin.getline(My_Adder_1, LOCAL_LENGTH);
    
    cout << endl << "Enter Second Number to ADD: ";
    cin.getline(My_Adder_2, LOCAL_LENGTH);
    
    // Creating the object using default constructor.
    Adder My_Add;
    My_Add.setAddend_1(My_Adder_1); // Setting addends.
    My_Add.setAddend_2(My_Adder_2);
    My_Add.getSum(My_Sum); // Getting Sum.
    
    // Displaying the addends, Sum in organised way!!
    cout << endl << endl << setw (10) << "Addend ONE: " << setw (7);
    My_Add.displayAddend_1(My_Adder_1);
    cout << endl << setw (10) << "Addend TWO: " << setw (7);
    My_Add.displayAddend_2(My_Adder_2);
    cout << endl << setw (10) << "               +  " << "--------------------";
    cout << endl << setw (10) << "       SUM:      ";
    cout << My_Sum;  
    
   // USING CONSTRUCTOR 
    cout << endl << endl;
    cout << endl << "-----------------------------------------------";
    cout << endl << "---------------USING CONSTRUCTOR---------------" << endl;
    cout << endl << "-----------------------------------------------";
    // Getting Input.
    cout << endl << endl << "Enter First Number to ADD: ";
    cin.getline(My_Adder_1, LOCAL_LENGTH);
    
    cout << endl << "Enter Second Number to ADD: ";
    cin.getline(My_Adder_2, LOCAL_LENGTH);
    
    // Creating object from the class Adder using the constructor having 
    // two parenthesis as two addends.
    Adder My_Adder(My_Adder_1, My_Adder_2);    
    My_Adder.getSum(My_Sum); // Getting Sum.
    
    // Displaying the addends, Sum in organised way!!
    cout << endl << endl << setw (10) << "Addend ONE: " << setw (7);
    My_Adder.displayAddend_1(My_Adder_1);
    cout << endl << setw (10) << "Addend TWO: " << setw (7);
    My_Adder.displayAddend_2(My_Adder_2);
    cout << endl << setw (10) << "               +  " << "--------------------";
    cout << endl << setw (10) << "       SUM:      ";
    cout << My_Sum;
    
    // USING JOE PROGRAMMER MODIFYING ADDENDS SIZE TO ANY NUMBER.
    cout << endl << endl;
    cout << endl << "-----------------------------------------------";
    cout << endl << "     ADDITION OPERATION OF 7 DIGIT NUMBERS     ";
    cout << endl << "  JOE PROGRAMMER MODIFYING ADDEND'S SIZE TO 7  " << endl;
    cout << endl << "-----------------------------------------------";
    
    // Taking Input.
    cout << endl << endl << "Enter First Number to ADD: ";
    cin.getline(My_Adder_1, LOCAL_LENGTH);
    
    cout << endl << "Enter Second Number to ADD: ";
    cin.getline(My_Adder_2, LOCAL_LENGTH);
    
    // Creating Object of the class Adder.
    Adder My_Adder_7;
    
    // Joe Programmer changing the size of addends to 7. He can type 50 to 
    // get the sum of 50 digit Addends.
    My_Adder_7.Adjust_Addends_Size(7); 
    
    // Settting Addends.
    My_Adder_7.setAddend_1(My_Adder_1); 
    My_Adder_7.setAddend_2(My_Adder_2);
    // Getting Sum.
    My_Adder_7.getSum(My_Sum);
    
    // Displaying the addends & Sum in organised way!!
    cout << endl << endl << setw (10) << "Addend ONE: " << setw (7);
    My_Adder_7.displayAddend_1(My_Adder_1);
    cout << endl << setw (10) << "Addend TWO: " << setw (7);
    My_Adder_7.displayAddend_2(My_Adder_2);
    cout << endl << setw (10) << "               +  " << "-------";
    cout << endl << setw (10) << "       SUM:      ";
    cout << My_Sum;
    cout << endl << endl << "-----------------------------------------------";
    cout << endl << "Contact the Programmer, if you want to perform "
         << endl << "specific number of digit's sum."; 
    cout << endl << "-----------------------------------------------";
    cout << endl << "THANK YOU FOR USING THIS PROGRAM! VERSION 1.7";
    cout << endl << "-----------------------------------------------";
    
    //---------------------------------------------------------
    cout << endl << endl << "\aDepress Any Key to Continue...";
    _getch ();
    return 0;
}
//------------------------------------------------------------------------
// Function Definitions
//------------------------------------------------------------------------



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


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
Prajwal Shrestha, 720-233-2603
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;