Wednesday, March 31, 2010

Let the user enter a charge account number and determines if the account number entered by ther user is Valid or Invalid. It uses a function to determine whether the account number is valid or invalid by checking the valid account numbers which we store in an array.

// Programming Environment: Bloodshed
// Program Description: This program lets the user enter a charge account number
//                      and determines if the account number entered by ther user
//                      is Valid or Invalid. It uses a function to determine
//                      whether the account number is valid or invalid by
//                      checking the valid account numbers which we store in an
//                      array.
// Date/Time: 3/26/2010  4:27:49 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 ACCOUNT_SIZE = 18;
//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------
// Function Prototypes
bool Search_Valid_Account(int[], int, int); // Using Bool as function return type.
//---------------------------------------------------------------------------

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

    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);
  
    // Storing the valid account numbers in integer array.
    int Valid_Charge_Account[ACCOUNT_SIZE] = {5658845, 8080152, 1005231, 4520125,
                                              4562555, 6545231, 7895122, 5552012,
                                              3852085, 8777541, 5050552, 7576651,
                                              8451277, 7825877, 7881200, 1302850,
                                              1250255, 4581002};  
    int Charge_Account_Num;
    int Num_Elements = 0;  
    // Getting input from user to check if it is valid or not.  
    do {
    cout << endl << "Please Enter Charge Account Number: ";
    cin >> Charge_Account_Num;    
    // Displaying the valid account numbers so that they know where they went wrong.
    cout << endl << endl << "Valid Charge Account Numbers are: " << endl << endl;
    for (int i = 0; i < 18; ++i) {
        cout << " " << Valid_Charge_Account[i];
        ++ Num_Elements;      
    }
    // If the function return true, the account is valid else its Invalid.
    if (Search_Valid_Account (Valid_Charge_Account, Charge_Account_Num,
                              Num_Elements)) {
        cout << endl << endl << "This Account Number is Valid!";
    } else {
           cout << endl << endl << "This Account Number is Invalid";
    }
  
    } while (Do_Again ());
    return 0;
}
//------------------------------------------------------------------------
// Function Definitions
bool Search_Valid_Account(int valid_charge_account[], int charge_account_num,
                          int num_elements) {
     // This function checks from index 0 to index one less than the number of
     // elements(our case: 18) if the account number entered by user is in any
     // of the index of our array of valid acount numbers. If it finds it then
     // it returns true else it return false to main.
     int index = 0;
     while (index < num_elements &&
                    charge_account_num != valid_charge_account[index]) {
           ++ index;
     }
     if (index < num_elements) {
         return true;
     } else {
         return false;
     }
}
//------------------------------------------------------------------------
bool Do_Again (void) {

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

Tuesday, March 30, 2010

Quiz: Write a C++ function (you decide on the name) that takes a character array (i.e., string) as an argument. The function trims any leading and trailing whitespace characters from the given string and it also replaces any occur- rences of space characters with underscores. You decide how the function "returns" the modified string.

Quiz

Write a C++ function (you decide on the name) that takes a character array
(i.e., string) as an argument. The function trims any leading and trailing
whitespace characters from the given string and it also replaces any occur-
rences of space characters with underscores. You decide how the function
"returns" the modified string. Note: Do not use any "string function" that
may be available; i.e., do it yourself!

Write a C++ program that demonstrates your function performs correctly.

Accomplish this either as a team or as an individual.

Although the joy experienced and knowledge acquired while doing this problem
should be reward enough, I'll go ahead and assign 25 points to this exercise.

*********************************************************
*                   Some Help For You                   *
*********************************************************

Function Prototype: void My_Stringer (char[], char[]);

Function: void My_Stringer (char init_str[], char new_str[]) {

    Pseudocode:

    // Find where the given string begins, bypassing any whitespace.

    Set Index to 0

    While (init_str[Index] == Space Character OR init_str[Index] == Tab Character)
        Increment Index
    End While

    Set Start_Index to Index

    // Find where the given string ends.

    // Find where the given string ends, bypassing any trailing whitespace.

    // Create new string (i.e., new_str), replacing space characters with underscores.


End Function




// Programming Environment: Bloodshed
// Program Description: This program takes input from user and it stores it in
//                      an array. It uses this characters stored in an array to
//                      manupulate any space character and tab characters in
//                      between the other characters in to underscore as well as
//                      it trims any leading and trailing whitespace characters
//                      from the string using function.
// Date/Time: 3/29/2010  4:41:41 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 MAX_ELEMENTS = 256;
//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------
// Function Prototypes
void My_Stringer (char[], char[]);

//---------------------------------------------------------------------------

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

    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);
  
    char Init_Str[MAX_ELEMENTS]; // For manupulation.  
    cout << endl << "Enter Anything you want and I will convert it: ";
    cin.getline(Init_Str, MAX_ELEMENTS);  
    char New_Str[MAX_ELEMENTS]; // Array declared to store the manupulated array.
    My_Stringer(Init_Str, New_Str);
    cout << endl << New_Str; // Displaying the manupulated string array which
    //--------------------------our function passed after processing it.
  
    //---------------------------------------------------------
    cout << endl << endl << "\aDepress Any Key to Continue...";
    _getch ();
    return 0;
}
//------------------------------------------------------------------------
// Function Definitions
void My_Stringer (char init_str[], char new_str[]) {
     // This function defination takes the address/argument of the the actual
     // function in main and performs the calculation so that we could access the
     // manupulated output from main.
     // First we find the start index ignoring any space and tab characters from
     // the beginning of the array till we found the characters except space and
     // tab. Then, we find the end of the character that the user has last entered.
     // Now, we move backwards from the position where the string ends searching
     // for characters excpet space and tab as we have to ignore them.
     // Once we find that character then we set that index of memory location as
     // our end index so that we get the starting and ending point where we have
     // to manupulate.
     // In this range of start index and end index, we now convert any space and
     // tab character in to underscore and leave it as it is if we encounter
     // other characters excpet them. At the same time we transfer the
     // manupulated characterd in to a new array. Hence displaying this array
     // in the main would display the manupulated array.
     // Lastly, we put the (end of character / string terminator) to the
     // character array we created in main to make it a string array or to
     // terminate the array.
        
     int index = 0;
     while (init_str[index] == ' ' || init_str[index] == '\t') {
           ++ index;
     }
     int start_index = index; // Start boundry.
      
     index = 0;
     while (init_str[index] != '\0') {
           ++ index; // After the while loop, we are at the end of user entered
           //-----------character.
     }  
     -- index; // It moves one index back than the index that has end of
     //-----------character which allows us to compare the space and tab user
     //-----------enters after the last characters setting the ground to ignore
     //-----------trailing whitespace characters.  
     while (init_str[index] == ' ' || init_str[index] == '\t') {
     --index; // From the end of the characters entered by user we move
     //----------backwards to find space and tabs to get the end index.
     }  
  
     int end_index = index; // Store it to other variable so that we can use
     //------------------------index again.
     int j = 0; // For our new array.  
     // Since, we have our boundry, we now use the for loop in our bounrdy of
     // concern to put underscore where there is space and tabs. We skip the
     // tabs and space in the trailing and leading section of our array by
     // assigning the values to our new array in this boundry only.
     for (int index = start_index; index <= end_index; ++index, ++j) {
         if (init_str[index] != ' ' && init_str[index] != '\t'  ) {
            new_str[j] = init_str[index];
            } else {
                   new_str[j] = '_';
            }        
     }
     new_str[j] = '\0'; // We are ending the array after loading all the
     //--------------------manupulation so that when we disply the new array
     //--------------------it won't load unnecessary memory loctions.
}
//------------------------------------------------------------------------

