C programming tweak needed for a specific program.
This is the complete program up and running. except for one modification that my teacher is
requiring but it is confusing me.
The program needs to allocate disjoint memory and use that.
right now im allocating a continous block of memory on the heap but I need it to do disjoing
memory instead.
// Purpose: Program will allow a reseller to save their sales and calculate their profits.
// Also able to view highest profitable items and remove any sales they no longer want in their
sales inventory.
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#define PAUSE system(\"pause\")
#define CLS system(\"cls\");
//#define FLUSH fflush(stdin);
//////////////// SRUCTS BELOW //////////////////////////
typedef struct
{
char itemName[40];
float purchasePrice;
float soldPrice;
float shippingPrice;
float ebayFee;
float payPalFee;
float profit;
}SALES;
////////// FUNCTION PROTOTYPE BELOW /////////////
void addSale(SALES *Inventory, int *InventoryCounter);
void displayMenu(int *InventoryCounter);
void displayProfit(int *InventoryCounter, SALES *Inventory);
void displaySales(int *InventoryCounter, SALES *Inventory);
int getChoice(int *InventoryCounter);
void searchSale(SALES* Inventory, int InventoryCounter);
void sortProfits(SALES* Inventory, int InventoryCounter);
void removeSale(SALES* Inventory, int *InventoryCounter);
main() {
int SIZE;
int userChoice;
int InventoryCounter = 0;
//printf(\"*********************\ \");
//printf(\"* Welcome Reseller! *\ \");
//printf(\"*********************\ \");
printf(\"Enter the size of todays inventory:\");
scanf(\"%i\", &SIZE);
SALES *Inventory;
Inventory = calloc(SIZE, sizeof(SALES));//Using dynamic memory to allocate space on the
heap
do {
userChoice = getChoice(&InventoryCounter);
switch (userChoice) {
case 1:// Add a Sale
if (InventoryCounter == SIZE) // statement checks so we dont exceed the size of the
inventory user wants to enter.
{
printf(\"You Have Reached Max Inventory \ \");
PAUSE;
}
else {
addSale(&(Inventory[InventoryCounter]), &InventoryCounter);
}
break;
case 2: // Display all sales records
displaySales(&InventoryCounter, Inventory);
PAUSE;
break;
case 3: // Display all profits
sortProfits(Inventory, InventoryCounter);
displayProfit(&InventoryCounter, Inventory);
PAUSE;
break;
case 4: // Display Inventory
searchSale(Inventory, InventoryCounter);
break;
case 5:// remove a sale
removeSale(Inventory, &InventoryCounter);
break;
case 6: // Quit
break;
default:
printf(\"Please choose a valid option\ \");
PAUSE;
break;
}// end of switch
} while (userChoice != 6);
free(Inventory);
} // End of main
//////////////////////////////////////////// FUNCTIONS BELOW //////////////////////////////////////////////////
void addSale(SALES *Inventory, int *InventoryCounter)// Function that adds sale and
calculates the fees in the background.
{
float payPalFee = 0; // variable to store the paypal fee from 1 sale
float ebayFee = 0; // variable to store ebay fee for 1 sale.
Please answer the 4 questions using C- The expected output is shown be.docxcgraciela1
Please answer the 4 questions using C. The expected output is shown below. Thank you!
---------------------------------------------------------------------------------------------------
// Write your name here
// Write the compiler used: Visual studio or gcc
// Reminder that your file name is incredibly important. Please do not change it.
// Reminder that we are compiling on Gradescope using GCC.
// READ BEFORE YOU START:
// You are given a partially completed program that creates a list of game items
like you'd see in a folder.
// Each item has this information: item's name, game's name, type of item, item ID.
// The struct 'itemRecord' holds information of one item. Variety is an enum.
// An array of structs called 'list' is made to hold the list of items.
// To begin, you should trace through the given code and understand how it works.
// Please read the instructions above each required function and follow the
directions carefully.
// You should not modify any of the given code, the return types, or the
parameters. Otherwise, you risk getting compilation errors.
// You are not allowed to modify main().
// You can use string library functions.
// WRITE COMMENTS FOR IMPORANT STEPS IN YOUR CODE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable: 4996) // for Visual Studio
Only
#define MAX_ITEMS 15
#define MAX_NAME_LENGTH 25
typedef enum { Health = 0, Equip, Etc } itemType; // enum type
struct itemRecord { // struct for item details
char itemName[MAX_NAME_LENGTH];
char gameName[MAX_NAME_LENGTH];
itemType variety;
unsigned int itemID;
};
struct itemRecord list[MAX_ITEMS]; // declare list of items
int count = 0; // the number of items
currently stored in the list (initialized to 0)
// functions already implmented
void flushStdIn();
void executeAction(char);
void save(char* fileName);
void display();
// functions that need implementation:
int add(char* itemName_input,
char* gameName_input,
char* variety_input,
unsigned int idNumber_input); // 10 points
void sort(); // 10 points
int delete(unsigned int idNumber_input); // 10 points
void load(char* fileName); // 10 points
int main()
{
char* fileName = "Item_List.txt";
load(fileName); // load list of items from
file (if it exists). Initially there will be no file.
char choice = 'i'; // initialized to a dummy
value
do
{
printf("\nEnter your selection:\n");
printf("\t a: add a new item\n");
printf("\t d: display item list\n");
printf("\t r: remove an item from list\n");
printf("\t s: sort item list by ID\n");
printf("\t q: quit\n");
choice = getchar();
flushStdIn();
executeAction(choice);
} while (choice != 'q');
save(fileName); // save list of items to file
(overwrites file, if it exists)
return 0;
}
// flush out leftover '\n' characters
void flushStdIn()
{
char c;
do c = getchar();
while (c != '\n' && c != EOF);
}
// ask for details from user for the given selection and perform that action
.
In C pls -- Write your name here -- Write the compiler used- Visual st.docxBlake0FxCampbelld
In C pls
// Write your name here
// Write the compiler used: Visual studio or gcc
// Reminder that your file name is incredibly important. Please do not change it.
// Reminder that we are compiling on Gradescope using GCC.
// READ BEFORE YOU START:
// You are given a partially completed program that creates a list of game items
like you'd see in a folder.
// Each item has this information: item's name, game's name, type of item, item ID.
// The struct 'itemRecord' holds information of one item. Variety is an enum.
// An array of structs called 'list' is made to hold the list of items.
// To begin, you should trace through the given code and understand how it works.
// Please read the instructions above each required function and follow the
directions carefully.
// You should not modify any of the given code, the return types, or the
parameters. Otherwise, you risk getting compilation errors.
// You are not allowed to modify main().
// You can use string library functions.
// WRITE COMMENTS FOR IMPORANT STEPS IN YOUR CODE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable: 4996) // for Visual Studio
Only
#define MAX_ITEMS 15
#define MAX_NAME_LENGTH 25
typedef enum { Health = 0, Equip, Etc } itemType; // enum type
struct itemRecord { // struct for item details
char itemName[MAX_NAME_LENGTH];
char gameName[MAX_NAME_LENGTH];
itemType variety;
unsigned int itemID;
};
struct itemRecord list[MAX_ITEMS]; // declare list of items
int count = 0; // the number of items
currently stored in the list (initialized to 0)
// functions already implmented
void flushStdIn();
void executeAction(char);
void save(char* fileName);
void display();
// functions that need implementation:
int add(char* itemName_input,
char* gameName_input,
char* variety_input,
unsigned int idNumber_input); // 10 points
void sort(); // 10 points
int delete(unsigned int idNumber_input); // 10 points
void load(char* fileName); // 10 points
int main()
{
char* fileName = "Item_List.txt";
load(fileName); // load list of items from
file (if it exists). Initially there will be no file.
char choice = 'i'; // initialized to a dummy
value
do
{
printf("\nEnter your selection:\n");
printf("\t a: add a new item\n");
printf("\t d: display item list\n");
printf("\t r: remove an item from list\n");
printf("\t s: sort item list by ID\n");
printf("\t q: quit\n");
choice = getchar();
flushStdIn();
executeAction(choice);
} while (choice != 'q');
save(fileName); // save list of items to file
(overwrites file, if it exists)
return 0;
}
// flush out leftover '\n' characters
void flushStdIn()
{
char c;
do c = getchar();
while (c != '\n' && c != EOF);
}
// ask for details from user for the given selection and perform that action
void executeAction(char c)
{
char itemName_input[MAX_NAME_LENGTH], gameName_input[MAX_NAME_LENGTH];
unsigned int idNumber_input, add_result = 0;
char variety_input[20];
swi.
RightTriangle/rightTriangle.cppRightTriangle/rightTriangle.cpp// This file includes implementations for functions of the right
// triangle class.
#include<iostream>
#include<cmath>
usingnamespace std;
#include"rightTriangle.h"
// Default constructor
RightTriangle::RightTriangle()
{
base =0;
height =0;
}
// SET functions (for storing data in private data members)
voidRightTriangle::setHeight(double h)
{
height = h;
}
voidRightTriangle::setBase(double b)
{
base = b;
}
// Calculate length of hypotenuse using
// Pythagorean Theorem
doubleRightTriangle::calcHypotenuse()
{
return sqrt (base * base + height * height);
}
__MACOSX/RightTriangle/._rightTriangle.cpp
RightTriangle/rightTriangle.h
// This file defines the specifications for a class to store
// attributes of a right triangle
class RightTriangle
{
private: // PRIVATE data members
double base;
double height;
public: // PUBLIC member functions
RightTriangle(); // Default constructor
void setHeight(double h); // SET functions
void setBase(double b);
// Calculate length of hypotenuse
double calcHypotenuse();
};
__MACOSX/RightTriangle/._rightTriangle.h
RightTriangle/testTriangle.cppRightTriangle/testTriangle.cpp// This program calculates various parameters of a
// right triangle.
#include<iostream>
usingnamespace std;
#include"rightTriangle.h"
int main()
{
// Declaration
double base,height;
RightTriangle aTriangle;
// Input
cout <<"Enter the base of the triangle: ";
cin >> base;
cout <<"Enter the height of the triangle: ";
cin >> height;
// Move data to object
aTriangle.setBase(base);
aTriangle.setHeight(height);
// Calculations and output
cout << endl;
cout <<"Length of hypotenuse: "
<< aTriangle.calcHypotenuse()<< endl;
return0;
}// end main function
__MACOSX/RightTriangle/._testTriangle.cpp
c++practice3a3b/._rightTriangle.cpp
c++practice3a3b/._rightTriangle.h
c++practice3a3b/._testTriangle.cpp
c++practice3a3b/partList.txt
2345 Snoozle 15.4 29.95
1234 Widget 5.4 9.99
3456 Bludger 9.1 15.49
5678 Zeeter 7.7 1.99
6789 Sub_Tweezer 12.3 5.25
4567 Woofle 3.7 49.79
c++practice3a3b/partMgr.cppc++practice3a3b/partMgr.cpp// This program manages a list of parts.
#include<iostream>
#include<iomanip>
#include<fstream>
usingnamespace std;
// Attributes for one part
struct partInfo
{
int number;
char name[30];
double weight;
double price;
};
constint MAX_LIST_SIZE =100;
// Function prototypes
int menu();
void buildPartsList(partInfo partList[],int& listSize);
void searchParts(partInfo partList[],int numParts);
void listParts(partInfo partList[],int& numParts);
void insertPart(partInfo list[],int& numElems);
void deletePart(partInfo list[],int& numElems);
partInfo getPartInfo();
v ...
/* Lab 2: Histrogram generation
* Author: Naga Kandasamy
* Date: 01/25/2017
*
* compile as follows: gcc -o histogram histogram.c -std=c99 -fopenmp -lm
*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <math.h>
#include <float.h>
#include <omp.h>
void run_test(int);
void compute_gold(int *, int *, int, int);
void compute_using_openmp(int *, int *, int, int);
void check_histogram(int *, int, int);
#define HISTOGRAM_SIZE 500
#define NUM_THREADS 8
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int
main( int argc, char** argv)
{
if(argc != 2){
printf("Usage: histogram <num elements> \n");
exit(0);
}
int num_elements = atoi(argv[1]);
run_test(num_elements);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//! Generate the histogram in both single-threaded and multi-threaded fashion and compare results for correctness
////////////////////////////////////////////////////////////////////////////////
void run_test(int num_elements)
{
double diff;
int i;
int *reference_histogram = (int *)malloc(sizeof(int) * HISTOGRAM_SIZE); // Space to store histogram generated by the CPU
int *histogram_using_openmp = (int *)malloc(sizeof(int) * HISTOGRAM_SIZE); // Space to store histogram generated by the GPU
// Allocate memory for the input data
int size = sizeof(int) * num_elements;
int *input_data = (int *)malloc(size);
// Randomly generate input data. Initialize the input data to be integer values between 0 and (HISTOGRAM_SIZE - 1)
for(i = 0; i < num_elements; i++)
input_data[i] = floorf((HISTOGRAM_SIZE - 1) * (rand()/(float)RAND_MAX));
printf("Creating the reference histogram. \n");
// Compute the reference solution on the CPU
struct timeval start, stop;
gettimeofday(&start, NULL);
compute_gold(input_data, reference_histogram, num_elements, HISTOGRAM_SIZE);
gettimeofday(&stop, NULL);
printf("CPU run time = %0.2f s. \n", (float)(stop.tv_sec - start.tv_sec + (stop.tv_usec - start.tv_usec)/(float)1000000));
// check_histogram(reference_histogram, num_elements, HISTOGRAM_SIZE);
// Compute the histogram using openmp. The result histogram should be stored on the histogram_using_openmp array
printf("\n");
printf("Creating histogram using OpenMP. \n");
compute_using_openmp(input_data, histogram_using_openmp, num_elements, HISTOGRAM_SIZE);
// check_histogram(histogram_using_openmp, num_elements, HISTOGRAM_SIZE);
// Compute the differences between the reference and pthread results
diff = 0.0;
for(i = 0; i < HISTOGRAM_SIZE; i++)
diff = diff + abs(reference_histogram[i] - histogram_using_openmp[i]);
printf("Difference between the reference and OpenMP results: %f. \n", diff);
// cleanup memory
free(input_data);
free(reference_his ...
Please answer the 4 questions using C- The expected output is shown be.docxcgraciela1
Please answer the 4 questions using C. The expected output is shown below. Thank you!
---------------------------------------------------------------------------------------------------
// Write your name here
// Write the compiler used: Visual studio or gcc
// Reminder that your file name is incredibly important. Please do not change it.
// Reminder that we are compiling on Gradescope using GCC.
// READ BEFORE YOU START:
// You are given a partially completed program that creates a list of game items
like you'd see in a folder.
// Each item has this information: item's name, game's name, type of item, item ID.
// The struct 'itemRecord' holds information of one item. Variety is an enum.
// An array of structs called 'list' is made to hold the list of items.
// To begin, you should trace through the given code and understand how it works.
// Please read the instructions above each required function and follow the
directions carefully.
// You should not modify any of the given code, the return types, or the
parameters. Otherwise, you risk getting compilation errors.
// You are not allowed to modify main().
// You can use string library functions.
// WRITE COMMENTS FOR IMPORANT STEPS IN YOUR CODE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable: 4996) // for Visual Studio
Only
#define MAX_ITEMS 15
#define MAX_NAME_LENGTH 25
typedef enum { Health = 0, Equip, Etc } itemType; // enum type
struct itemRecord { // struct for item details
char itemName[MAX_NAME_LENGTH];
char gameName[MAX_NAME_LENGTH];
itemType variety;
unsigned int itemID;
};
struct itemRecord list[MAX_ITEMS]; // declare list of items
int count = 0; // the number of items
currently stored in the list (initialized to 0)
// functions already implmented
void flushStdIn();
void executeAction(char);
void save(char* fileName);
void display();
// functions that need implementation:
int add(char* itemName_input,
char* gameName_input,
char* variety_input,
unsigned int idNumber_input); // 10 points
void sort(); // 10 points
int delete(unsigned int idNumber_input); // 10 points
void load(char* fileName); // 10 points
int main()
{
char* fileName = "Item_List.txt";
load(fileName); // load list of items from
file (if it exists). Initially there will be no file.
char choice = 'i'; // initialized to a dummy
value
do
{
printf("\nEnter your selection:\n");
printf("\t a: add a new item\n");
printf("\t d: display item list\n");
printf("\t r: remove an item from list\n");
printf("\t s: sort item list by ID\n");
printf("\t q: quit\n");
choice = getchar();
flushStdIn();
executeAction(choice);
} while (choice != 'q');
save(fileName); // save list of items to file
(overwrites file, if it exists)
return 0;
}
// flush out leftover '\n' characters
void flushStdIn()
{
char c;
do c = getchar();
while (c != '\n' && c != EOF);
}
// ask for details from user for the given selection and perform that action
.
In C pls -- Write your name here -- Write the compiler used- Visual st.docxBlake0FxCampbelld
In C pls
// Write your name here
// Write the compiler used: Visual studio or gcc
// Reminder that your file name is incredibly important. Please do not change it.
// Reminder that we are compiling on Gradescope using GCC.
// READ BEFORE YOU START:
// You are given a partially completed program that creates a list of game items
like you'd see in a folder.
// Each item has this information: item's name, game's name, type of item, item ID.
// The struct 'itemRecord' holds information of one item. Variety is an enum.
// An array of structs called 'list' is made to hold the list of items.
// To begin, you should trace through the given code and understand how it works.
// Please read the instructions above each required function and follow the
directions carefully.
// You should not modify any of the given code, the return types, or the
parameters. Otherwise, you risk getting compilation errors.
// You are not allowed to modify main().
// You can use string library functions.
// WRITE COMMENTS FOR IMPORANT STEPS IN YOUR CODE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable: 4996) // for Visual Studio
Only
#define MAX_ITEMS 15
#define MAX_NAME_LENGTH 25
typedef enum { Health = 0, Equip, Etc } itemType; // enum type
struct itemRecord { // struct for item details
char itemName[MAX_NAME_LENGTH];
char gameName[MAX_NAME_LENGTH];
itemType variety;
unsigned int itemID;
};
struct itemRecord list[MAX_ITEMS]; // declare list of items
int count = 0; // the number of items
currently stored in the list (initialized to 0)
// functions already implmented
void flushStdIn();
void executeAction(char);
void save(char* fileName);
void display();
// functions that need implementation:
int add(char* itemName_input,
char* gameName_input,
char* variety_input,
unsigned int idNumber_input); // 10 points
void sort(); // 10 points
int delete(unsigned int idNumber_input); // 10 points
void load(char* fileName); // 10 points
int main()
{
char* fileName = "Item_List.txt";
load(fileName); // load list of items from
file (if it exists). Initially there will be no file.
char choice = 'i'; // initialized to a dummy
value
do
{
printf("\nEnter your selection:\n");
printf("\t a: add a new item\n");
printf("\t d: display item list\n");
printf("\t r: remove an item from list\n");
printf("\t s: sort item list by ID\n");
printf("\t q: quit\n");
choice = getchar();
flushStdIn();
executeAction(choice);
} while (choice != 'q');
save(fileName); // save list of items to file
(overwrites file, if it exists)
return 0;
}
// flush out leftover '\n' characters
void flushStdIn()
{
char c;
do c = getchar();
while (c != '\n' && c != EOF);
}
// ask for details from user for the given selection and perform that action
void executeAction(char c)
{
char itemName_input[MAX_NAME_LENGTH], gameName_input[MAX_NAME_LENGTH];
unsigned int idNumber_input, add_result = 0;
char variety_input[20];
swi.
RightTriangle/rightTriangle.cppRightTriangle/rightTriangle.cpp// This file includes implementations for functions of the right
// triangle class.
#include<iostream>
#include<cmath>
usingnamespace std;
#include"rightTriangle.h"
// Default constructor
RightTriangle::RightTriangle()
{
base =0;
height =0;
}
// SET functions (for storing data in private data members)
voidRightTriangle::setHeight(double h)
{
height = h;
}
voidRightTriangle::setBase(double b)
{
base = b;
}
// Calculate length of hypotenuse using
// Pythagorean Theorem
doubleRightTriangle::calcHypotenuse()
{
return sqrt (base * base + height * height);
}
__MACOSX/RightTriangle/._rightTriangle.cpp
RightTriangle/rightTriangle.h
// This file defines the specifications for a class to store
// attributes of a right triangle
class RightTriangle
{
private: // PRIVATE data members
double base;
double height;
public: // PUBLIC member functions
RightTriangle(); // Default constructor
void setHeight(double h); // SET functions
void setBase(double b);
// Calculate length of hypotenuse
double calcHypotenuse();
};
__MACOSX/RightTriangle/._rightTriangle.h
RightTriangle/testTriangle.cppRightTriangle/testTriangle.cpp// This program calculates various parameters of a
// right triangle.
#include<iostream>
usingnamespace std;
#include"rightTriangle.h"
int main()
{
// Declaration
double base,height;
RightTriangle aTriangle;
// Input
cout <<"Enter the base of the triangle: ";
cin >> base;
cout <<"Enter the height of the triangle: ";
cin >> height;
// Move data to object
aTriangle.setBase(base);
aTriangle.setHeight(height);
// Calculations and output
cout << endl;
cout <<"Length of hypotenuse: "
<< aTriangle.calcHypotenuse()<< endl;
return0;
}// end main function
__MACOSX/RightTriangle/._testTriangle.cpp
c++practice3a3b/._rightTriangle.cpp
c++practice3a3b/._rightTriangle.h
c++practice3a3b/._testTriangle.cpp
c++practice3a3b/partList.txt
2345 Snoozle 15.4 29.95
1234 Widget 5.4 9.99
3456 Bludger 9.1 15.49
5678 Zeeter 7.7 1.99
6789 Sub_Tweezer 12.3 5.25
4567 Woofle 3.7 49.79
c++practice3a3b/partMgr.cppc++practice3a3b/partMgr.cpp// This program manages a list of parts.
#include<iostream>
#include<iomanip>
#include<fstream>
usingnamespace std;
// Attributes for one part
struct partInfo
{
int number;
char name[30];
double weight;
double price;
};
constint MAX_LIST_SIZE =100;
// Function prototypes
int menu();
void buildPartsList(partInfo partList[],int& listSize);
void searchParts(partInfo partList[],int numParts);
void listParts(partInfo partList[],int& numParts);
void insertPart(partInfo list[],int& numElems);
void deletePart(partInfo list[],int& numElems);
partInfo getPartInfo();
v ...
/* Lab 2: Histrogram generation
* Author: Naga Kandasamy
* Date: 01/25/2017
*
* compile as follows: gcc -o histogram histogram.c -std=c99 -fopenmp -lm
*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <math.h>
#include <float.h>
#include <omp.h>
void run_test(int);
void compute_gold(int *, int *, int, int);
void compute_using_openmp(int *, int *, int, int);
void check_histogram(int *, int, int);
#define HISTOGRAM_SIZE 500
#define NUM_THREADS 8
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int
main( int argc, char** argv)
{
if(argc != 2){
printf("Usage: histogram <num elements> \n");
exit(0);
}
int num_elements = atoi(argv[1]);
run_test(num_elements);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//! Generate the histogram in both single-threaded and multi-threaded fashion and compare results for correctness
////////////////////////////////////////////////////////////////////////////////
void run_test(int num_elements)
{
double diff;
int i;
int *reference_histogram = (int *)malloc(sizeof(int) * HISTOGRAM_SIZE); // Space to store histogram generated by the CPU
int *histogram_using_openmp = (int *)malloc(sizeof(int) * HISTOGRAM_SIZE); // Space to store histogram generated by the GPU
// Allocate memory for the input data
int size = sizeof(int) * num_elements;
int *input_data = (int *)malloc(size);
// Randomly generate input data. Initialize the input data to be integer values between 0 and (HISTOGRAM_SIZE - 1)
for(i = 0; i < num_elements; i++)
input_data[i] = floorf((HISTOGRAM_SIZE - 1) * (rand()/(float)RAND_MAX));
printf("Creating the reference histogram. \n");
// Compute the reference solution on the CPU
struct timeval start, stop;
gettimeofday(&start, NULL);
compute_gold(input_data, reference_histogram, num_elements, HISTOGRAM_SIZE);
gettimeofday(&stop, NULL);
printf("CPU run time = %0.2f s. \n", (float)(stop.tv_sec - start.tv_sec + (stop.tv_usec - start.tv_usec)/(float)1000000));
// check_histogram(reference_histogram, num_elements, HISTOGRAM_SIZE);
// Compute the histogram using openmp. The result histogram should be stored on the histogram_using_openmp array
printf("\n");
printf("Creating histogram using OpenMP. \n");
compute_using_openmp(input_data, histogram_using_openmp, num_elements, HISTOGRAM_SIZE);
// check_histogram(histogram_using_openmp, num_elements, HISTOGRAM_SIZE);
// Compute the differences between the reference and pthread results
diff = 0.0;
for(i = 0; i < HISTOGRAM_SIZE; i++)
diff = diff + abs(reference_histogram[i] - histogram_using_openmp[i]);
printf("Difference between the reference and OpenMP results: %f. \n", diff);
// cleanup memory
free(input_data);
free(reference_his ...
Hi,Please fidn the Answer.Sorting,h is Header .pdfanandf0099
Hi,
Please fidn the Answer.
//////////////////Sorting,h is Header file which contians all Function decalartion
#include
#include // std::cout
#include // std::shuffle
#include // std::array
#include // std::default_random_engine
#include
using namespace std;
class Sorting
{
private:
int num;
public:
Sorting::Sorting() {
};
///Buble Sort Input array and n Number of Elemnets
void BubbleSorting(int array[], int n);
void SelectionSorting(int array[], int n);
void ShuffleArray(int array[], int n);
void DisplayArray(int array[], int n);
void displayMenu();
int choice;
};
//////////////////////////Sorting.cpp is class fuction Which Implemnets the Function
#include \"Sorting.h\"
#include
using namespace std;
///Sorting the Array Using Bubble Sort...
void Sorting::BubbleSorting(int Array[],int n)
{
int temp = 0;
cout << \"\ ------------ BUBBLE SORT ------------ \ \ \";
for (int i = 1; iArray[j + 1])
{
temp = Array[j];
Array[j] = Array[j + 1];
Array[j + 1] = temp;
}
}
cout << \"\ ------------ RESULTS BUBBLE SORT ------------ \ \ \";
DisplayArray(Array, n);
}
//////SelectionSorting input Array and n is number of Elemnets//////////////////////
void Sorting::SelectionSorting(int Array[], int n)
{
int i, n, p, k, min, loc, temp;
for (p = 1; p <= n - 1; p++) // Loop for Pass
{
min = Array[p]; // Element Selection
loc = p;
for (k = p + 1; k <= n; k++) // Finding Min Value
{
if (min > Array[k])
{
min = Array[k];
loc = k;
}
}
temp = Array[p]; // Swap Selected Element and Min Value
Array[p] = Array[loc];
Array[loc] = temp;
}
cout << \"\ ------------ RESULTS SELECTION SORT ------------ \ \ \";
DisplayArray(Array, n);
}
//////SelectionSorting input Array and n is number of Elemnets//////////////////////
///exchange each element with a randomly chosen element. It\'s possible that an element will be
exchanged with itself, but there is no problem with that
void Sorting::ShuffleArray(int Array[], int n)
{
cout << \"\ ------------ ShuffleArray SORT ------------ \ \ \";
for (int i = 0; i
#include \"Sorting.h\"
using namespace std;
int main()
{
bool SelectionOn = true;
Sorting Sorting;
int choice;
int n = 10;
int *Arry;
while (SelectionOn != false) {
cout << \"*******************************\ \";
cout << \" 1 - Enter User Input Array of Elements.\ \";
cout << \" 2 - Display User Input.\ \";
cout << \" 3 - Shuffle User Input the Elements i.\ \";
cout << \" 4 - Bubble Sorting.\ \";
cout << \" 5 - Selection Sorting.\ \";
cout << \" 6 - Exit.\ \";
cout << \" 7 - Display Menu Again. \ \";
cout << \" Enter your choice and press return: \";
cin >> choice;
switch (choice)
{
case 1:
cout << \"Enter User Input Array of Elements\ \";
cout << \"Enter No. of Elements=\";
cin >> n;
Arry = new int[n];
cout << \"\ Enter Elements=\ \";
for (int i = 1; i <= n; i++)
{
cin >> Arry[i];
}
break;
case 2:
cout << \"DISPLAY OF ARRAY\ \";
if (Arry != NULL)
{
Sorting.DisplayArray(Arry, n);
}
else
{
cout << \"ENTER ELEMENTS TO ARRAY BY SELCTING CHOICE 1\ \";
}
break;
case 3:
cout << \"SHUFFLE OF A.
-- Reminder that your file name is incredibly important- Please do not.docxAdamq0DJonese
// Reminder that your file name is incredibly important. Please do not change it.
// Reminder that we are compiling on Gradescope using GCC.
// READ BEFORE YOU START:
// You are given a partially completed program that creates a list of game items
like you'd see in a folder.
// Each item has this information: item's name, game's name, type of item, item ID.
// The struct 'itemRecord' holds information of one item. Variety is an enum.
// An array of structs called 'list' is made to hold the list of items.
// To begin, you should trace through the given code and understand how it works.
// Please read the instructions above each required function and follow the
directions carefully.
// You should not modify any of the given code, the return types, or the
parameters. Otherwise, you risk getting compilation errors.
// You are not allowed to modify main().
// You can use string library functions.
// WRITE COMMENTS FOR IMPORANT STEPS IN YOUR CODE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable: 4996) // for Visual Studio
Only
#define MAX_ITEMS 15
#define MAX_NAME_LENGTH 25
typedef enum { Health = 0, Equip, Etc } itemType; // enum type
struct itemRecord { // struct for item details
char itemName[MAX_NAME_LENGTH];
char gameName[MAX_NAME_LENGTH];
itemType variety;
unsigned int itemID;
};
struct itemRecord list[MAX_ITEMS]; // declare list of items
int count = 0; // the number of items
currently stored in the list (initialized to 0)
// functions already implmented
void flushStdIn();
void executeAction(char);
void save(char* fileName);
void display();
// functions that need implementation:
int add(char* itemName_input,
char* gameName_input,
char* variety_input,
unsigned int idNumber_input); // 10 points
void sort(); // 10 points
int delete(unsigned int idNumber_input); // 10 points
void load(char* fileName); // 10 points
int main()
{
char* fileName = "Item_List.txt";
load(fileName); // load list of items from
file (if it exists). Initially there will be no file.
char choice = 'i'; // initialized to a dummy
value
do
{
printf("\nEnter your selection:\n");
printf("\t a: add a new item\n");
printf("\t d: display item list\n");
printf("\t r: remove an item from list\n");
printf("\t s: sort item list by ID\n");
printf("\t q: quit\n");
choice = getchar();
flushStdIn();
executeAction(choice);
} while (choice != 'q');
save(fileName); // save list of items to file
(overwrites file, if it exists)
return 0;
}
// flush out leftover '\n' characters
void flushStdIn()
{
char c;
do c = getchar();
while (c != '\n' && c != EOF);
}
// ask for details from user for the given selection and perform that action
void executeAction(char c)
{
char itemName_input[MAX_NAME_LENGTH], gameName_input[MAX_NAME_LENGTH];
unsigned int idNumber_input, add_result = 0;
char variety_input[20];
switch (c)
{
case 'a':
// input item record from user
printf("\nEnter item name: ").
files/Heap.h
#ifndef HEAP_H
#define HEAP_H
#include <vector>
#include <stdexcept> // std::out_of_range
#include <math.h> // pow()
using namespace std;
template<typename T>
class Heap
{
private:
vector<T> _items; // Main vector of elements for heap storage
/**
* Used to take unsorted data and heapify it
*/
void buildHeap()
{
for (int i = _items.size() / 2; i >= 0; i--)
{
percolateDown(i);
}
}
/*********************************************************************/
/********************* Microassignment zone *************************/
/**
* Percolates the item specified at by index down
* into its proper location within a heap.
* Used for dequeue operations and array to heap conversions
* MA TODO: Implement percolateDown!
*/
void percolateDown(int index)
{
}
/**
* Percolate up from a given index to fix heap property
* Used in inserting new nodes into the heap
* MA TODO: Implement percolateUp
*/
void percolateUp( int current_position )
{
}
/************************** Microassigment zone DONE *********************/
public:
/**
* Default empty constructor
*/
Heap()
{
}
/**
* Constructor with a vector of elements
*/
Heap(const vector<T> &unsorted)
{
for (int i = 0; i < unsorted.size(); i++)
{
_items.push_back(unsorted[i]);
}
buildHeap();
}
/**
* Adds a new item to the heap
*/
void insert(T item)
{
int current_position = size(); // Get index location
_items.push_back(item); // Add data to end
percolateUp( current_position ); // Adjust up, as needed
}
/**
* Returns the top-most item in our heap without
* actually removing the item from the heap
*/
T& getFirst()
{
if( size() > 0 )
return _items[0];
else
throw std::out_of_range("No elements in Heap.");
}
/**
* Removes minimum value from heap and returns it to the caller
*/
T deleteMin()
{
int last_index = size() - 1; // Calc last item index
int root_index = 0; // Root index (for readability)
T min_item = _items[root_index]; // Keep item to return
_items[root_index] = _items[last_index]; // Move last item to root
_items.erase(_items.end() - 1); // Erase last element entry
percolateDown(0); // Fix heap property
return min_item;
}
/**
* Returns true if heap is empty, else false
*/
bool isEmpty() const
{
return _items.size() == 0;
}
/**
* Returns current quantity of elements in heap (N)
*/
int size() const
{
return _items.size();
}
/**
* Return heap data in order from the _items vector
*/
string to_s() const
{
string ret = "";
for(int i = 0; i < _items.size(); i++)
{
ret += to_string(_items[i]) + " ";
}
return ret;
}
/**
...
Write a program that converts an infix expression into an equivalent.pdfmohdjakirfb
Write a program that converts an infix expression into an equivalent postfix expression. The
rules to convert an infix expression into an equivalent postfix expression are as follows (C++):
Initialize pfx to an empty expression and also initialize the stack.
Get the next symbol, sym, from infx.
If sym is an operand, append sym to pfx.
If sym is (, push sym into the stack.
If sym is ), pop and append all of the symbols from the stack until the most recent left
parentheses. Pop and discard the left parentheses.
If sym is an operator:
Pop and append all of the operators from the stack to pfx that are above the most recent left
parentheses and have precedence greater than or equal to sym.
Push sym onto the stack.
After processing infx, some operators might be left in the stack. Pop and append to pfx
everything from the stack.
In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /.
You may assume that the expressions you will process are error free. Design a class that stores
the infix and postfix strings. The class must include the following operations:
getInfix: Stores the infix expression.
showInfix: Outputs the infix expression.
showPostfix: Outputs the postfix expression.
convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix
expression is stored in pfx.
precedence: Determines the precedence between two operators. If the first operator is of higher
or equal precedence than the second operator, it returns the value true; otherwise, it returns the
value false.
A + B - C;
(A + B ) * C;
(A + B) * (C - D);
A + ((B + C) * (E - F) - G) / (H - I);
A + B * (C + D ) - E / F * G + H;
Infix Expression: A+B-C;
Postfix Expression: AB+C-
Infix Expression: (A+B)*C;
Postfix Expression: AB+C*
Infix Expression: (A+B)*(C-D);
Postfix Expression: AB+CD-*
Infix Expression: A+((B+C)*(E-F)-G)/(H-I);
Postfix Expression: ABC+EF-*G-HI-/+
Infix Expression: A+B*(C+D)-E/F*G+H;
Postfix Expression: ABCD+*+EF/G*-H+
Turn in:
A UML diagram for your class.
The header file for your class.
The implementation file for your class.
The source code for your test program. (C++)
(Below already done code.)
//Header file: myStack.h
#ifndef H_StackType
#define H_StackType
#include
#include
#include \"stackADT.h\"
using namespace std;
template
class stackType: public stackADT
{
public:
const stackType& operator=(const stackType&);
//Overload the assignment operator.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: stackTop = 0
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
void push(const Type& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postc.
Symfony World - Symfony components and design patternsŁukasz Chruściel
There are so many Symfony components already, and they have some pretty neat perks. But have you seen them in action?
Design patterns are not a silver bullet. They will never resolve your problem on their own. On the other hand, design patterns provide a common ground for developers without going into details and could be used as building bricks to solve some more advanced problems.
During my presentation, I will take a closer look and explain the appliance of selected design patterns. What is more, I will take advantage of the Symfony ecosystem to implement them with ease.
I will do the presentation on sample code that developers will understand at all levels of expertise.
The purpose of this C++ programming project is to allow the student .pdfRahul04August
The purpose of this C++ programming project is to allow the student to perform parallel array
and multidimensional array processing. The logic for string and Cstring has already been
completed, so the assignment can be started before we actually cover string and Cstring in detail.
This program has the following three menu options:
Solution
/*
This program uses simple arrays, multidimensional arrays, cstrings, strings, and files.
It allows a payroll clerk to choose an option from a menu. The choices are:
A: List the Payroll Information by Employee Name
B: Search Payroll Information by Employee Name
X: Exit the Payroll Information Module
The following items for each employee are saved in the file p10.txt:
Employee ID (1000 - 9999)
Last Name (15 characters)
First Name (15 characters)
Rate (5.00 - 10.00)
Hours W1,W2,W3,W4 (0-60)
*/
#include // file processing
#include // cin and cout
#include // toupper
#include // setw
#include // cstring functions strlen, strcmp, strcpy stored in string.h
#include // string class
#define stricmp strcasecmp
#define strnicmp strncasecmp
using namespace std;
//Disable warning messages C4267 C4996.
//To see the warnings, comment out the following line.
//#pragma warning( disable : 4267 4996)
//Warning C4267: coversion from size_t to int, possible lost of data
//size_t is a data type defined in and is an unsigned integer.
//The function strlen returns a value of the type size_t, but in
//searchByName we assign the returned value to an int.
//We could also declare the variable as size_t instead of int.
// size_t stringLength;
//Warning C4996: strnicmp strcpy, stricmp was declared deprecated, means
//the compiler encountered a function that was marked with deprecated.
//The deprecated function may no longer be supported in a future release.
//Global Constants
//When using to declare arrays, must be defined with const modifier
const int ARRAY_SIZE = 20, HOURS_SIZE = 4, NAME_SIZE = 16;
//Declare arrays as global so we don\'t have to pass the arrays to each function.
//Normally we wouldn\'t declare variables that change values a global.
int employeeId[ARRAY_SIZE];
string firstName[ARRAY_SIZE];
char lastName[ARRAY_SIZE][NAME_SIZE];
double rate[ARRAY_SIZE];
int hours[ARRAY_SIZE][HOURS_SIZE];
int numberOfEmps; //count of how many employees were loaded into arrays
int sumHours[ARRAY_SIZE] = {0}; //initialize arrays to zero by providing a
double avgHours[ARRAY_SIZE] = {0}; //value for the first element in the array
//Function Prototypes
void loadArray( );
void sumAndComputeAvgHours( );
void listByName( );
void searchByName( );
void sortByName( );
void swapValues(int i, int minIndex);
void listEmployees( );
void listEmployeesHeadings( );
void listEmployeesDetails(int i);
void listEmployeesTotals( );
void displayContinuePrompt( );
//Program starts here
int main()
{
//Declare and initialize local main variables
char choice; //menu option
//Load the arrays with data
loadArray();
//Sum and compute the average hours
sumAndComputeAv.
How does the mutation rate of speciation in the Dobzhansky- Muller m.pdfflashfashioncasualwe
How does the mutation rate of speciation in the Dobzhansky- Muller model? How does the
mutation rate affect the rate of speciation in the Dobzhansky Muller model? An increased
mutation rate results in a more rapid reproductive isolation between the two diverging
populations. O An increased mutation rate results in slower reproductive isolation between the
two diverging populations. The mutation rate is unrelated to the rate of evolution of reproductive
isolation.
Solution
ans- a increased mutation rate results in a more reproduction isolation between the two diverging
population.
an ancestral population splits into two parts the two lineage begins to diverge genetically which
are temporally isolated from each other.new alleles evolved at one locus of lineage and different
alleles evolved in another locus of the lineage..
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdfflashfashioncasualwe
Hello. I need help fixing this Java Code on Eclipse. Please fix parts indicated as \"//Fix\" or
\"//Fill-in\". The code given is the first image. Thank you! Sample outputs are given below along
with what the code is required to do. import java til. Random import java til. Scanner public class
GenCheeseShopv2 public static void intro (Stringt] names, double []prices int amounts Fill-in
public static void getAmount (Scanner input, String[] names, int[] amounts) public static void
itemizedList (String[] names, double Prices int[] amounts) Fill-i public static double
calcSubTotal (double prices, int amounts return 0; pub. lic static int discount (double subTotal
return 0; pub. lic static oid print Total (double subTotal int discount) Fill-in public static void mi
args final int MAXCH EESEE DO NOT CHANGE ANYTHING BELOW String[] names new
String CMAXCH EESE double[] prices new double EESE] int[] amounts new int
[MAXCHEESEJ Scanner input new Scanner (Syste intro names, prices, amounts get Amo unt
input, names, amounts double total calcSubTotal (prices, amounts if EESEE 0) System. out print
Display the itemized list? (1 for yes) int itemized input-nex if item 1) itemized List (names,
prices, amounts); System. out. println(); print Total(total, discount total));
Solution
import java.util.Random;
import java.util.Scanner;
public class GenCheeseShopv2 {
public static void intro(String[] names, double[] prices,int[] amounts){
System.out.println(\"We sell \"+names.length+\" kinds of cheese\");
for(int i=0;i0)
System.out.println(amounts[i]+\" lbs of \"+names[i]+\" @ \"+prices[i]+\" =
$\"+(amounts[i]*prices[i]));
}
}
public static double calcSubTotal( double[] prices,int[] amounts){
double subTotal=0;
for(int i=0;i100)
return 10;
else if(subTotal > 50)
return 25;
else
return 0;
}
public static void printTotal(double subTotal,int discount){
System.out.println(\"Sub Total : $\"+subTotal);
System.out.println(\"-Discount : $\"+discount);
System.out.println(\"Total : $\"+(subTotal-discount));
}
public static void main(String[] args){
final int MAXCHEESES=4;
String[] names = new String[MAXCHEESES];
double[] prices = new double[MAXCHEESES];
int[] amounts = new int[MAXCHEESES];
Scanner input = new Scanner(System.in);
intro(names, prices, amounts);
getAmount(input, names, amounts);
double total = calcSubTotal(prices, amounts);
if(MAXCHEESES>0){
System.out.println(\"Display the itemized list? (1 for yes)\");
int itemized = input.nextInt();
if(itemized==1){
itemizedList(names, prices, amounts);
}
}
System.out.println();
printTotal(total, discount(total));
}
}.
More Related Content
Similar to C programming tweak needed for a specific program.This is the comp.pdf
Hi,Please fidn the Answer.Sorting,h is Header .pdfanandf0099
Hi,
Please fidn the Answer.
//////////////////Sorting,h is Header file which contians all Function decalartion
#include
#include // std::cout
#include // std::shuffle
#include // std::array
#include // std::default_random_engine
#include
using namespace std;
class Sorting
{
private:
int num;
public:
Sorting::Sorting() {
};
///Buble Sort Input array and n Number of Elemnets
void BubbleSorting(int array[], int n);
void SelectionSorting(int array[], int n);
void ShuffleArray(int array[], int n);
void DisplayArray(int array[], int n);
void displayMenu();
int choice;
};
//////////////////////////Sorting.cpp is class fuction Which Implemnets the Function
#include \"Sorting.h\"
#include
using namespace std;
///Sorting the Array Using Bubble Sort...
void Sorting::BubbleSorting(int Array[],int n)
{
int temp = 0;
cout << \"\ ------------ BUBBLE SORT ------------ \ \ \";
for (int i = 1; iArray[j + 1])
{
temp = Array[j];
Array[j] = Array[j + 1];
Array[j + 1] = temp;
}
}
cout << \"\ ------------ RESULTS BUBBLE SORT ------------ \ \ \";
DisplayArray(Array, n);
}
//////SelectionSorting input Array and n is number of Elemnets//////////////////////
void Sorting::SelectionSorting(int Array[], int n)
{
int i, n, p, k, min, loc, temp;
for (p = 1; p <= n - 1; p++) // Loop for Pass
{
min = Array[p]; // Element Selection
loc = p;
for (k = p + 1; k <= n; k++) // Finding Min Value
{
if (min > Array[k])
{
min = Array[k];
loc = k;
}
}
temp = Array[p]; // Swap Selected Element and Min Value
Array[p] = Array[loc];
Array[loc] = temp;
}
cout << \"\ ------------ RESULTS SELECTION SORT ------------ \ \ \";
DisplayArray(Array, n);
}
//////SelectionSorting input Array and n is number of Elemnets//////////////////////
///exchange each element with a randomly chosen element. It\'s possible that an element will be
exchanged with itself, but there is no problem with that
void Sorting::ShuffleArray(int Array[], int n)
{
cout << \"\ ------------ ShuffleArray SORT ------------ \ \ \";
for (int i = 0; i
#include \"Sorting.h\"
using namespace std;
int main()
{
bool SelectionOn = true;
Sorting Sorting;
int choice;
int n = 10;
int *Arry;
while (SelectionOn != false) {
cout << \"*******************************\ \";
cout << \" 1 - Enter User Input Array of Elements.\ \";
cout << \" 2 - Display User Input.\ \";
cout << \" 3 - Shuffle User Input the Elements i.\ \";
cout << \" 4 - Bubble Sorting.\ \";
cout << \" 5 - Selection Sorting.\ \";
cout << \" 6 - Exit.\ \";
cout << \" 7 - Display Menu Again. \ \";
cout << \" Enter your choice and press return: \";
cin >> choice;
switch (choice)
{
case 1:
cout << \"Enter User Input Array of Elements\ \";
cout << \"Enter No. of Elements=\";
cin >> n;
Arry = new int[n];
cout << \"\ Enter Elements=\ \";
for (int i = 1; i <= n; i++)
{
cin >> Arry[i];
}
break;
case 2:
cout << \"DISPLAY OF ARRAY\ \";
if (Arry != NULL)
{
Sorting.DisplayArray(Arry, n);
}
else
{
cout << \"ENTER ELEMENTS TO ARRAY BY SELCTING CHOICE 1\ \";
}
break;
case 3:
cout << \"SHUFFLE OF A.
-- Reminder that your file name is incredibly important- Please do not.docxAdamq0DJonese
// Reminder that your file name is incredibly important. Please do not change it.
// Reminder that we are compiling on Gradescope using GCC.
// READ BEFORE YOU START:
// You are given a partially completed program that creates a list of game items
like you'd see in a folder.
// Each item has this information: item's name, game's name, type of item, item ID.
// The struct 'itemRecord' holds information of one item. Variety is an enum.
// An array of structs called 'list' is made to hold the list of items.
// To begin, you should trace through the given code and understand how it works.
// Please read the instructions above each required function and follow the
directions carefully.
// You should not modify any of the given code, the return types, or the
parameters. Otherwise, you risk getting compilation errors.
// You are not allowed to modify main().
// You can use string library functions.
// WRITE COMMENTS FOR IMPORANT STEPS IN YOUR CODE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable: 4996) // for Visual Studio
Only
#define MAX_ITEMS 15
#define MAX_NAME_LENGTH 25
typedef enum { Health = 0, Equip, Etc } itemType; // enum type
struct itemRecord { // struct for item details
char itemName[MAX_NAME_LENGTH];
char gameName[MAX_NAME_LENGTH];
itemType variety;
unsigned int itemID;
};
struct itemRecord list[MAX_ITEMS]; // declare list of items
int count = 0; // the number of items
currently stored in the list (initialized to 0)
// functions already implmented
void flushStdIn();
void executeAction(char);
void save(char* fileName);
void display();
// functions that need implementation:
int add(char* itemName_input,
char* gameName_input,
char* variety_input,
unsigned int idNumber_input); // 10 points
void sort(); // 10 points
int delete(unsigned int idNumber_input); // 10 points
void load(char* fileName); // 10 points
int main()
{
char* fileName = "Item_List.txt";
load(fileName); // load list of items from
file (if it exists). Initially there will be no file.
char choice = 'i'; // initialized to a dummy
value
do
{
printf("\nEnter your selection:\n");
printf("\t a: add a new item\n");
printf("\t d: display item list\n");
printf("\t r: remove an item from list\n");
printf("\t s: sort item list by ID\n");
printf("\t q: quit\n");
choice = getchar();
flushStdIn();
executeAction(choice);
} while (choice != 'q');
save(fileName); // save list of items to file
(overwrites file, if it exists)
return 0;
}
// flush out leftover '\n' characters
void flushStdIn()
{
char c;
do c = getchar();
while (c != '\n' && c != EOF);
}
// ask for details from user for the given selection and perform that action
void executeAction(char c)
{
char itemName_input[MAX_NAME_LENGTH], gameName_input[MAX_NAME_LENGTH];
unsigned int idNumber_input, add_result = 0;
char variety_input[20];
switch (c)
{
case 'a':
// input item record from user
printf("\nEnter item name: ").
files/Heap.h
#ifndef HEAP_H
#define HEAP_H
#include <vector>
#include <stdexcept> // std::out_of_range
#include <math.h> // pow()
using namespace std;
template<typename T>
class Heap
{
private:
vector<T> _items; // Main vector of elements for heap storage
/**
* Used to take unsorted data and heapify it
*/
void buildHeap()
{
for (int i = _items.size() / 2; i >= 0; i--)
{
percolateDown(i);
}
}
/*********************************************************************/
/********************* Microassignment zone *************************/
/**
* Percolates the item specified at by index down
* into its proper location within a heap.
* Used for dequeue operations and array to heap conversions
* MA TODO: Implement percolateDown!
*/
void percolateDown(int index)
{
}
/**
* Percolate up from a given index to fix heap property
* Used in inserting new nodes into the heap
* MA TODO: Implement percolateUp
*/
void percolateUp( int current_position )
{
}
/************************** Microassigment zone DONE *********************/
public:
/**
* Default empty constructor
*/
Heap()
{
}
/**
* Constructor with a vector of elements
*/
Heap(const vector<T> &unsorted)
{
for (int i = 0; i < unsorted.size(); i++)
{
_items.push_back(unsorted[i]);
}
buildHeap();
}
/**
* Adds a new item to the heap
*/
void insert(T item)
{
int current_position = size(); // Get index location
_items.push_back(item); // Add data to end
percolateUp( current_position ); // Adjust up, as needed
}
/**
* Returns the top-most item in our heap without
* actually removing the item from the heap
*/
T& getFirst()
{
if( size() > 0 )
return _items[0];
else
throw std::out_of_range("No elements in Heap.");
}
/**
* Removes minimum value from heap and returns it to the caller
*/
T deleteMin()
{
int last_index = size() - 1; // Calc last item index
int root_index = 0; // Root index (for readability)
T min_item = _items[root_index]; // Keep item to return
_items[root_index] = _items[last_index]; // Move last item to root
_items.erase(_items.end() - 1); // Erase last element entry
percolateDown(0); // Fix heap property
return min_item;
}
/**
* Returns true if heap is empty, else false
*/
bool isEmpty() const
{
return _items.size() == 0;
}
/**
* Returns current quantity of elements in heap (N)
*/
int size() const
{
return _items.size();
}
/**
* Return heap data in order from the _items vector
*/
string to_s() const
{
string ret = "";
for(int i = 0; i < _items.size(); i++)
{
ret += to_string(_items[i]) + " ";
}
return ret;
}
/**
...
Write a program that converts an infix expression into an equivalent.pdfmohdjakirfb
Write a program that converts an infix expression into an equivalent postfix expression. The
rules to convert an infix expression into an equivalent postfix expression are as follows (C++):
Initialize pfx to an empty expression and also initialize the stack.
Get the next symbol, sym, from infx.
If sym is an operand, append sym to pfx.
If sym is (, push sym into the stack.
If sym is ), pop and append all of the symbols from the stack until the most recent left
parentheses. Pop and discard the left parentheses.
If sym is an operator:
Pop and append all of the operators from the stack to pfx that are above the most recent left
parentheses and have precedence greater than or equal to sym.
Push sym onto the stack.
After processing infx, some operators might be left in the stack. Pop and append to pfx
everything from the stack.
In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /.
You may assume that the expressions you will process are error free. Design a class that stores
the infix and postfix strings. The class must include the following operations:
getInfix: Stores the infix expression.
showInfix: Outputs the infix expression.
showPostfix: Outputs the postfix expression.
convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix
expression is stored in pfx.
precedence: Determines the precedence between two operators. If the first operator is of higher
or equal precedence than the second operator, it returns the value true; otherwise, it returns the
value false.
A + B - C;
(A + B ) * C;
(A + B) * (C - D);
A + ((B + C) * (E - F) - G) / (H - I);
A + B * (C + D ) - E / F * G + H;
Infix Expression: A+B-C;
Postfix Expression: AB+C-
Infix Expression: (A+B)*C;
Postfix Expression: AB+C*
Infix Expression: (A+B)*(C-D);
Postfix Expression: AB+CD-*
Infix Expression: A+((B+C)*(E-F)-G)/(H-I);
Postfix Expression: ABC+EF-*G-HI-/+
Infix Expression: A+B*(C+D)-E/F*G+H;
Postfix Expression: ABCD+*+EF/G*-H+
Turn in:
A UML diagram for your class.
The header file for your class.
The implementation file for your class.
The source code for your test program. (C++)
(Below already done code.)
//Header file: myStack.h
#ifndef H_StackType
#define H_StackType
#include
#include
#include \"stackADT.h\"
using namespace std;
template
class stackType: public stackADT
{
public:
const stackType& operator=(const stackType&);
//Overload the assignment operator.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: stackTop = 0
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
void push(const Type& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postc.
Symfony World - Symfony components and design patternsŁukasz Chruściel
There are so many Symfony components already, and they have some pretty neat perks. But have you seen them in action?
Design patterns are not a silver bullet. They will never resolve your problem on their own. On the other hand, design patterns provide a common ground for developers without going into details and could be used as building bricks to solve some more advanced problems.
During my presentation, I will take a closer look and explain the appliance of selected design patterns. What is more, I will take advantage of the Symfony ecosystem to implement them with ease.
I will do the presentation on sample code that developers will understand at all levels of expertise.
The purpose of this C++ programming project is to allow the student .pdfRahul04August
The purpose of this C++ programming project is to allow the student to perform parallel array
and multidimensional array processing. The logic for string and Cstring has already been
completed, so the assignment can be started before we actually cover string and Cstring in detail.
This program has the following three menu options:
Solution
/*
This program uses simple arrays, multidimensional arrays, cstrings, strings, and files.
It allows a payroll clerk to choose an option from a menu. The choices are:
A: List the Payroll Information by Employee Name
B: Search Payroll Information by Employee Name
X: Exit the Payroll Information Module
The following items for each employee are saved in the file p10.txt:
Employee ID (1000 - 9999)
Last Name (15 characters)
First Name (15 characters)
Rate (5.00 - 10.00)
Hours W1,W2,W3,W4 (0-60)
*/
#include // file processing
#include // cin and cout
#include // toupper
#include // setw
#include // cstring functions strlen, strcmp, strcpy stored in string.h
#include // string class
#define stricmp strcasecmp
#define strnicmp strncasecmp
using namespace std;
//Disable warning messages C4267 C4996.
//To see the warnings, comment out the following line.
//#pragma warning( disable : 4267 4996)
//Warning C4267: coversion from size_t to int, possible lost of data
//size_t is a data type defined in and is an unsigned integer.
//The function strlen returns a value of the type size_t, but in
//searchByName we assign the returned value to an int.
//We could also declare the variable as size_t instead of int.
// size_t stringLength;
//Warning C4996: strnicmp strcpy, stricmp was declared deprecated, means
//the compiler encountered a function that was marked with deprecated.
//The deprecated function may no longer be supported in a future release.
//Global Constants
//When using to declare arrays, must be defined with const modifier
const int ARRAY_SIZE = 20, HOURS_SIZE = 4, NAME_SIZE = 16;
//Declare arrays as global so we don\'t have to pass the arrays to each function.
//Normally we wouldn\'t declare variables that change values a global.
int employeeId[ARRAY_SIZE];
string firstName[ARRAY_SIZE];
char lastName[ARRAY_SIZE][NAME_SIZE];
double rate[ARRAY_SIZE];
int hours[ARRAY_SIZE][HOURS_SIZE];
int numberOfEmps; //count of how many employees were loaded into arrays
int sumHours[ARRAY_SIZE] = {0}; //initialize arrays to zero by providing a
double avgHours[ARRAY_SIZE] = {0}; //value for the first element in the array
//Function Prototypes
void loadArray( );
void sumAndComputeAvgHours( );
void listByName( );
void searchByName( );
void sortByName( );
void swapValues(int i, int minIndex);
void listEmployees( );
void listEmployeesHeadings( );
void listEmployeesDetails(int i);
void listEmployeesTotals( );
void displayContinuePrompt( );
//Program starts here
int main()
{
//Declare and initialize local main variables
char choice; //menu option
//Load the arrays with data
loadArray();
//Sum and compute the average hours
sumAndComputeAv.
Similar to C programming tweak needed for a specific program.This is the comp.pdf (20)
How does the mutation rate of speciation in the Dobzhansky- Muller m.pdfflashfashioncasualwe
How does the mutation rate of speciation in the Dobzhansky- Muller model? How does the
mutation rate affect the rate of speciation in the Dobzhansky Muller model? An increased
mutation rate results in a more rapid reproductive isolation between the two diverging
populations. O An increased mutation rate results in slower reproductive isolation between the
two diverging populations. The mutation rate is unrelated to the rate of evolution of reproductive
isolation.
Solution
ans- a increased mutation rate results in a more reproduction isolation between the two diverging
population.
an ancestral population splits into two parts the two lineage begins to diverge genetically which
are temporally isolated from each other.new alleles evolved at one locus of lineage and different
alleles evolved in another locus of the lineage..
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdfflashfashioncasualwe
Hello. I need help fixing this Java Code on Eclipse. Please fix parts indicated as \"//Fix\" or
\"//Fill-in\". The code given is the first image. Thank you! Sample outputs are given below along
with what the code is required to do. import java til. Random import java til. Scanner public class
GenCheeseShopv2 public static void intro (Stringt] names, double []prices int amounts Fill-in
public static void getAmount (Scanner input, String[] names, int[] amounts) public static void
itemizedList (String[] names, double Prices int[] amounts) Fill-i public static double
calcSubTotal (double prices, int amounts return 0; pub. lic static int discount (double subTotal
return 0; pub. lic static oid print Total (double subTotal int discount) Fill-in public static void mi
args final int MAXCH EESEE DO NOT CHANGE ANYTHING BELOW String[] names new
String CMAXCH EESE double[] prices new double EESE] int[] amounts new int
[MAXCHEESEJ Scanner input new Scanner (Syste intro names, prices, amounts get Amo unt
input, names, amounts double total calcSubTotal (prices, amounts if EESEE 0) System. out print
Display the itemized list? (1 for yes) int itemized input-nex if item 1) itemized List (names,
prices, amounts); System. out. println(); print Total(total, discount total));
Solution
import java.util.Random;
import java.util.Scanner;
public class GenCheeseShopv2 {
public static void intro(String[] names, double[] prices,int[] amounts){
System.out.println(\"We sell \"+names.length+\" kinds of cheese\");
for(int i=0;i0)
System.out.println(amounts[i]+\" lbs of \"+names[i]+\" @ \"+prices[i]+\" =
$\"+(amounts[i]*prices[i]));
}
}
public static double calcSubTotal( double[] prices,int[] amounts){
double subTotal=0;
for(int i=0;i100)
return 10;
else if(subTotal > 50)
return 25;
else
return 0;
}
public static void printTotal(double subTotal,int discount){
System.out.println(\"Sub Total : $\"+subTotal);
System.out.println(\"-Discount : $\"+discount);
System.out.println(\"Total : $\"+(subTotal-discount));
}
public static void main(String[] args){
final int MAXCHEESES=4;
String[] names = new String[MAXCHEESES];
double[] prices = new double[MAXCHEESES];
int[] amounts = new int[MAXCHEESES];
Scanner input = new Scanner(System.in);
intro(names, prices, amounts);
getAmount(input, names, amounts);
double total = calcSubTotal(prices, amounts);
if(MAXCHEESES>0){
System.out.println(\"Display the itemized list? (1 for yes)\");
int itemized = input.nextInt();
if(itemized==1){
itemizedList(names, prices, amounts);
}
}
System.out.println();
printTotal(total, discount(total));
}
}.
Focus on Writing 4. Supporting a Point of View Do you think Social Se.pdfflashfashioncasualwe
Focus on Writing 4. Supporting a Point of View Do you think Social Security has encouraged
Americans to become too dependent on the state and federal governments for support in times of
need? Write a paragraph explaining your answer.
Solution
ANSWER:
In America, Social Security is the often used term for the federal Survivors, Old-Age, and
Disability Insurance (OASDI) program. Yes, I think social security has encouraged Americans to
become too dependent for their security solely on earnings from employment. The reasons are:
--Social Security, providing education or other assistance support, once considered to be the
responsibility of individuals, families, churches, neighbourhoods, and other civil society
institutions is rising thus reflecting that America is building a dependency culture , with ever-
more people relying on an ever-growing federal government to provide them benefits or cash.
--Industrialization caused the migration of people toward centres of work, therefore separating
children from the support provided by the wider family. Moreover, the development of
compulsory education prolonged the period during which kids were dependent on the parents.
--U.S. system developed enforced retirement and created too much dependency. Most retirees
rely on long-term care in assisted home health care providers or living facilities under Medicaid.
--Social Security has greatly encroached on the responsibility of people for giving their own
retirement funds, thus leaving millions of retirees dependent on working younger generations to
fund their retirement..
Decision-Making Across the Organization The board of trustees of a lo.pdfflashfashioncasualwe
Decision-Making Across the Organization The board of trustees of a local church is concerned
about the internal accounting controls for the offering collections made at weekly services. The
trustees ask you to serve on a three-person audit team with the internal auditor of a local college
and a CPA who has just joined the church. At a meeting of the audit team and the board of
trustees, you learn the following 1. The church\'s board of trustees has delegated responsibility
for the financial management and audit of the financial records to the finance committee. This
group prepares the annual budget and approves major disbursements. It is not involved in
collections or recordkeeping. No audit has been made in recent years because the same trusted
employee has kept church records and served as financial secretary for 15 years. The church does
not carry any fidelity insurance 2. The collection at the weekly service is taken by a team of
ushers who volunteer to serve one month. The ushers take the collection plates to a basement
office at the rear of the church. They hand their plates to the head usher and return to the church
service. After all plates have been turned in, the head usher counts the cash received. The head
usher then places the cash in the church safe along with a notation of the amount counted. The
head usher volunteers to serve for 3 months 3. The next morning, the financial secretary opens
the safe and recounts the collection. The secretary withholds $150-$200 in cash, depending on
the cash expenditures expected for the week, and deposits the remainder of the collections in the
bank. To facilitate the deposit, church members who contribute by check are asked to make their
checks payable to \"Cash.\" Each month, the financial secretary reconciles the bank statement
and submits a copy of the reconciliation to the board of trustees. The reconciliations have rarely
contained any bank errors and have never shown any errors per books. 4. Instructions With the
class divided into groups, answer the following. Indicate the weaknesses in internal accounting
control over the handling of collections. List the improvements in internal control procedures
that you plan to make at the next meeting of the audit team for (1) the ushers, (2) the head usher,
(3) the financial secretary, and (4) the finance committee What church policies should be
changed to improve internal control?
Solution
(a) The primary weakness in internal accounting control with regards to handling of collections
starts with the weakness that the church has not undertaken an audit in recent years. An audit
should have been done regardless of the trustworthiness of its employees and regardless of their
tenure at the church. Secondly the church does not have fidelity insurance and this can possibly
lead to a situation in which the church will not be able to negate its loss in case of any occurrence
of fraud.
Another weakness in internal control is with regards to passing of th.
Explain the experience of African-Americans in the South over the co.pdfflashfashioncasualwe
Explain the experience of African-Americans in the South over the course of the half-century
following the Civil War.
How did an interracial democracy in the South come to be a plausible goal for a time? Why was
this goal not realized?
Why did sharecropping become the dominant form of black labor by the end of Reconstruction
and why was the white South able to impose a “Jim Crow” style of segregation, even as it was
disfranchising the overwhelming majority of black men?
Solution
1.
Post civil war the African Americans faced a lot of troubles like : Destruction, hunger,
lawlessness and violence amongst others.
after the civil war many of the african americans came out out slavery and were refugees and
they did not kenw what to do next.But when they arrived home, they found a strange new world
waiting for them..
During a diversity management session, a manager suggests that stereo.pdfflashfashioncasualwe
During a diversity management session, a manager suggests that stereotypes are a necessary part
of working with others. \"I have to make assumptions about what\'s in the other person\'s head,
and stereotypes help me do that,\" she explains. \"It\'s better to rely on stereotypes than to enter a
working relationship with someone from another culture without any idea of what they believe
in!\" Discuss the merits of and problems with the manager\'s statement.
Solution
The manager statement highlights her viewpoint on the benefits of stereotypes in a diverse
working environment. Below are merits and problems of her statement -
Merits
1. Individuals from different cultures hold a viewpoint regarding one another through stereotypes
2. It becomes easy to initiate the communication among individuals by having a viewpoint rather
than having nothing
3. As individuals start interaction and communication with stereotypes in minds, they will be
careful in how to communicate with others without hurting their sentiments.
Problems
1. Stereotype is the most common opinion about a culture or group based on historical references
that are in the news. Hence, they will not provide a clear viewpoint on the individuals.
2. Stereotypes usually carry viewpoints that oversimplify an individual\'s personality and
character based on his/her culture or origin thus resulting in hurting the individual who might be
quite different from the stereotype.
3. It becomes difficult to change the opinion about an individual if viewed through stereotype..
Explain why a mycoplasma PCR kit might give a negative result when u.pdfflashfashioncasualwe
Explain why a mycoplasma PCR kit might give a negative result when used to test for
mycoplasma in a cell line containing mycoplasma
Solution
Mycoplasma is a prokaryotic organism that is a frequent and occult contaminant of cell cultures.
This organism can modify many aspects of cell physiology, rendering experiments that are
conducted with contaminated cells worthless. Because of their small size, Mycoplasma can pass
through filters used to prevent bacterial and fungal contamination and potentially spread to all
the cultures in a laboratory. It is essential that all new cell cultures entering a laboratory and all
cell banks are tested for presence of Mycoplasma. It is recommended that two techniques be
used, selected from a PCR-based methos, indirect staining and an agar and broth culture. These
three tests for detecting Mycoplasma take one day to 3-4 weeks and such tests should be an
obligatory component of quality control in every tissue culture laboratory.
Mycoplasma refers to any of over 200 species of tiny bacteria that invade cell cultures and may
even persist unrecognized for some time. They can come from sources as mundane as other cells
introduced to lab via media, sera or lab personnel. So, it is important to test your cell lines for
mycoplasma regularly. Consequences to your cells of mycoplasma infestation include changes in
growth rates, gene expression, morphology, metabolism and viability.
Even though most lab contamination can be blamed on as few as eight main culprit species, these
differ enough that no one test can find them all. And the little blighters are hardy – most
antibiotics used in cell culture are ineffective against mycoplasmas. For example, mycoplasmas
lack a cell wall, which is the key to penicillin’s success. Flawless cell culture technique is one of
the best preventive tools and testing to ascertain which cultures are clean and which cultures are
infected – so you can take quick and aggressive action before infestation spreads.
The M.hyorhinis strain is picked up by the PCR method of detection. This is the quickest but
also the least sensitive, mycoplasma assay. In this method, you perform PCR on samples of your
suspected cell cultures, using primers specific for mycoplasma DNA, usually mycoplasma’s 16S
rRNA genes. Running the PCR product on a gel shows presence of mycoplasma DNA by bands
of distinct sizes.
One major limitation of PCR is that prior information about target sequence is necessary in order
to generate the primers that will allow its selective amplification. This means that, typically, PCR
users must know precise sequences upstream of target region on each of the two single-stranded
templates in order to ensure that DNA polymerase properly binds to primer-template hybrids and
subsequently generates entire target region during DNA synthesis. Like all enzymes, DNA
polymerases are also prone to error, which in turn causes mutations in PCR fragments that are
generated. Specificity of PCR fragments can .
Describe the difference between the MOV instruction and the LEA instr.pdfflashfashioncasualwe
Describe the difference between the MOV instruction and the LEA instruction as used in these
two sample instructions. MOV D, V1 LEA DX, V1
Solution
Answer:
MOV D , V1 it moves the D to V1 and the instruction LEA DX V1 moves the address of the data
to V1 . There is no difference between MOV and LEA but LEA can be more powerful than
MOV if we need to calculate the address..
Explain how enzymes work, explaining the four major types of metabol.pdfflashfashioncasualwe
Explain how enzymes work, explaining the four major types of metabolic reactions enzymes
perform. Include: (Metabolism, catabolism, anabolism, substrate product, active site, induced fit,
competative and non competative inhibitors, allosteric regulation, cofactors and coenzymes,
hydrolysis and dehydration reactions, Redox Reactions, NADH, FADH2, phosphorylation,
exergonic/ endergonic reactions, ATP, isomerization reactions, feedback inhibition)
Solution
Enzymes are biological molecules (typically proteins) that significantly speed up the rate of
virtually all of the chemical reactions that take place within cells.
They are vital for life and serve a wide range of important functions in the body, such as aiding
in digestion and metabolism. Substrate binding[edit]
Enzymes must bind their substrates before they can catalyse any chemical reaction. Enzymes are
usually very specific as to what substrates they bind and then the chemical reaction catalysed.
Specificity is achieved by binding pockets with complementary shape, charge and
hydrophilic/hydrophobic characteristics to the substrates. Enzymes can therefore distinguish
between very similar substrate molecules to be chemoselective, regioselective and stereospecific.
Some of the enzymes showing the highest specificity and accuracy are involved in the copying
and expression of the genome. Some of these enzymes have \"proof-reading\" mechanisms.
Here, an enzyme such as DNA polymerase catalyzes a reaction in a first step and then checks
that the product is correct in a second step. This two-step process results in average error rates of
less than 1 error in 100 million reactions in high-fidelity mammalian polymerases.:5.3.1 Similar
proofreading mechanisms are also found in RNA polymerase, aminoacyl tRNA synthetases and
ribosomes.
Conversely, some enzymes display enzyme promiscuity, having broad specificity and acting on a
range of different physiologically relevant substrates. Many enzymes possess small side
activities which arose fortuitously (i.e. neutrally), which may be the starting point for the
evolutionary selection of a new function.
Enzyme changes shape by induced fit upon substrate binding to form enzyme-substrate complex.
Hexokinase has a large induced fit motion that closes over the substrates adenosine triphosphate
and xylose. Binding sites in blue, substrates in black and Mg2+ cofactor in yellow. (PDB: 2E2N,
2E2Q)
\"Lock and key\" model
To explain the observed specificity of enzymes, in 1894 Emil Fischer proposed that both the
enzyme and the substrate possess specific complementary geometric shapes that fit exactly into
one another.This is often referred to as \"the lock and key\" model:8.3.2 This early model
explains enzyme specificity, but fails to explain the stabilization of the transition state that
enzymes achieve.
Induced fit model
In 1958, Daniel Koshland suggested a modification to the lock and key model: since enzymes are
rather flexible structures, the active site is conti.
Develop an inventory management system for an electronics store. The .pdfflashfashioncasualwe
Develop an inventory management system for an electronics store. The inventory system should
have the following functionalities .BuildInventory: reada text file containing electronics products
information and store them in an array of pointers .Shownventory display all inventory items
.ShowDefectInventory: display inventory items that are defective Terminate: to save cument
inventory to a text file This lab assignment illustrates the following concepts: -Text file readings
and writings .Arrays of pointers and dynamic memory allocations with new and delete
Inheritance .C++ type casting: static cast Class Design You need at least three classes class
Inventory System: (minimum implementation specified below). This class stores Inyentoryltem
objects (which are in fact Inventory item base class pointers to derived Product objects and
member functions to manipulate those Product objects as shown below. .Private data members
Store Name Store ID ltem List (array of pointers to Inventory Item objects, max of 512) ltem
Count (tracking how many items are currently stored in the array) .Constructors (initialize all
pointers in the array to NULL in addition to what\'s described below .Default constructor: set
data members to 0 (for integers), 0.0 (for float/double), or NULL (for pointers) as appropriate.
Also invoke this function to initialize a seed for the random generator srand (time (NULL), (to
be used later by Product class to genearte random values for Product ID. See Code Helper
section at the end of the lab specs.) .Non-default constructor: taking a string for store name, an
integer for store ID. Call srand as shown above Destructor: de-allocate dynamic memory in the
amay off pointers (up to Item Count elements) .Public member functions: BuildInventory: read a
text file containing Product records (one Product per line), dynamically allocate Product objects
and store the objects in the array ItemList (an array of Inventoryltem pointers). It should also
update Item Count as needed Shownventory: display all Products in the inventory. Output must
be properly formatted and aligned (usingfield with and floating data with 2 digits after decimal
point). Note that if you invoke the Display function using the pointers from the array only Invent
tem (base objec) information will be displayed. Extra work is needed to properly display
Products (derived objects) information ntory: display only defective Products Terminate: iterate
thru the array of pointers to write Product objects in the array to a text file in the same format as
they were read in. You may use a different file name for wniting .mutator cessors for store name,
store id, and item count
Solution
/*
import com.incors.plaf.*;
import com.incors.plaf.kunststoff.*;
import com.incors.plaf.kunststoff.themes.*;
*/
public class MainForm extends JFrame implements WindowListener{
/************************ Variable declaration start **********************/
//The form container variable
JPanel Panel1;
JDeskto.
Describe one event from your daily life when you have changed your o.pdfflashfashioncasualwe
Describe one event from your daily life when you have changed your original attitude, and one
event when you could not change your original attitude. For the event when you changed your
original attitude, explain how you changed your attitude and what led to the change. For the
event when you could not change your original attitude, explain what did not work. Submission
Requirements: Submit your responses in a Microsoft Word document of the following
specifications:•Font: Arial; 12-Point •Line Spacing: Double •Length: 300–500 words Evaluation
Criteria:•Did you describe one event from your daily life when you have changed your original
attitude? •Did you describe one event from your daily life when you have not changed your
original attitude? •Did you explain how you changed your attitude and what led to the change?
•Did you explain what did not work when you could not change your original attitude? •Did you
provide your answers in complete sentences with few grammatical errors?
Solution
Instance where I changed my Attitude -
I don\'t believe in charity and philanthropy. I had this firm belief that money given to NGOs and
trusts in grants is mis-used. I always believed in commercial models and never realized that
texcept for a few most of development agencies are working for the welfare of people.
When I came acrossNanhi Kali NGO which works for girl child education I was sure that this is
another fraud NGOs which improperly utilizes the money earned in grant. But when I visited the
centre and saw the real impact on ground then my eyes remained wide open. They were doing
awesome work and even there financial statements were also showing this. This instance
changed my attitude towards NGOs.
What made me Change -
The critical factor which made me change my attitude is my interaction with foundation and
meeting with a few girls who really got benefits from the activities of NGO. The interaction
helped me understand their model in a better way. When I analyzed their financials I realized
that manpower is working at half the salaries and highly motivated and focused towards the
cause. This all made me change my attitude.
Instance Where my attitude remained same -
Based on the learnings from my experiences in past I believed that people in politics are not
good at heart. Politicians should ideally be social worker and should have a motive of public
welfare but noboday remember their promises once elected. I always had this image of politicans
in mind. A lot of people tried to convince me that new breed of politicans are good and not
greedy but I remained and still firm on my attitude that all politicans are not good people.
Reasons behind my attitude -
This attitude had been built over a period of time. There is no substantial argument against my
attitude which can make me think. This is why I still beleive that none of the politician is good
person..
All answers must be in your own wordsProvide a good, understandabl.pdfflashfashioncasualwe
All answers must be in your own words
Provide a good, understandable definition of the following 40, using your own words (do not
simply copy words from the book).
Retaliation Blood feud
Vendetta Civil death
Inquisition Corporal punishment
Brank Criminology
Mamertine Prison Sanctuary
Bridewell Jail fever
Age of Enlightenment Classical School of Criminology
Workhouse Gaols
Banishment Transportation
Hulks Penitentiary
Pennsylvania System Outside cell
Inside cell Eastern Penitentiary
Auburn System Cell block
Congregate system System of silence
Lockstep formation Prison stripes
Treadmill Solitary confinement
Indeterminate sentence Irish system
Reformatory Industrial prison
Alcatraz Lock psychosis
Convict bogey Ombudsman
Ticket of Leave
Solution
Retaliation – In the event of attack by the enemy, do the fierce counter attack from our side.
Blood feud – It is lengthy fighting in the families going on for the generations. It involves killing
of various members of the families. Vendetta – Person whose relative has been killed seeks
revenge from the murderer. Civil death – It is the loss of the civil rights which is the result of act
of government in the some of conviction of civil people. Inquisition – Out of curiosity asking
many question on the related topic. Corporal punishment – It is the type of punishment which
involves physical pain. It involves mutilation, flogging branding etc. Brank – It is the birdcage-
like instrument put on prisonr’s head with sharp plates that would cut tongues and mouths once
involved in the gossips Criminology – This is the branch of science which involves study of
crime and criminals. Mamertine Prison – In the early age in the Rome confinement are under the
main sewers where survival is very difficult even for few days.. Sanctuary – It means taking
shelter or refuge from the danger or pursuit. Bridewell – It is called for city jail or reform center
or jail for pity offender. Jail fever – It is the former name to the typhus. It is commonly occurred
in the jail so got he name from its origin. Age of Enlightenment – European politics, philosophy,
science and communications were radically reoriented during beginning of the 18th century and
then throughout of the 18th century. This period is known as Age of Enlightenment. Classical
School of Criminology – It is the body of thought which understands the nature of crime and
suggests the best form of punishment to the crime. Looking at the severity of the punishment in
the early 18th century philosopher come up with this type of thoughts. Workhouse – It is the
place where unemployed people who can not support themselves were given shelter and
employment. Gaols – It the synonym to the jail. It is the place of confinement to the criminals.
Banishment – As an act of punishment offender are sent away from the designated place or
country known as banishment. Transportation – It is the act of movement of goods or people
from one place to another place. Hulks – It is an old ship whi.
Add to BST.java a method height() that computes the height of the tr.pdfflashfashioncasualwe
Add to BST.java a method height() that computes the height of the tree. Develop two
implementations: a recursive method (which takes linear time and space proportional to the
height), and method like size() that adds a field to each node in the tree (and takes linear space
and constant time per query)
Solution
Answer:
/*BST.java a method height() that computes the height of the tree. Developing two
implementations: a recursive method, and method like size() that adds a field to each node in the
tree **/
public class SplayBST, Value> {
private Node root; // root of the BST
// BST helper node data type
private class Node {
private Key key; // key
private Value value; // associated data
private Node left, right; // left and right subtrees
public Node(Key key, Value value) {
this.key = key;
this.value = value;
}
}
public boolean contains(Key key) {
return get(key) != null;
}
// return value associated with the given key
// if no such value, return null
public Value get(Key key) {
root = splay(root, key);
int cmp = key.compareTo(root.key);
if (cmp == 0) return root.value;
else return null;
}
/*
* Splay tree insertion.
**/
public void put(Key key, Value value) {
// splay key to root
if (root == null) {
root = new Node(key, value);
return;
}
root = splay(root, key);
int cmp = key.compareTo(root.key);
// Insert new node at root
if (cmp < 0) {
Node n = new Node(key, value);
n.left = root.left;
n.right = root;
root.left = null;
root = n;
}
// Insert new node at root
else if (cmp > 0) {
Node n = new Node(key, value);
n.right = root.right;
n.left = root;
root.right = null;
root = n;
}
// It was a duplicate key. Simply replace the value
else {
root.value = value;
}
}
/*
* Splay tree deletion.
**/
/*
*This splays the key, then does a slightly modified Hibbard deletion on the root (if it is the node
to be deleted, if it is not, the key was not in the tree).
*The modification is that rather than swapping the root (call it node A) with its successor, it\'s
successor (call it Node B) is moved to the root position
*by splaying for the deletion key in A\'s right subtree. Finally, A\'s right child is made the new
root\'s right child.
*/
public void remove(Key key) {
if (root == null) return; // empty tree
root = splay(root, key);
int cmp = key.compareTo(root.key);
if (cmp == 0) {
if (root.left == null) {
root = root.right;
}
else {
Node x = root.right;
root = root.left;
splay(root, key);
root.right = x;
}
}
// else: it wasn\'t in the tree to remove
}
/*
* Splay tree function.
**/
// splay key in the tree rooted at Node h. If a node with that key exists,
// it is splayed to the root of the tree. If it does not, the last node
// along the search path for the key is splayed to the root.
private Node splay(Node h, Key key) {
if (h == null) return null;
int cmp1 = key.compareTo(h.key);
if (cmp1 < 0) {
// key not in tree, so we\'re done
if (h.left == null) {
return h;
}
int cmp2 = key.compareTo(h.left.key);
if (cmp2 < 0) {
h.left.left = splay(h.left.left, key);
h = rot.
Write an awareness objective for a newly formed adolescent chemical .pdfflashfashioncasualwe
Write an awareness objective for a newly formed adolescent chemical dependency program
whose target market consists of judeges and social workers who refer to the facility. How would
this objective change for the trial level of the hierarchy of effects?
Solution
Answer:
The objectives are:
1. To create primary level awareness to the people who uses this service frequently and also
those who refer our facility,
2. To find out the ways to help people in different situations and making an sustainable
ecosystem.
This objective (twin objectives) would become altered in case of implementation of them in real
situation..
which of these prokaryotes are most likely to be found in the immedi.pdfflashfashioncasualwe
which of these prokaryotes are most likely to be found in the immediate vicinity of active deep-
sea vents?
a) cynobacteria
b)archaea
c)aerobically respiring bacteria
d)bacteria adapted to being embedded in ice
Solution
The answer is Archaea
as they are the thermophilic anaerobes which do not depend on oxygen for survival..
2. Why is only one end point observed for citric acid even though it .pdfflashfashioncasualwe
2. Why is only one end point observed for citric acid even though it is a triprotic acid?
Solution
Citric acid has three relatively similar dissociation constants, but instead of giving three (or at
least two) separate end points, it has , only one end point at which buffering effect of the first and
second dissociation steps doesn\'t allow for fast rise of pH. Hence it has only one end point..
10. Benefits and costs of International Trade Search for a newspap.pdfflashfashioncasualwe
10. Benefits and costs of International Trade : Search for a newspaper article from any English
newspaper that discusses the advantages or disadvantages of international trade. Copy and paste
the weblink into this Forum and discuss one or two main points of the article. Please give
detailed answer with examples and elaborations.
Solution
The web is a awesome invention. Since of its introduction into schooling and its availability to
just about any individual, the world will mainly never be the identical.
Persons of all a while can go surfing 24/7 looking for something they want. The elderly woman
who\'s unable to drive can log onto the web and shop for groceries, fill a prescription or even
chat together with her grandchildren via web cam.
Collectors now not have got to scour flea markets and yard revenue on weekends to find coveted
gadgets so as to add to their collections all they need to do is go browsing to Ebay and publish a
bid. Something can be purchased on line now. Garb, jewellery, furniture...Even take-out.
As a instructor i\'ve discovered the web to be extremely valuable in planning classes. The web
has a plethora of websites created in particular for lecturers to share suggestions, change
information, and share records (thanks enotes!). Probably young people stand to gain the most
from making use of the web. Additionally to being in a position to express themselves and show
creativity on websites like MySpace and Twitter, they can also use the web for school tasks and
homework.
Still, for every pro, there is a con. I feel that scholars regularly count too much in the internet.
They do not look to have an understanding of that simply considering the fact that some thing is
on Google, that does not make it a riskless supply. I are not able to depend the number of
occasions a scholar has became in an essay that includes unsuitable data from web sites which
were created with the aid of any person who is not an authority on the topic.
Chat rooms have emerge as the brand new playground for sexual predators. The web gives them
the anonymity they have got to entice unsuspecting youngsters into inappropriate conversations
and in some circumstances meeting up with them. There are laws that preserve predators far
from parks and schools, however none retaining them off the web.
With out suitable supervision, kids can accidentally go online to pornographic web pages. Even
adults can fall prey to identity theft and stolen passwords if they don\'t seem to be careful about
the matters they are downloading onto their laptop.
Advantages and drawbacks of web use amongst kids and adults can be considered from quite a
lot of angles - objectively, or subjectively. If a individual is in favor of science, then he/she
would find extra advantages than negative aspects for its use. However, if a man or woman
believes in guide work and that technology could one day be used to replace human work, then
the he/she may just view web use to be more damaging than .
Why does the pattern in a shift register shift only one bit position.pdfflashfashioncasualwe
Why does the pattern in a shift register shift only one bit position each time it is clocked?
please no hand written answers
Solution
Beacuse if we move all bits at a time there will be no buffers to store the bits temporarily and
then shift the data to next position for each bit.
Hence , first Least significant bit(LSB) is moved out the the others follow for each step upto the
MSB most significant bit is moved by one bit position..
Use the Internet to identify three network firewalls, and create a t.pdfflashfashioncasualwe
Use the Internet to identify three network firewalls, and create a table that compares their
features. Note if they are rule-based or settings-based, perform stateless or stateful packet
filtering, what additional features they include (IDS, content filtering, and so on), their costs, and
so on.
Solution
Below is the table :
Firewall Capability
Packet Filters
Application-layer Gateways
Stateful Inspection
Communication Information
Partial
Partial
Yes
Communication-derived State
No
Partial
Yes
Application-derived State
No
Yes
Yes
Information Manipulation
Partial
Yes
Yes
If you take packet filters, for example, historically they are implemented on routers, are filters on
user defined content, such as IP addresses. packet filters examine a packet at the network layer
and are application independent, which allows them to deliver good performance and
scaleability. However, they are the least secure type of firewall, especially when filtering
services such as FTP.
As with application gateways, he security is improved by examining all application layers,
bringing context information into the decision process. However, they do this by breaking the
client/server model. Every client/server communication requires two connections: one from the
client to the firewall and one from the firewall to the server. In addition, each proxy requires a
different application process, or daemon, making scaleability and support for new applications a
problem.
The Stateful Inspection introduced by Check Point overcomes the limitations of the previous two
approaches by providing full application-layer awareness without breaking the client/server
model. With Stateful Inspection, the packet is intercepted at the network layer. It extracts state-
related information required for the security decision from all application layers and maintains
this information in dynamic state tables for evaluating subsequent connection attempts. This
provides a solution which is highly secure and offers maximum performance, scaleability, and
extensibility.
Firewall Capability
Packet Filters
Application-layer Gateways
Stateful Inspection
Communication Information
Partial
Partial
Yes
Communication-derived State
No
Partial
Yes
Application-derived State
No
Yes
Yes
Information Manipulation
Partial
Yes
Yes.
To vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdfflashfashioncasualwe
To vaccinate or not to vaccinate: Is the influenza Virus vaccine Safe? Who should be
vaccinated? Are you planning to get a flu-shot? Are you going to encourage your family
members to get a flu-shot?
Solution
Influenza is the respiratory illness caused by influenza virus.This virus can cause mild to severe
illness and finally leads to death. So inorder to avoid such a bad condition,vaccination should be
done for our body for every 6 months or atleast once in a year. Influenza is also known as \"flu\"
which infects the respiratory tract ie., nose,throat and lungs.The name of influenza vaccine is
also called as FLUZONE which saves us from influenza virus. Yes am planning to get a flu shot
because i dont want to risk my life by getting viral diseases and i also encourage my family
members to have a flu-shot because not only myself, i also want my family members to say away
from viral diseases. So i suggest my family members to have a flu-shot for every 6 months or
once in a year..
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
C programming tweak needed for a specific program.This is the comp.pdf
1. C programming tweak needed for a specific program.
This is the complete program up and running. except for one modification that my teacher is
requiring but it is confusing me.
The program needs to allocate disjoint memory and use that.
right now im allocating a continous block of memory on the heap but I need it to do disjoing
memory instead.
// Purpose: Program will allow a reseller to save their sales and calculate their profits.
// Also able to view highest profitable items and remove any sales they no longer want in their
sales inventory.
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#define PAUSE system("pause")
#define CLS system("cls");
//#define FLUSH fflush(stdin);
//////////////// SRUCTS BELOW //////////////////////////
typedef struct
{
char itemName[40];
float purchasePrice;
float soldPrice;
float shippingPrice;
float ebayFee;
float payPalFee;
float profit;
}SALES;
////////// FUNCTION PROTOTYPE BELOW /////////////
void addSale(SALES *Inventory, int *InventoryCounter);
void displayMenu(int *InventoryCounter);
void displayProfit(int *InventoryCounter, SALES *Inventory);
2. void displaySales(int *InventoryCounter, SALES *Inventory);
int getChoice(int *InventoryCounter);
void searchSale(SALES* Inventory, int InventoryCounter);
void sortProfits(SALES* Inventory, int InventoryCounter);
void removeSale(SALES* Inventory, int *InventoryCounter);
main() {
int SIZE;
int userChoice;
int InventoryCounter = 0;
//printf("********************* ");
//printf("* Welcome Reseller! * ");
//printf("********************* ");
printf("Enter the size of todays inventory:");
scanf("%i", &SIZE);
SALES *Inventory;
Inventory = calloc(SIZE, sizeof(SALES));//Using dynamic memory to allocate space on the
heap
do {
userChoice = getChoice(&InventoryCounter);
switch (userChoice) {
case 1:// Add a Sale
if (InventoryCounter == SIZE) // statement checks so we dont exceed the size of the
inventory user wants to enter.
{
printf("You Have Reached Max Inventory ");
PAUSE;
}
else {
addSale(&(Inventory[InventoryCounter]), &InventoryCounter);
}
3. break;
case 2: // Display all sales records
displaySales(&InventoryCounter, Inventory);
PAUSE;
break;
case 3: // Display all profits
sortProfits(Inventory, InventoryCounter);
displayProfit(&InventoryCounter, Inventory);
PAUSE;
break;
case 4: // Display Inventory
searchSale(Inventory, InventoryCounter);
break;
case 5:// remove a sale
removeSale(Inventory, &InventoryCounter);
break;
case 6: // Quit
break;
default:
printf("Please choose a valid option ");
PAUSE;
break;
}// end of switch
} while (userChoice != 6);
free(Inventory);
} // End of main
//////////////////////////////////////////// FUNCTIONS BELOW //////////////////////////////////////////////////
void addSale(SALES *Inventory, int *InventoryCounter)// Function that adds sale and
calculates the fees in the background.
{
float payPalFee = 0; // variable to store the paypal fee from 1 sale
float ebayFee = 0; // variable to store ebay fee for 1 sale
4. /////////////// GETTING INVENTORY DETAILS ////////////////
printf("Enter the Item name: ");
scanf(" %[A-Z a-z]", Inventory->itemName);
printf(" Enter the item's purchase price: ");
scanf(" %f", &(Inventory->purchasePrice));
printf(" Enter the items Sold Price : ");
scanf(" %f", &(Inventory->soldPrice));
printf(" Enter the item Shipping Price: ");
scanf(" %f", &(Inventory->shippingPrice));
///////////////////////////////////////////////////////////
/////////////// Fees Calculated below ////////////////
payPalFee = (Inventory->soldPrice) * (.03) + .30; // Calculating Paypals fee Which is 3% of
sold price plus .30 cents
ebayFee = (Inventory->soldPrice)* (.10); // Caluculating Ebays fee which is 10% of sold
price
Inventory->payPalFee = payPalFee; // Saving the paypal fee for this specific item in struct
Inventory->ebayFee = ebayFee; // Saving the ebay fee for this specific item in struct
// calculating the profit for this 1 secific item based on details provided (line below) //
Inventory->profit = Inventory->soldPrice - Inventory->payPalFee - Inventory->ebayFee -
Inventory->purchasePrice - Inventory->shippingPrice;
(*InventoryCounter)++; // Incrementing Inventory counter ( amount of sales)
} // End of addSale
void searchSale(SALES* Inventory, int InventoryCounter) // function that searches for a sale by
5. name
{
char name[100]; // array to hold item searched name
char found = 'N'; // Flag variable
int i; // loop control variable
////// Ask User for item name //////
printf("What item are you searching for? ");
scanf("%s", name);
for (i = 0; i < InventoryCounter; i++)
{
if (strcmp(name, Inventory[i].itemName) == 0)// returns 0 if item was found, then we can
display the item details.
{
printf(" |Name|t|Purchase Price|t|soldPrice|t|Profit| ");
printf(" %.6s ttt$%.2f tt$%.2f tt$%.2f ", Inventory[i].itemName,
Inventory[i].purchasePrice, Inventory[i].soldPrice, Inventory[i].profit);
found = 'Y';//flag changed to illustrate item was found
PAUSE;
}// end if statment
}// end for loop
if (found == 'N') // if strcmp does not return 0 and flag stays 'N' then item will not be in
inventory
{
printf("Item not found ");
PAUSE;
}
}// end search Sales function
void displayProfit(int *InventoryCounter, SALES *Inventory) // Function that displays the
profit details of each item.
{
int i; // loop control variable
CLS;
6. printf("|Name|t| Profit| ");
for (i = 0; i < *InventoryCounter; i++)// loops through all the items and displays their name
and profit detials.
{
printf("%st%.2f ", Inventory[i].itemName, Inventory[i].profit);
} // End of for loop
} // End of displayProfit
void displayMenu(int *InventoryCounter) // Fucntion that displays the Main Menu
{
CLS;
printf("******** Main Menu ********* ");
printf("1. Add a sale. ");
printf("2. Display all Inventory records. ");
printf("3. Display all Inventory profits (high to low). ");
printf("4. Search inventory for a specific item . ");
printf("5. Remove a Sale from Inventory ");
printf("6. Quit. ");
printf("Current Sales: %i ", *InventoryCounter);
printf("Enter your choice: ");
} // End of displayMenu
void displaySales(int *InventoryCounter, SALES *Inventory) // Fucntion that Displays all sales
records
{
int i; // loop control variable
CLS;
printf(" |Name|tt|Purchase Price|t|soldPrice|tt|shippingPrice| ");
for (i = 0; i < *InventoryCounter; i++) // loops through all the inventory and displays details
{
printf(" %.6s ttt$%.2f ttt$%.2f ttt $%.2f ", Inventory[i].itemName,
Inventory[i].purchasePrice, Inventory[i].soldPrice, Inventory[i].shippingPrice);
} // End of for loop
} // End of displaySales
7. int getChoice(int *InventoryCounter)// Function that returns the user Choice from menu
{
int result;
displayMenu(InventoryCounter);
while (getchar() != ' ') {};
scanf(" %i", &result);
return result;
} // End of getChoice
void sortProfits(SALES *Inventory, int InventoryCounter)// Function that sorts all the profits
from highest to lowest
{
int i, j;// loop control variable
SALES temp;// temp place holder.
for (i = 0; i < (InventoryCounter - 1); i++)
{
for (j = 0; j < InventoryCounter - i - 1; j++)
{
if (Inventory[j].profit < Inventory[j + 1].profit)
{
temp = Inventory[j];
Inventory[j] = Inventory[j + 1];
Inventory[j + 1] = temp;
}
}
}// end for loop through all inventory
}// End Sort Profits function
void removeSale(SALES* Inventory, int *InventoryCounter) {
char name[100];// char array to hold item searched name
int i, j; // loop control variable
char found = 'N';// Flag variable
printf("What item do you want to remove? ");
8. scanf("%s", name);
for (i = 0; i < *InventoryCounter; i++)
{
if (strcmp(name, Inventory[i].itemName) == 0) //if strcmp returns 0 then item will be
removed from inventory
{
for (j = i; j < *InventoryCounter - 1; j++)
Inventory[j] = Inventory[j + 1];
(*InventoryCounter)--;
printf(" Item Succesfully Removed ");
found = 'Y';
PAUSE;
}// end if statement
}// end for loop
if (found == 'N') // if strcmp does not return 0 and flag stays 'N' then item will not be in
inventory
{
printf("Item not found ");
PAUSE;
}// end else statement
}// end removeSale function
Solution
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#define PAUSE system("pause")
#define CLS system("cls");
//#define FLUSH fflush(stdin);
//////////////// SRUCTS BELOW //////////////////////////
9. typedef struct SALESINFO
{
char itemName[40];
float purchasePrice;
float soldPrice;
float shippingPrice;
float ebayFee;
float payPalFee;
float profit;
}SALES;
////////// FUNCTION PROTOTYPE BELOW /////////////
void addSale(SALES *Inventory, int *InventoryCounter);
void displayMenu(int *InventoryCounter);
void displayProfit(int *InventoryCounter, SALES *Inventory);
void displaySales(int *InventoryCounter, SALES *Inventory);
int getChoice(int *InventoryCounter);
void searchSale(SALES* Inventory, int InventoryCounter);
void sortProfits(SALES* Inventory, int InventoryCounter);
void removeSale(SALES* Inventory, int *InventoryCounter);
main() {
int SIZE;
int userChoice;
int InventoryCounter = 0;
//printf("********************* ");
//printf("* Welcome Reseller! * ");
//printf("********************* ");
printf("Enter the size of todays inventory:");
scanf("%i", &SIZE);
//SALES *Inventory;
struct SALESINFO *Inventory;
Inventory=(struct SALESINFO *) malloc (SIZE * sizeof(struct SALESINFO));
//Inventory = calloc(SIZE, sizeof(SALES));//Using dynamic memory to allocate space on the
heap
10. do {
userChoice = getChoice(&InventoryCounter);
switch (userChoice) {
case 1:// Add a Sale
if (InventoryCounter == SIZE) // statement checks so we dont exceed the size of the inventory
user wants to enter.
{
printf("You Have Reached Max Inventory ");
PAUSE;
}
else {
addSale(&(Inventory[InventoryCounter]), &InventoryCounter);
}
break;
case 2: // Display all sales records
displaySales(&InventoryCounter, Inventory);
PAUSE;
break;
case 3: // Display all profits
sortProfits(Inventory, InventoryCounter);
displayProfit(&InventoryCounter, Inventory);
PAUSE;
break;
case 4: // Display Inventory
searchSale(Inventory, InventoryCounter);
break;
case 5:// remove a sale
removeSale(Inventory, &InventoryCounter);
break;
case 6: // Quit
break;
default:
printf("Please choose a valid option ");
PAUSE;
break;
}// end of switch
11. } while (userChoice != 6);
free(Inventory);
} // End of main
//////////////////////////////////////////// FUNCTIONS BELOW //////////////////////////////////////////////////
void addSale(SALES *Inventory, int *InventoryCounter)// Function that adds sale and calculates
the fees in the background.
{
float payPalFee = 0; // variable to store the paypal fee from 1 sale
float ebayFee = 0; // variable to store ebay fee for 1 sale
/////////////// GETTING INVENTORY DETAILS ////////////////
printf("Enter the Item name: ");
scanf(" %[A-Z a-z]", Inventory->itemName);
printf(" Enter the item's purchase price: ");
scanf(" %f", &(Inventory->purchasePrice));
printf(" Enter the items Sold Price : ");
scanf(" %f", &(Inventory->soldPrice));
printf(" Enter the item Shipping Price: ");
scanf(" %f", &(Inventory->shippingPrice));
///////////////////////////////////////////////////////////
/////////////// Fees Calculated below ////////////////
payPalFee = (Inventory->soldPrice) * (.03) + .30; // Calculating Paypals fee Which is 3% of
sold price plus .30 cents
ebayFee = (Inventory->soldPrice)* (.10); // Caluculating Ebays fee which is 10% of sold price
Inventory->payPalFee = payPalFee; // Saving the paypal fee for this specific item in struct
Inventory->ebayFee = ebayFee; // Saving the ebay fee for this specific item in struct
// calculating the profit for this 1 secific item based on details provided (line below) //
Inventory->profit = Inventory->soldPrice - Inventory->payPalFee - Inventory->ebayFee -
Inventory->purchasePrice - Inventory->shippingPrice;
(*InventoryCounter)++; // Incrementing Inventory counter ( amount of sales)
} // End of addSale
void searchSale(SALES* Inventory, int InventoryCounter) // function that searches for a sale by
name
{
char name[100]; // array to hold item searched name
12. char found = 'N'; // Flag variable
int i; // loop control variable
////// Ask User for item name //////
printf("What item are you searching for? ");
scanf("%s", name);
for (i = 0; i < InventoryCounter; i++)
{
if (strcmp(name, Inventory[i].itemName) == 0)// returns 0 if item was found, then we can
display the item details.
{
printf(" |Name|t|Purchase Price|t|soldPrice|t|Profit| ");
printf(" %.6s ttt$%.2f tt$%.2f tt$%.2f ", Inventory[i].itemName,
Inventory[i].purchasePrice, Inventory[i].soldPrice, Inventory[i].profit);
found = 'Y';//flag changed to illustrate item was found
PAUSE;
}// end if statment
}// end for loop
if (found == 'N') // if strcmp does not return 0 and flag stays 'N' then item will not be in
inventory
{
printf("Item not found ");
PAUSE;
}
}// end search Sales function
void displayProfit(int *InventoryCounter, SALES *Inventory) // Function that displays the profit
details of each item.
{
int i; // loop control variable
CLS;
printf("|Name|t| Profit| ");
for (i = 0; i < *InventoryCounter; i++)// loops through all the items and displays their name and
profit detials.
{
printf("%st%.2f ", Inventory[i].itemName, Inventory[i].profit);
} // End of for loop
13. } // End of displayProfit
void displayMenu(int *InventoryCounter) // Fucntion that displays the Main Menu
{
CLS;
printf("******** Main Menu ********* ");
printf("1. Add a sale. ");
printf("2. Display all Inventory records. ");
printf("3. Display all Inventory profits (high to low). ");
printf("4. Search inventory for a specific item . ");
printf("5. Remove a Sale from Inventory ");
printf("6. Quit. ");
printf("Current Sales: %i ", *InventoryCounter);
printf("Enter your choice: ");
} // End of displayMenu
void displaySales(int *InventoryCounter, SALES *Inventory) // Fucntion that Displays all sales
records
{
int i; // loop control variable
CLS;
printf(" |Name|tt|Purchase Price|t|soldPrice|tt|shippingPrice| ");
for (i = 0; i < *InventoryCounter; i++) // loops through all the inventory and displays details
{
printf(" %.6s ttt$%.2f ttt$%.2f ttt $%.2f ", Inventory[i].itemName,
Inventory[i].purchasePrice, Inventory[i].soldPrice, Inventory[i].shippingPrice);
} // End of for loop
} // End of displaySales
int getChoice(int *InventoryCounter)// Function that returns the user Choice from menu
{
int result;
displayMenu(InventoryCounter);
while (getchar() != ' ') {};
scanf(" %i", &result);
return result;
} // End of getChoice
void sortProfits(SALES *Inventory, int InventoryCounter)// Function that sorts all the profits
from highest to lowest
14. {
int i, j;// loop control variable
SALES temp;// temp place holder.
for (i = 0; i < (InventoryCounter - 1); i++)
{
for (j = 0; j < InventoryCounter - i - 1; j++)
{
if (Inventory[j].profit < Inventory[j + 1].profit)
{
temp = Inventory[j];
Inventory[j] = Inventory[j + 1];
Inventory[j + 1] = temp;
}
}
}// end for loop through all inventory
}// End Sort Profits function
void removeSale(SALES* Inventory, int *InventoryCounter) {
char name[100];// char array to hold item searched name
int i, j; // loop control variable
char found = 'N';// Flag variable
printf("What item do you want to remove? ");
scanf("%s", name);
for (i = 0; i < *InventoryCounter; i++)
{
if (strcmp(name, Inventory[i].itemName) == 0) //if strcmp returns 0 then item will be removed
from inventory
{
for (j = i; j < *InventoryCounter - 1; j++)
Inventory[j] = Inventory[j + 1];
(*InventoryCounter)--;
printf(" Item Succesfully Removed ");
found = 'Y';
PAUSE;
}// end if statement
15. }// end for loop
if (found == 'N') // if strcmp does not return 0 and flag stays 'N' then item will not be in
inventory
{
printf("Item not found ");
PAUSE;
}// end else statement
}// end removeSale function
-------------------------
output sample:-
******** Main Menu *********
1. Add a sale.
2. Display all Inventory records.
3. Display all Inventory profits (high to low).
4. Search inventory for a specific item .
5. Remove a Sale from Inventory
6. Quit.
Current Sales: 0
Enter your choice: 1
Enter the Item name: XYZ
Enter the item's purchase price: 4
Enter the items Sold Price : 6
Enter the item Shipping Price:2
******** Main Menu *********
1. Add a sale.
2. Display all Inventory records.
3. Display all Inventory profits (high to low).
4. Search inventory for a specific item .
5. Remove a Sale from Inventory
6. Quit.
Current Sales: 1
Enter your choice: 2
|Name| |Purchase Price| |soldPrice| |shippingPrice|
XYZ $4.00 $6.00 $2.00
---------------------------------------------------------------------------------------------
If you have any query, please feel free to ask.