I've got a small task I need to complete and I'm rather confused. This task has 3 parts to it which are:
Write a program that dynamically allocates a float array of a size specified by a user (currently working on - if anyone could check my code for this it would be appreciated.
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
Program should print what was saved into the array, the sum, and the average value in the array, and exit.
As you could tell I'm new to C++ and coding in general so please spell it out for me wherever possible. It is mandatory that I am using pointers so I'm afraid I can't change that.
#include <iostream>
using namespace std;
int main()
{
int length;
cout << “Please enter the length of the array: “;
cin >> length;
float * dArray = new float [length];
for (int i = 0; i < length; i++)
{
cin >> dArray[i] = i;
for (int i = 0; i < length; i++)
{
cout << dArray[i] << “ “;
}
cout << ‘/n’;
int sum = 0;
for (int i=0; i < length; i++)
{
sum +=dArray[i];
avg =sum/length;
cout << “Sum is “ << sum << “/nAverage is “ << average;
delete [] dArray;
}
return 0;
}
Please explain the 2nd part.
Thanks in advance.
Regarding
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
It means that you have to let the user input the values to that array. What you are doing is giving them values yourself.
What you need to do is change
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
to
for (int i = 0; i < length; i++)
{
cin>>dArray[i];
}
Also Note that length should be an int and not a float.
After completion, this would probably be the code you need ( although I would advice you to do the part of finding the sum and average by yourself and use this code I have posted as reference to check for any mistake, as finding the sum and average for this is really easy )
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
float sum = 0 , avg; // variables to store sum and average
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for (int i = 0; i < length; i++)
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
delete[] dArray;
return 0;
}
EDIT
After getting your comment, I decided to post this new code. ( I am assuming what you meant is that the program should repeat as long as the user wants )
I have done it by using a do while loop.
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
char a; // a variable to store the user choice
do
{
float sum = 0 , avg; // variables to store sum and average
cout << "\nPlease enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for ( int i = 0; i < length; i++ )
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++ ) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
cout << "\n\nDo you want to try again ( y/n ) ?\n";
cin >> a;
delete[] dArray;
}while( a =='Y' || a == 'y' ); // The do while loop repeats as long as the character entered is Y or y
return 0;
}
Well, hope this is what you were looking for, if not, please do notify me with a comment... :)
Just so you know, the new code you have posted doesn't even compile. Here are some of the problems.
cin >> dArray[i] = i;
You don't need to use = i here. Just cin >> dArray[i] ; is enough.
The next problem is
cout << ‘/n’;
First of all, its \n and not /n. You also need to enclose it in double quotes and not single quotes. That is cout << "\n";
Next one, you have not defined the variable avg . Also note that you have also used an undefined variable average, which I assume you meant avg.
Now here's one of the main problems , You have not closed the curly brackets you opened. You open the brackets for for loops, but forget to close it. I'm leaving that part to you as you need to learn that part yourself by trying.
Now Here's one problem I don't understand, you have used “ “, which is somehow not the same as " ". I don't know if it's something wrong with my computer, or if it's a totally different symbol. My compiler couldn't recognize it. If its not causing any trouble on your end, then don't mind it.
Well, this sums up the problems I noticed in your code ( the problems that I noticed ).
Your issues are too simple for us to just give you the answers, but I've commented your code with suggestions on how to solve your problem:
#include <iostream>
using namespace std;
int main()
{
float length; //it doesn't make sense for something to be of a float length
//should be size_t instead
cout << "Please enter the length of the array: ";
cin >> length;
float *dArray = new float[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i; //this line is incorrect
//how should we read the data into this array?
//we've used cin before
}
for (int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
cout << '\n';
//now we've output the array, just need to output the sum and average value
int sum = 0;
for (int i=0; i < length; i++)
{
sum += //what should go here?
}
int average = //how should we calculate the average?
cout << "Sum is " << sum << "\nAverage is " << average;
delete[] dArray;
return 0;
}
Related
So in this program, I have to do multiplication in a very tedious fashion and for the second loop, the for loop, I'm multiplying one variable by 2 and the output is the product of that multiplication I am wondering how I could go about taking those output values and adding them together. The code and output of the code are below
#include <iostream>
using namespace std;
int main()
{
cout << "Time to do some Martian Math" << endl;
// variables for math
int righthandnum;
int lefthandnum;
cout << "Please enter two numbers" << endl;
// get values to do the martian math
cin >> lefthandnum;
cin >> righthandnum;
//while loop for right hand number
int i = 0;
while (righthandnum >= 1 ) {
//cout << righthandnum << endl;
//if to find out if any values are odd
if (righthandnum % 2 == 0) {
i -= 1;
}
righthandnum = righthandnum / 2;
i++;
}
int num;
for (num = 1; num <= i; num++) {
lefthandnum = lefthandnum * 2;
//lefthandnum + lefthandnum;
cout << lefthandnum << endl;
}
return 0;
}
The output is
Time to do some Martian Math
Please enter two numbers
50
30
100
200
400
800
Thank you so much for any help!
I don't know if this is what you are looking for but maybe a stack or an array might help you
with the array (the easy way), you make a list of N size for the data as an example:
int values[10];
for(int i = 0; i < 10; i++){
std::cin>>values[i];
}
for(int i = 0; i < 10; i++){
std::cout<<"List element "<<i<<": "<<values[i]<<std::endl;
}
while the stack as I've used it it's a bit more complex and requires pointers.
this is a video (sorry it's in Spanish): https://youtu.be/joAw2jWgZqA
So this is for a lab assignment and I already have it working, but one thing is bothering me. The assignment involves creating a 1-dimensional array and then manipulating it. I am supposed to allow a max of 100 inputs but the user does not have to use all 100. Right now, I am using a while statement to either break or allow another input to be entered. To break the statement, you have to enter a negative number (this is what I don't like and want to change). What other options are there to end the user input, once they are done entering their numbers? Is it possible to end the loop once you hit enter with nothing typed?
I have searched stackoverflow for the last 3 days and found some compelling stuff but could never get it to work.
Note, I get the void function is redundant here but that's besides the point (unless it actually affects my ability to achieve what I want).
Also, thanks in advance.
here is my code so far (my while statement is in the main)... be kind I'm a newbie to coding.
#include <iostream>
using namespace std;
void reverseElements(int array[], int size)
{
int tmp;
int j;
int i = size;
j = i - 1;
i = 0;
while (i < j)
{
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
cout << "I will now reverse the elements of the array." << endl;
cout << endl;
for (i = 0; i < size; i++)
{
cout << array[i] << " " << endl;
}
}
int main()
{
const int NUM_ELEMENTS = 100;
int iArr[NUM_ELEMENTS];
int i;
int myInput;
cout << "Enter your numbers, then enter a negative number to finish" << endl;
cout << endl;
for (i = 0; i < NUM_ELEMENTS; i++) //loop to obtain input
{
cin >> myInput;
if (myInput < 0) //checks for negative number to end loop
{
break;
}
else //continues to allow input
{
iArr[i] = myInput;
}
}
cout << endl;
reverseElements(iArr, i);
return 0;
}
Probably the easiest solution: let your user choose how many numbers to write before actually writing them.
int readNumbersCount()
{
int const numbersMin = 1;
int const numbersMax = 100;
int numbersCount = -1;
while (numbersCount < numbersMin || numbersCount > numbersMax)
{
std::cout <<
"How many numbers are you going to enter? Choose from " <<
numbersMin << " to " << numbersMax << ":\n";
std::cin >> numbersCount;
}
return numbersCount;
}
int main()
{
int const numbersCount = readNumbersCount();
for (int i = 0; i < numbersCount; ++i)
{
// read the numbers etc.
}
return 0;
}
I wrote readNumbersCount() as a separate function to extract numbersMin and other "one-use" identifiers from main() and to make main()'s numbersCount const.
I have edited the main function a little bit.
Here the user is asked how many elements he wants to enter .
and doing the memory allocation dynamically so as to save space
int main()
{ int n=101;
while(n>100){
cout<<"How many numbers do you want to enter";
cin>>n;
}
int *ptr=new(nothrow)int[n];
for (int i=0;i<n;i++){
cout << "Enter your number" << endl;
cin>>ptr[i];
}
cout << endl;
reverseElements(ptr, n);
return 0;
}
I know this isnt the right kind of question to be asking, but for the life of me I could not figure out what is causing this problem.
I need to write a problem that takes a set number of integers or doubles and returns their sum.
I have written the code to make this work, making sure to check each time I changed something.
#include<iostream>
using namespace std;
template <class T>
class totalClass
{
private:
T *p;
T Total;
T sum;
int size;
public:
T total(int x)
{
size = x;
p = new T[x];
for (int i = 0; i < size; i++)
p[i] = T();
if (size > 1)
{
for (int i = 0; i < size; ++i)
{
cin >> sum;
Total += sum;
}
}
return Total;
}
};
int main()
{
int size, result1;
double result2;
cout << "Enter: ";
cin >> size;
cout << "the number of ints you wish to enter: Enter: " << size << " integers:";
totalClass<int> test;
result1 = test.total(size);
cout << " Total = " << result1 << endl;
cout << "Enter: ";
cin >> size;
cout << "the number of doubles you wish to enter: Enter: " << size << " doubles:";
totalClass<double> test2;
result2 = test2.total(size);
cout << " Total = " << result2 << endl;
}
My doubles are getting added up correctly but my integer addition always seems to add up to some crazy number. Is there something wrong with my problem that I cannot see?
If you forget to initialize a variable and attempt to use it or do math with it, you might end up with "crazy numbers." Make sure all of your variables are Initialized.
I have a call to 2 functions which find the highest and lowest grade, respectively. they return "highestGrade" and "lowestGrade" but I am confused why the error appears when I compile. This is a lab assignment and most of the code was pre-written and I was tasked with filling in the missing code. The error occurs around lines 55 and 63, and the functions I am referring to are at the end of the code.
I am new to using arrays so I am assuming I may have some for of erroneous code inside the functions "findHighest" and "findLowest". For example, the program in "findHighest" will assume the first array it runs into is the highest grade and will compare the remaining arrays to it until it finds one that is higher. If it is, it will then assign that array to "highestGrade".
float findAverage(const GradeType, int);
int findHighest(const GradeType, int);
int findLowest(const GradeType, int);
int main()
{
GradeType grades;
int numberOfGrades;
int pos;
float avgOfGrades;
int highestGrade;
int lowestGrade;
// Read in the values into the array
pos = 0;
cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
cin >> grades[pos];
int i = 1;
while (grades[pos] != -99)
{
// read in more grades
pos = i;
cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
cin >> grades[pos];
}
numberOfGrades = pos; // Fill blank with appropriate identifier
// call to the function to find average
findAverage(grades, numberOfGrades);
avgOfGrades = findAverage(grades, numberOfGrades);
cout << endl << "The average of all the grades is " << avgOfGrades << endl;
// Fill in the call to the function that calculates highest grade
findHighest(grades, highestGrade);
highestGrade = findHighest(grades, highestGrade);
cout << endl << "The highest grade is " << highestGrade << endl;
// Fill in the call to the function that calculates lowest grade
findLowest(grades, lowestGrade);
// Fill in code to write the lowest to the screen
lowestGrade = findLowest(grades, lowestGrade);
cout << endl << "The lowest grade is " << lowestGrade << endl;
return 0;
}
float findAverage(const GradeType array, int size)
{
float sum = 0; // holds the sum of all the numbers
for (int pos = 0; pos < size; pos++)
sum = sum + array[pos];
return (sum / size); //returns the average
}
int findHighest(const GradeType array, int size)
{
// Fill in the code for this function
float highestGrade = array[0];
for (int i = 0; i < size; i++)
{
if (array[i] > highestGrade)
highestGrade = array[i];
}
return highestGrade;
}
int findLowest(const GradeType array, int size)
{
// Fill in the code for this function
float lowestGrade = array[0];
for (int i = 1; i < size; i++)
{
if (array[i] < lowestGrade)
lowestGrade = array[i];
}
return lowestGrade;
}
The program is unable to output the highest and lowest grade due to the error.
findLowest(grades, lowestGrade);
You are using lowestGrade before initializing it.
int lowestGrade;
should be
int lowestGrade = 0; // or to anything that has meaning for your app.
And of course, as better C++, declare it just before you need it, not at the top of the function.
Same thing for the other variables.
All of this of course if the logic is correct. Why do you pass the lowest/higest grade as a size parameter in the functions?
Having trouble getting my code to run properly, first time I have ever used C++ and just trying to learn it for my knowledge, I am trying to get a 2d array with all zeros except in the final column. Inputs are stock = 100, strike = 100, time to maturity = 1, interest rate = 0.06, time steps = 3, upfactor = 1.1, downfactor = 0.9091. The end Array should look like {[0,0,0,133.10], [0,0,0,110], [0,0,0,90.91], [0,0,0,75.13]}, bot for some reason I keep getting values in the first column as well and I am stumped. Any advice?
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <cmath>
using namespace std;
int main(int nNumberofArgs, char*pszArgs[])
{
double st;
cout << " Enter Value of stock: ";
cin >> st;
double K;
cout << " Enter Value of strike price: ";
cin >> K;
double t;
cout << " Enter time of maturity: ";
cin >> t;
double r;
cout << " Enter Value of the interest rate: ";
cin >> r;
int N;
cout << " Enter Value of time steps: ";
cin >> N;
double u;
cout << " Enter value of up factor: ";
cin >> u;
double d;
cout << " Enter Value of down factor: ";
cin >> d;
double dt;
dt = t/N;
double p;
p = (exp(r*dt)-d)/(u-d);
// Initialise asset price at maturity time step N
double price[N][N];
for( int i = 0; i < N+1; i++)
{
for (int j = 0; j<N+1; j++)
{
price[i][j] = 0;
}
}
price[N][N] = st*pow(d,N);
cout << "price[N][N] is equal to: " << price[N][N] << endl;
double newN;
newN = N-1;
//cout << price[2][0] << endl;
for(int ii = newN; ii >=0; ii--)
{
price[ii][N] = (price[ii+1][N]) * (u/d);
}
//cout << price[2][0] << endl;
for( int i = 0; i <= N; i++)
{
for (int j = 0; j <=N; j++)
{
cout << price[i][j] << " ";
}
cout << endl;
}
system("PAUSE");
return 0;
}
The problem area is
for(int ii = newN; ii >=0; ii--)
{
price[ii][N] = (price[ii+1][N]) * (u/d);
}
and not sure exactly how to fix it. Any thoughts??
In C/C++ indexes are from 0
double price[N][N];
or
double price[10][10];
means that you have an array from 0..9 and 0..9
so
price[N][N] = st*pow(d,N);
is writing to a location outside the arrays as the maximum index is price[N-1][N-1]
and for that reason, loops in C/C++
for( int i = 0; i <= N; i++)
should be written as
for( int i = 0; i < N; i++)
since N is not included as a valid index value for the array.
Couple of issues with your program.
You have created a double dimensional array on stack with variable sized length (N).
If your array size is dynamic don't create it on stack, use new to allocate it on heap.
Also, as I see it you are accessing out-of-array entries. (Index greater than max array index)