Friday, March 26, 2010

Lottery Application using rand() & srand()


// Programming Assignment : Lottery Application
// Programming Environment: Bloodshed
// Program Description: This program generates a non repetitive random numbers
// for the lottery Application using rand() & srand(). It asks user their choice
// of lucky numbers which is unique. Then it processes the result how many matches
// the user has and gives congratulations if they manage to match 5 out of 5.
// Date/Time: 2/25/2010  3:08:47 AM
//---------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

//---------------------------------------------------------------------------
// Named Constants
const int MAX_ELEMENTS = 5;
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
   bool Unique_Lottery_Value(int[], int, int);
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
int main (void)
{
    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);

    int Lottery[5];
    int User[5];  
    for(int i = 0; i < 5; ++i) {
        Lottery[i] = rand() % 10;      
    }
      
    int current_index = 0;
    unsigned seed = time(0);
    srand(seed);
    while (current_index < 5) {    
        int lottery_value = rand() % 10;      
        // Unique_Lottery_Value(Lottery, current_index, lottery_value);
        // To get computer unique value
        if(Unique_Lottery_Value(Lottery, current_index, lottery_value)) {          
             Lottery[current_index] = lottery_value;                  
             ++ current_index;          
             }  
    }
    // Getting the unique value from the  user.
    int Last_Index = -1;
    // Value is 0 after one iteration!! (Maintains the index of last element loaded).  
    int Search_Index; // Used to check or search array for duplicates.
    int User_Num; // Value entered by user.
  
    for (int count = 1; count <= MAX_ELEMENTS; ++count) {
        cout << endl << "Enter Your Lucky Number: ";
        cin >> User_Num;
      
        if (Last_Index >= 0) {
            Search_Index = 0;
            while (Search_Index <= Last_Index && User_Num != User[Search_Index]) {
                  ++ Search_Index;
            }
            if (Search_Index > Last_Index) {
               User[Search_Index] = User_Num;
               ++ Last_Index;
            } else {
                   cout << endl << "Your Input Duplicates Entry Number"
                        << " "<< (Search_Index + 1) << " " << "Please Re-Enter" << endl;
                   --count;
            }
        } else {
               User[0] = User_Num;
               Last_Index = 0;
        }
    }        
        
   //This was my first attempt to ge the unique value from the user
  /*
   do {
   cout << endl << endl << "Enter your 1st lucky num: ";
   cin >> User[0];
   }
   while (User[0] > 9 || User[0] < 0);


   do {
   cout << endl << "Enter your 2nd lucky no without repetition: ";
   cin >> User[1];
   }
   while (User[1] == User[0] || (User[1] > 9 || User[1] < 0));

   do {
       cout << endl << "Enter your 3rd Lucky no without repetition: ";
       cin >> User[2];
   }
       while (User[2] == User[1] || User [2] == User[0] || (User[2] > 9 || User[2] < 0) );
    
       do {
          cout << endl << "Enter your 4rd Lucky no without repetition: ";
          cin >> User[3];
       }
       while (User[3] == User[2] || User[3] == User[1] || User [3] == User[0] || (User[3] > 9 || User[3] < 0));
    
          do {
          cout << endl << "Enter your 5rd Lucky no without repetition: ";
          cin >> User[4];
          }
          while (User[4] == User[3] || User[4] == User[2] || User [4] == User[1] || User [4] == User [0] || (User[4] > 9 || User[4] < 0));  
        
    
       */


    cout << endl << endl << "The Numbers you Entered: ";  
    for(int i = 0; i < 5; ++i) {
        cout << User[i] << "  ";      
    }
    cout << endl << "Today's Winning Numbers: ";
    for(int i = 0; i < 5; ++i) {
        cout << Lottery[i] << "  ";      
    }
    int match = 0;
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j) {
            if (Lottery[i] == User[j]) {
            ++ match;
            }
        }
    }
    cout << endl << endl << "Your Luck Today!!" << endl << "You Managed to match: "
         << match << "/5.";
  
    if (match == 5) {
        cout << endl << "Congratulations: You won $99,000,000";
    }
    cout << endl << endl << endl << "Depress Any Key to Continue...";
    _getch ();
    return 0;
}
//---------------------------------------------------------------------------
// Function Definitions follow.
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
   // Checks if the random numbers generated in unique or not.
   bool Unique_Lottery_Value(int array[], int index, int lottery_pick){
        if(index > 0) {
            for(int i = 0; i < index; ++i) {
                if (lottery_pick == array[i] || lottery_pick == array[i - 1] || lottery_pick == array[i + 1]){
                    return false;                
                }
            }
        }
        return true;      
   }
