Dynamic array and how to check if it has a certain number - arrays

I'm having trouble with dynamic array. The code I wrote is suppose to input the # of coins and check if 1 is included. If it is not include in the arrays include 1 to the array. But the array size is "fixed" so i can't change the size of array while keeping the other numbers inputted. How can I do this without messing up with my arrays?
#include <iostream>
using namespace std;
int main()
{
int N,coin;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] != 1)
S[coin] = 1; // confused at this part of how to set the last element to 1
cout << S[i] << endl;
}
//system("PAUSE");
return 0;
}

here is pseudo code/comments
bool hasOne;
for(int i = 0; i < coin; i++) {
cin >> S[i];
if(S[i] == 1) hasOne = true;
}
if(!hasOne) {
// create a new array size one more than S
// copy elements from S to the new array
// set the last element to 1 in the new array
// assign the new array to S
}

Do you need to append 1 to the end of the array? If so, I would use std::vector object instead of an array
#include <vector>
vector<int> S;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] != 1)
S.push_back(1);
cout << S[i] << endl;
}
If you must use arrays you need to use malloc() to dynamically allocate memory. But since you are using c++ std::vector is the way to go.

Related

c++ Getting the Summation of numbers using an array and pointers

So I was doing a program where i need to find the total area of all floors, where the floors are determined by the user. I think I'm correct on the part to use the pointers, so to check if the code was correct I tried it doing it with basic addition. but even with basic addition it seems to have already some problems. I tried looking for similar questions in here and I can't find anything that might help me, so I hope you guys can help me. Thank you in advance.
float *Length=NULL, *Width=NULL, *Area=NULL, TotalArea, templ, tempw;
int floors, count;
cout << "Input the number of floors to proceed\n";
cout << ":";
cin >> floors;
Length = new float[floors];
Width = new float[floors];
Area = new float[floors];
for (int loop = 0; loop < floors; loop++)
{
cout << "\n\nFloor " << loop + 1 << endl;
cout << "Input the Length: \n";
cin >> templ;
cout << "Input the Width: \n";
cin >> tempw;
*(Length + loop) = templ;
*(Width + loop) = tempw;
*(Area + loop) = (*Length + loop) + (*Width + loop);
count = loop;
for (int count = 0; count < floors; count++)
{
TotalArea = TotalArea + *Area+count;
}
}
cout << TotalArea << endl;
I tried inputting the following:
floor:2
floor 1
length: 1
width: 1
floor 2
length: 1
width: 1
The answer should be 4, but the output ends up with 10.
You don't need arrays and pointers. Since you are looping through the floors and summing the areas of each floor, you can "forget" about previously encountered lengths, widths and areas, and only remember the total area encountered so far.
float length;
float width;
float area;
float totalArea;
int floors;
std::cout << "Input the number of floors to proceed\n";
std::cout << ":";
std::cin >> floors;
totalArea = 0;
for (int loop = 0; loop < floors; loop++)
{
std::cout << "\n\nFloor " << loop + 1 << std::endl;
std::cout << "Input the Length: " << std::endl;
std::cin >> length;
std::cout << "Input the Width: " << std::endl;
std::cin >> width;
area = length * width;
totalArea += area;
}
std::cout << totalArea << std::endl;
Notice how I added these annoying std:: everywhere? If you wonder why, see this other question: Why is “using namespace std;” considered bad practice?
I tried making some changes based on you guys comments and here is what I did.
There are some warnings I don't really know why but It seems to be working
float* Length = NULL, * Width = NULL, TotalArea, tempw, templ, * Area = NULL;
int floors, loop = 0;
cout << "Input the number of floors to proceed\n";
cout << ":";
cin >> floors;
for (int loop = 0; loop < floors; loop++)
{
Length = new float[floors];
Width = new float[floors];
Area = new float[floors];
cout << "\n\nFloor " << loop + 1 << endl;
cout << "Input the Length: \n";
cin >> templ;
cout << "Input the Width: \n";
cin >> tempw;
*(Length +loop) = l;
*(Width+loop) = w;
Area[floors] = (*(Length+loop)) * (*(Width+loop));
TotalArea += a[floors];
}
cout << TotalArea << endl;
This is what I came u with, it seems to be working, the output is also correct now.

C++ How to Increment Int Variable From String Array Element