//---------------------------------------------------------------------------

Advertisement: 

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

Functions to perform the profit or loss from the sale of stock.


// Programming Assignment: Stock Profit
// Programming Environment: Bloodshed
// Date/Time: 2/17/2010  5:48:40 PM
//---------------------------------------------------------------------------
// This program uses functions to perform the profit or loss from the sale
// of stock. It used Pass by value and return statement to get the profit or loss.
// The input is taken from the user and validated using while loop. Function is
// called to check the profit or loss and used if..else statement to check profit
// or loss. Then function defination is written to support the function call.
//---------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
   //Function Prototype
   double Calculate_Profit(int, double, double, double, double);
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
int main (void)
{
    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);
  
    int Num_Shares;
    double Share_Price_Buy;
    double Purchase_Commission;
  
    double Share_Price_Sell;
    double Sale_Commission;
  
    // Getting input from the user.
    cout << endl << "Please Enter the Number of Shares: ";
    cin >> Num_Shares;
    // Validating the user input to enter positive numbers only.
    while(Num_Shares <= 0) {
        cout << "Warning: Invalid Share Number." << endl
             << "Please Re-enter the Number of Shares: ";
        cin >> Num_Shares;
    }
  
    cout << endl << "Please Enter the Price of Share when Bought: $";
    cin >> Share_Price_Buy;
    // Validating the user input to enter positive numbers only.
    while(Share_Price_Buy <= 0) {
        cout << "Warning: Invalid Share Price." << endl
             << "Please Re-enter the Price Share when Bought: $";
        cin >> Share_Price_Buy;
    }
  
    cout << endl << "Please Enter the Commission Amount when Purchased Share: $";
    cin >> Purchase_Commission;  
    // Validating the user input to enter positive numbers only.
    while(Purchase_Commission <= 0) {
        cout << "Warning: Invalid Commission Amount." << endl
             << "Please Re-enter the Commission Amount when Purchased Share: $";
        cin >> Purchase_Commission;
    }
  
    cout << endl << "Please Enter the Price of Share when Sold: $";
    cin >> Share_Price_Sell;  
    // Validating the user input to enter positive numbers only.
    while(Share_Price_Sell <= 0) {
        cout << "Warning: Invalid Share Price." << endl
              << "Please Re-enter the Price Share when Sold: $";
        cin >> Share_Price_Sell;
    }
  
    cout << endl << "Please Enter the Commission Amount when Sold the Share: $";
    cin >> Sale_Commission;  
    // Validating the user input to enter positive numbers only.
    while(Sale_Commission <= 0) {
        cout << "Warning: Invalid Commission Amount." << endl
             << "Please Re-enter the Commission Amount when Sold the Share: $";
        cin >> Sale_Commission;
    }
  
    double profit; // Local Valiable defined to store the profit / loss.
  
    // Function Invoke / Call
    // Just using function call by passing parameters by value. Not using reference!
    profit = Calculate_Profit(Num_Shares, Share_Price_Buy, Purchase_Commission,
             Share_Price_Sell, Sale_Commission);
  
    // Using if..else statement to determine if we encounter with profit or loss.
    if(profit >= 0) {
        cout << endl << "\nYour Profit is: " << "$" << profit;
        } else {
          cout << endl << "\nYour Loss is: " << "$" << abs(profit);
        }                  
    
      
    cout << endl << endl << endl << "Depress Any Key to Continue...";
    _getch ();
    return 0;
}
//---------------------------------------------------------------------------
    // Function Defination
    // Function Defination that uses return statement. This functions returns
    // a double value to the function call.
    double Calculate_Profit (int num_shares, double share_price_buy,
                            double purchase_commission, double share_price_sell,
                            double sale_commission) {
           // Just the formula to calculate the profit / loss.                      
    double Profit = (num_shares * share_price_sell - sale_commission) -
                    (num_shares * share_price_buy + purchase_commission);
    return Profit; // Pass By Value
    }
//---------------------------------------------------------------------------

Population Bar Chart: Processes the population figures so that it's one symbol ('\x03') represents 1000 people and displays the year and it's consequent population in terms of neatly calculated symbol.


// Programming Assignment: Population Bar Chart
// Programming Environment: Bloodshed
// Date/Time: 2/10/2010 8:31:19 PM
//------------------------------------------------------------------------------
// This program takes input from "prople.dat" file from external storage device.
// The inputs are population of small town. It processes the population figures
// so that it's one symbol ('\x03') represents 1000 people and displays the year
// and it's consequent population in terms of neatly calculated symbol.
//------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//---------------------------------------------------------------------------
const char BAR_CHART_SYMBOL = '\x03'; // Love symbol for bar representation.
const char MY_PATH_FILE[]="c:\\c++\\assignment 4\\people.dat";
//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------
int main (void)
{
cout.setf (ios::fixed, ios::floatfield);
cout.setf (ios::showpoint);
cout.precision (2);

int population;
int no_symbol;
int year = 1900; // Initialization of variable "year" to 1900.

// Reading the population figures for the years(interval of 20 years).
ifstream My_Infile;
My_Infile.open(MY_PATH_FILE);
if(My_Infile){
cout << endl << "File from external source opened: Successfully!"; // Formatting the o/p so that it would look good on screen! cout << endl << endl << "PRAIRIEVILLE POPULATION GROWTH"; cout << endl << "[Each \x03 represents 1,000 people]" << endl; cout << endl << "YEAR" << " " << "POPULATION"; cout << endl << "----" << " " << "----------"; // Reading one line of data at a time and performing calculations and // displaying the population in terms of symbols. while (My_Infile >> population ) {
//My_Infile >> population;
cout << endl << year << setw(8); no_symbol = population / 1000; // If resudial population is greater or equal to 500 then // considering it as 1000 & incrementing symbol by 1. if (population % 1000 >= 500) {
no_symbol ++;
}

// Using for loop to display the symbol.
for (int count = 1; count <= no_symbol; ++count) {
cout << BAR_CHART_SYMBOL;
}

// Population Parentheses.
cout << setw(2) << "[" << population << "]";
year = year + 20; // Incrementing year by 20.
}