I'm wondering if there is a way to increment an int variable when a specific string array element is called? I'm working on a project for fun and have run into a roadblock. The goal of my project is to have a program that determines what genres of electronic music the user likes. The program will present two DJ's and ask the user which one they prefer or allow them to select neither. Each DJ will have up to three genres that they mainly specialize in, and I have created int variables for each (with all being set to 0). Once a user selects a DJ, I want points to be assigned to each genre variable in which the DJ is associated with. I'm unsure of how to set up this rule as everything I have attempted so far has failed (two example attempts are commented out in the code). Eventually my plan is to develop logic to have the DJ's randomly selected, however I need to have the genre tally allocation set up first. Is there any way this can be done? Any help would be greatly appreciated. Cheers!
###include "stdafx.h"
###include < iostream>
###include < iomanip>
###include < string>
###include < array>
###using namespace std;
int main()
{
cout << "Hello! This program is designed to figure out what Electronic Music you like based on artists presented and the answers you choose...\n" << endl;
cout << "When you are ready to begin press \"Enter\"..." << endl;
getchar();
int bigRoom = 0;
int deepHouse = 0;
int drumBass = 0;
int dubstep = 0;
int electroHouse = 0;
int futureHouse = 0;
int hardDance = 0;
int house = 0;
int progressiveHouse = 0;
int techno = 0;
int trance = 0;
int trap = 0;
string textArray[5]{ "DeadMau5", "Armin Van Buuren", "Avicii", "Ferry Corsten", "Kaskade"};
string answer;
cout << "Select the DJ you prefer by number. Otherwise select 3 if you don't know them. " << endl; //Haven't coded option 3 yet.
cout << "1 - " << textArray[1] << endl;
cout << "2 - " << textArray[2] << endl;
cin >> answer;
/*
if (textArray[1]) {
++trance;
}
for (textArray[1]) {
++trance;
}
*/
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
}
//cout << trance << endl;
}
You can increment each tally once the user has selected a DJ:
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
++trance;
// ++ ohter genres you want to increment
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
++trance;
// ++ ohter genres you want to increment
}

arrays pointers dynamic c++

#include <iostream>
using namespace std;
void main()
{
int numDays;
double sum = 0;
double avg;
cout << "Enter the number of days of sales";
cin >> numDays;
double *Sales = new double[numDays];
for (int i = 0; i < numDays; i++)
{
cout << "enter how much you sold for day " << i << endl;
cin>>*Sales;
sum = sum + *Sales;
cout << Sales;
}
delete[] Sales;
avg = sum / (numDays);
cout << "the sum is" << sum << endl;
cout << "the avg is" << avg << endl;
}
Hi this is the output I'm getting can somone explain why the pointer doesn't need to be incremented? and the proper way of doing the same task with pointers.
Enter the number of days of sales2
enter how much you sold for day 0
1
0050CD70enter how much you sold for day 1
2
0050CD70the sum is3
the avg is1.5
Press any key to continue . . .
There are a couple styles for doing this. You can either index into the array itself:
double *Sales = new double[numDays];
for (int i = 0; i < numDays; i++)
{
cout << "enter how much you sold for day " << i << endl;
cin >> Sales[i];
sum = sum + Sales[i];
}
Or you can advance a pointer, making sure to keep a copy of the original pointer. In the next example, the destination of p creeps along indices of Sales. (Make sure not to use delete on p since it wasn't created with a new!)
double *Sales = new double[numDays];
double *p = Sales;
for (i = 0; i < numDays; i++)
{
cout << "enter how much you sold for day " << i << endl;
cin >> *(p++);
}
(Technically the parentheses aren't needed in *(p++), and in fact there's a lot of code that uses *p++ instead).

Finding the max and min values in array of five times

I'm supposed to find the minimum and maximum values in the array, but I can't seem to figure out why the answers aren't correct. For example if I entered "1 2 3 4 5" as my five times, it told me 1 was my maximum and 0 was the minimum. For some reason, whatever the first number is, it calls it the max and it also assigns 0 as the min.
#include <iostream>
using namespace std;
int find_distance(int j); //a function that returns a distance based on the choice j
int intmax, intmin;
int main( )
{
int i =0;
int distance[6];
double data[6][5];
for(int j = 0; j < 6; j++)
{
distance[j] = find_distance(j);
cout << "\nEnter 5 of your best running times for \n " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
cout << "Enter a time \n"; cin >> data[j][i];
}
}
cout << "Here is your best 5 times: ";
for(int j = 0; j < 6; j++)
{
cout << "\nDistance : " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
system ("pause");
cout << data[j][i] << "\t"; } cout << endl;
if (data[j][i] < intmin)
intmin = data[j][i];
else if (data[j][i] > intmax)
intmax = data[j][i];
cout << "The maximum time is: " << intmax << endl;
cout << "The minimum time is: "<< intmin << endl;
}
return 0;
}
int find_distance(int j)
{
switch (j)
{ case 0: // 100 meter
return 100;
break;
case 1: // 150 meter
return 150;
break;
case 2: // 200 meter
return 200;
break;
case 3: // 400 meter
return 400;
break;
case 4: // 500 meter
return 800;
break;
default: // 1600 meter
return 1600;
}
}
The minimum value is 0 because when you initialize intmin, it is set to 0 by default. You never enter a negative time, so in your comparisons it is always less than the compared value.
The maximum value is off because your for loop ends in an odd place and the comparison code is improperly executed. Change this code:
for(int j = 0; j < 6; j++)
{
cout << "\nDistance : " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
system ("pause");
cout << data[j][i] << "\t"; } cout << endl; //why does the for loop end here?
if (data[j][i] < intmin)
intmin = data[j][i];
else if (data[j][i] > intmax)
intmax = data[j][i];
//move the end bracket to this line and it should work
cout << "The maximum time is: " << intmax << endl;
cout << "The minimum time is: "<< intmin << endl;
}
Just to practice:
#include <iostream>
#include <algorithm>
#include <string>
#include <boost/regex.hpp>
int main () {
using namespace std;
string input;
boost::regex re("-?\\d+");
vector<int> integers;
cout << "enter sequence of integers: ";
getline(cin, input);
boost::sregex_token_iterator begin(input.begin(), input.end(), re, 0);
boost::sregex_token_iterator end;
while (begin != end) {
integers.push_back(stoi(*begin));
++begin;
}
if (integers.size()) {
auto pair = minmax_element(integers.begin(), integers.end());
cout << "min: " << *pair.first << " max: " << *pair.second << endl;
} else {
cout << "you didn't enter any integers." << endl;
}
return 0;
}
This is how to compile and to run:
$ g++ -o lab_2 -std=c++11 -lboost_regex lab_2.cpp
$ ./lab_2
$ enter sequence of integers: -10 34 75 101 2 43
$ min: -10 max: 101
Requires boost installed because STL regular expressions aren't functional yet.