My_Infile.close(); // Closing the file as it would be unnecessary at
// this point of the program.
} else {
cout << endl << "Error: File Open Error!"; // Error message if the file
// don't open!
}

cout << endl << endl << endl << "Depress Any Key to Continue...";
_getch ();
return 0;
}
//---------------------------------------------------------------------------
// Function Definitions follow.
//---------------------------------------------------------------------------

Population Bar Chart

// Programming Environment: Bloodshed
// Date/Time: 2/10/2010  8:31:19 PM
//------------------------------------------------------------------------------
// This program takes input from "prople.dat" file from external storage device.
// The inputs are population of small town. It processes the population figures
// so that it's one symbol ('\x03') represents 1000 people and displays the year
// and it's consequent population in terms of neatly calculated symbol.
//------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//---------------------------------------------------------------------------
    const char BAR_CHART_SYMBOL = '\x03'; // Love symbol for bar representation.
    const char MY_PATH_FILE[]="c:\\c++\\assignment 4\\people.dat";
//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------
int main (void)
{
    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);

    int population;  
    int no_symbol;
    int year = 1900; // Initialization of variable "year" to 1900.  

    // Reading the population figures for the years(interval of 20 years).
    ifstream My_Infile;      
    My_Infile.open(MY_PATH_FILE);  
    if(My_Infile){
        cout << endl << "File from external source opened: Successfully!";
      
        // Formatting the o/p so that it would look good on screen!
        cout << endl << endl << "PRAIRIEVILLE POPULATION GROWTH";
        cout << endl << "[Each \x03 represents 1,000 people]" << endl;
        cout << endl << "YEAR" << "       " << "POPULATION";
        cout << endl << "----" << "       " << "----------";
      
    // Reading one line of data at a time and performing calculations and
    // displaying the population in terms of symbols.
    while (My_Infile >> population ) {
        //My_Infile >> population;            
        cout << endl << year << setw(8);      
        no_symbol = population / 1000;
                
            // If resudial population is greater or equal to 500 then
            // considering it  as 1000 & incrementing symbol by 1.
            if (population % 1000 >= 500) {
               no_symbol ++;          
            }
      
        // Using for loop to display the symbol.
        for (int count = 1; count <= no_symbol; ++count) {
            cout << BAR_CHART_SYMBOL;          
        }
            
    // Population Parentheses.
    cout << setw(2) << "[" << population << "]";
    year = year + 20; // Incrementing year by 20.            
    }

   My_Infile.close(); // Closing the file as it would be unnecessary at
                      // this point of the program.
   } else {
     cout << endl << "Error: File Open Error!"; // Error message if the file
                                                // don't open!
   }  
      
    cout << endl << endl << endl << "Depress Any Key to Continue...";
    _getch ();
    return 0;
}
//---------------------------------------------------------------------------
// Function Definitions follow.
//---------------------------------------------------------------------------

Advertisement: 

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

Stock Transaction Program: It displays the money paid in dollars for the stock, commission paid for the broker, total stock bought, total stock sold, commissions paid to broker and whether you ended up making profit or loss (if you also sold your stock).


// Programming Assignment: 2. Stock Transaction Program
// Programming Environment: Bloodshed
// Date/Time: 1/27/2010  3:01:55 AM
//---------------------------------------------------------------------------
// This program asks the Joe user to input the values for shares purchased
// and sold, price per share bought and sold and, percentage of commission when
// bought and sold the stock to stock broker.
// It processes the information provided by the user using if...else statement
// at two different location in the program to be more user-friendly.
// It displays the money paid in dollars for the stock, commission paid for the
// broker, total stock bought, total stock sold, commissions paid to broker and
// whether you ended up making profit or loss (if you also sold your stock).
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------
int main (void)
{
    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);

    // Variable Initialization.
    int share_no;
    double share_price;
    double commission_rate;
    double amount_paid_stock;
    double commission_paid;
  
    int share_no_sold;
    double share_price_sold;
    double commission_rate_sold;
    double amount_sold_stock;
    double commission_paid_sell;
  
    double total_buying;
    double total_selling;
    double profit;
    double loss;
  
    // Prompt for and get shares purchased, price per share and commission to
    // broker.  
    cout << endl << "Enter the number of shares purchased: ";
    cin >> share_no;
  
    cout << endl << "Enter the price per share: ";
    cin >> share_price;
  
    cout << endl << "Enter the percentage of commission paid to broker: ";
    cin >> commission_rate;
  
    // Calculations for amount paid for stock, commission paid to the broker and
    // total buying.
    amount_paid_stock = share_no * share_price;
    commission_paid = amount_paid_stock * commission_rate / 100;
    total_buying = amount_paid_stock + commission_paid;
  
    // Display Results
    cout << endl << "Amount of money paid for the stock: " << "$" << amount_paid_stock;
    cout << endl << "Amount of commission paid to broker when the stock was bought: " << "$" << commission_paid;
    
    // Using if...else to make this program more user-friendly.
    cout << endl << endl << endl << "\nHave you sold the stock? (y/n): ";
    char answer;
    cin >> answer;
    if (answer == 'Y' || answer == 'y'){    
  
       // Prompt for and get shares sold, price per share and commission to broker.
       cout << endl << "Enter the number of shares sold: ";
       cin >> share_no_sold;
  
       cout << endl << "Enter the price per share sold: ";
       cin >> share_price_sold;
  
       cout << endl << "Enter the percentage of commission paid to broker: ";
       cin >> commission_rate_sold;
  
       // Calculations for amount of stock sold, commission paid to sell the
       // stock and total selling.  
       amount_sold_stock = share_no_sold * share_price_sold;
       commission_paid_sell = amount_sold_stock * commission_rate_sold / 100;
       total_selling = amount_sold_stock - commission_paid_sell;
       profit = total_selling - total_buying;
  
       // Display results
       cout << endl << "Amount of money received for the stock sold: " << "$" << amount_sold_stock;
       cout << endl << "Amount of commission paid to broker when the stock was sold: " << "$" << commission_paid_sell;
       // cout << endl << "Profit/loss: " << "$" << profit;

       if (profit >= 0.0){
          cout << endl << "Your profit is: " << "$" << profit;
          } else {
          cout << endl << "Your Loss is: " << "$" << fabs(profit);
          // Using Fabs function to convert negative no into a positive.
          }

    } else {
    cout << endl << "Come back again when you sell your stock. ";
    cout << endl << "Thank You";
    }
        
    cout << endl << endl << endl << "Depress Any Key to Continue...";
    _getch ();
    return 0;
}
//---------------------------------------------------------------------------
// Function Definitions follow.
//---------------------------------------------------------------------------