Issue with FOR loops and IF statement

Trying to display # of each combo ordered and total price. Not sure why it won't store values in A, B, and C. Novice programmer here, so be easy. Been having the problem with if statements for a while, so obviously I'm doing the whole if statement thing incorrectly.
#include <iostream>
using namespace std;
int main( )
{
int group = 0;
char combo = ' ';
int A = 0;
int B = 0;
int C = 0;
double total = 0.0;
cout << "How many customers are in the group? ";
cin >> group;
for (int counter = 0; counter < group; counter = counter + 1)
{
cout << "Enter combo ordered: ";
cin >> combo;
if (combo = A)
{
A = A + 1;
cout << "Enter combo ordered: ";
cin >> combo;
}
else if (combo = B)
{
B = B + 1;
cout << "Enter combo ordered: ";
cin >> combo;
}
else if (combo = C)
{
C = C + 1;
cout << "Enter combo ordered: ";
cin >> combo;
}
total = A*6 + B*6.25 + C*5.75;
}
cout << "# of Combo A ordered: " << A << endl;
cout << "# of Combo B ordered: " << B << endl;
cout << "# of Combo C ordered: " << C << endl;
cout << "Total price: $" << total << endl;
system("pause");
return 0;
}
For-loop should be for (int counter = 0; counter < group; counter++)
If statement should use == for equality. = is for assignment only.
Your if statement needs to quote the character you are comparing: if (combo == 'A') {. It is also possible that you'll need to access combo as an array of characters, like so: if (combo[0] == 'A') {
I think you may need to tweak just a few things; a few compilers don't like it when you compute a double using int and there is no reason to not use double here since the program is small. Also a few syntax errors (i.e. with = instead of ==). Have you tried displaying your output in an isolated way? Something like:
main(){
double A = 1;
double B = 2;
double C = 3;
double total = A*6 + B*6.25 + C*5.75;
cout << "# of Combo A ordered: " << A << endl;
cout << "# of Combo B ordered: " << B << endl;
cout << "# of Combo C ordered: " << C << endl;
cout << "Total price: $" << total << endl;
system("pause");
return 0;
}
Your corrected code:
#include <iostream>
using namespace std;
int main( )
{
int group = 0;
char combo = ' ';
double A = 0;
double B = 0;
double C = 0;
double total = 0.0;
cout << "How many customers are in the group? ";
cin >> group;
for (int counter = 0; counter < group; counter++)
{
cout << "Enter combo ordered: ";
cin >> combo;
if (combo == 'A')
{
A++;
}
else if (combo == 'B')
{
B++;
}
else if (combo == 'C')
{
C++;
}
cout << "Enter combo ordered: ";
cin >> combo;
}
total = A*6 + B*6.25 + C*5.75;
cout << "# of Combo A ordered: " << A << endl;
cout << "# of Combo B ordered: " << B << endl;
cout << "# of Combo C ordered: " << C << endl;
cout << "Total price: $" << total << endl;
system("pause");
return 0;
}
I would also display your value for group to make sure that the if loop is even running at least once. There are a few fault points here that I would test individually.
EDIT:
Maybe test this:
#include <iostream>
using namespace std;
int main( )
{
int group = 0;
cout << "How many customers are in the group? ";
cin >> group;
for (int counter = 0; counter < group; counter++)
{
cout << "Test success";
}
to see if you are even entering into your for loop.

Resources