Stock Commission: This program also processes amount of commission (2%) from the amount paid for the stock alone. This program then adds amount paid for the stock alone and amount of commission to process total amount paid by Kathryn.


// Programming: Stock Commission
// Programming Environment: Bloodshed
// Date/Time: 1/22/2010  7:31:02 PM
//---------------------------------------------------------------------------
// This program has constant value of 600 shares and a price of $21.77 per share.
// Stock broker's commission is 2%.
// This program multiplies the number of share and price per share to get the
// amount paid for the stock alone.
// This program also processes amount of commission (2%) from the amount paid
// for the stock alone.
// This program then adds amount paid for the stock alone and amount of
// commission to process total amount paid by Kathryn.
// -------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//---------------------------------------------------------------------------
// Named Constants
//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------
int main (void)
{
    cout.setf (ios::fixed, ios::floatfield);
    cout.setf (ios::showpoint);
    cout.precision (2);
  
    // Variable Assignments and Initialization.
    int shares = 600;
    double price = 21.77;
    double commission = 2;
  
    double amount_stock;
    double amount_commission;
    double total_amount;
  
    // Information for the user: Kathryn bought 600 shares of stock at a
    // price of $21.77.
    cout << endl << "Since, Kathryn Bought 600 Shares of Stock at a Price of $21.77,";
    
    // Calculate and display amount paid for stock alone.
    amount_stock = shares * price; // Arithmetic Operators.
    cout << endl << "\a\n The amount paid for the stock alone, without the commission: " << "$" << amount_stock;
  
    // Information for the user: Commission for the transaction is 2%.
    cout << endl << "\n\nSince, commission for the stock broker is 2%,";
  
    // Calculate and display the amount of commission only.
    amount_commission = amount_stock * commission / 100; // Arithmetic Operators.  
    cout << endl << "\a\n The amount of commission for stock brokers: " << "$" << amount_commission;
  
    // Information for the user: Total Investment.
    cout << endl << "\n\nFinally, calculating total investment made on shares,";
  
    // Calculate and display the total amount paid by Kathryn.
    total_amount = amount_stock + amount_commission; // Arithmetic Operators.      
    cout << endl << "\a\n Total amount paid for the stock and the commission by Kathryn: " << "$" << total_amount;
        
    cout << endl << endl << endl << "Press Any Key to Continue...";
    getch (); // Holds the screen, so that, we can see the result.
    return 0;
}
//---------------------------------------------------------------------------
// Function Definitions follow.
//---------------------------------------------------------------------------

Advertisement: 

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