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)
Related
I need to create a program that asks the user for N unique values and print the values in descending order for every number entered. The problem is it only outputs the number 0. Can anyone point out what is wrong with my code?
#include <iostream>
using namespace std;
int main(){
//declare the variables
int N, j, i, k, z, desc, temp, sorter[N];
bool found;
//Ask the user for N size array
cout << "Enter array size: ";
cin >> N;
while(N<5){
cout << "Invalid value. N must be greater than five(5)" << endl;
cout << "Enter array size: ";
cin >> N;
}
int list[N];
//Printing how many values they need to enter
cout << " " << endl;
cout << "Please enter " << N << " values" << endl;
//Code of the program
for (int i = 0; i < N; i++){
do{
found = false;
cout << "\n" << endl;
cout << "Enter value for index " << i << ": ";
cin >> temp;
for (int j = 0; j < i; j++)
if (list[j] == temp)
found = true;
if (found == true)
cout << "Value already exist";
else{
for(int k = 0; k < i; k++){
int key = sorter[k];
j = k - 1;
while(j >= 0 && key >= sorter[j]){
sorter[j + 1] = sorter[j];
j--;
}
sorter[j + 1] = key;
}
cout << "\nValues: ";
for(int z = 0; z <= i; z++){
cout << sorter[z] <<" ";
}
}
} while(found == true);
sorter[i] = temp;
}
You shouldn't be defining the array 'sorter[N]', the position, where you are currently, because you don't have the value of 'N', during compilation the arbitrary amount of space will be allocated to the the array.
solve the other compiling errors in your code.
What you want is just a 3-line code:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> vecOfNumbers = { 1,3,5,7,9,8,6,4,2 }; // scan these numbers if you want
std::sort(vecOfNumbers.begin(), vecOfNumbers.end());
std::copy(vecOfNumbers.rbegin(), vecOfNumbers.rend(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Make sure you understand it before using it
I need to write a program that receives 2 arrays and checks how many times 1 is included in the other...
But I cant find what is wrong with my program! tx!!
#include <iostream>
using namespace std;
int main()
{
int vector1[500];
int vector2[100];
int a = 0, b = 0, count = 0, k = 0;
cout << "enter size of first array:" << endl;
cin >> a;
cout << " enter first array values:" << endl;
for (int i = 0; i < a; i++)
cin >> vector1[i];
cout << "enter size of second array:" << endl;
cin >> b;
cout << "enter secound array values:" << endl;
for (int i = 0; i < b; i++)
cin >> vector2[i];
for (int i = 0; i < b; i++)
for (int j = 0; j < a; j++)
if (vector2[i + k] == vector1[j])
{
count++;
k++;
}
else
k = 0;
cout << count << endl;
system("pause");
return 0;
}
Why at all do you need k? The problem is about all inclusions of all elements right? If O(n^2) complexity is fine, then...
for (int i = 0; i < b; i++)
for (int j = 0; j < a; j++)
if (vector2[i] == vector1[j])
count++;
One obvious disadvantage of the code above is that you'll get the total sum of all occurences of elements from vector1 in vector2. The key idea remains the same in case you need to know, which elements exactly appeared in another array and how many times, you'll just have to use map or other vector.
I'm having problems moving the first input of my array to the end so that I can compute the average of the Window number of inputs. I have to use an array (not a matrix) to compute the moving average of weights. Question: if I set my number of weights to 5, input 5 weights, and then execute the arithmetic I get the correct average for the 1st day, however, everyday after that is incorrect. Can anyone lend guidance here and/or point me to a program or website that will allow me to execute my code line for line so that I can trouble shoot this problem more effectively. Thanks!
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX_NUM_WEIGHTS = 50;
// Function prototypes:
void movingAverage(int& numWeights, int weightArray[], int& Window);
int main()
{
int numWeights, Window;
int weightArray[MAX_NUM_WEIGHTS];
movingAverage(numWeights, weightArray, Window);
return 0;
}
void movingAverage(int& numWeights, int weightArray[], int& Window)
{
int i = 0, j = 0, day = 0, sum = 0, temp;
double avg;
cout << "Enter the number of weights: ";
cin >> numWeights;
cout << endl;
cout << "Enter the weights: ";
for(i = 0; i < numWeights; i++) {
cin >> weightArray[i];
}
cout << "Enter the length of the window: ";
cin >> Window;
cout << endl << endl;
while(k < numWeights - 1) {
for(j = 0; j < Window; j++) {
sum += weightArray[j];
}
avg = static_cast<double>(sum) / Window;
day = day + 1;
cout << day << ": " << avg << endl;
int temp = weights[i];
weights[i] = weights[numWeights];
if(k >= (numWeights - 1)) {
break;
}
}
}
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;
}
The problem is:
A Class of 40 students has received their grades for 5 exams. Implement a function that calculates the worst average grade and display the the IDs of all students having the worst average grade.
I already calculated the average but do not know how to calculate the WORST average ( as in the lowest average of the 40 students) and displaying the ID numbers that have this number.
This is what I have written so far:
#include<iostream>
#include <iomanip>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
int main()
{
float avg;
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
cout << "Enter an ID number: " << endl;
cin >> x[i];
cout << "Enter 5 grades: " << endl;
for (int j = 0; j < 5; j++)
{
cin >> y[j];
while (y[j]>100)
{
cout << "Please enter a valid grade that is less than a 100: " << endl;
cin >> y[j];
}
total += y[j];
}
avg = total / 5;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg << endl;
}
Something like this:
Note: I have added some important statements!
#include<iostream>
#include <iomanip>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
float AVG[MAX_NUM];
int worstIDCount = 0;
int main()
{
float avg, min = 1001;
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
avg = 0;
total = 0;
cout << "Enter an ID number: " << endl;
cin >> x[i];
cout << "Enter 5 grades: " << endl;
for (int j = 0; j < 5; j++)
{
cin >> y[j];
while (y[j]>100)
{
cout << "Please enter a valid grade that is less than a 100: " << endl;
cin >> y[j];
}
total += y[j];
}
avg = total / 5;
AVG[i] = avg;
if(avg < min)
min = avg;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg << endl;
}
for(int i = 0; i < MAX_NUM; i++)
{
if(AVG[i] == min)
cout << "Student with WORST Average: ID" << x[i] << endl;
}
};
So you want to store these averages in a std::vector<float>, std::sort it and get the lowest. Then go back and find the students that have that average.
working example
#include <iostream>
#include <vector>
#include <functional> // mem_fn
#include <algorithm> // sort, upper_bound
#include <iterator> // ostream_iterator
struct Student_average {
int student_id;
float average;
};
bool compare_student_averages(Student_average const &lhs,
Student_average const &rhs) {
return lhs.average < rhs.average;
}
int main() {
std::vector<Student_average> averages;
// collect the data and populate the averages vector
// ...
sort(begin(averages), end(averages), compare_student_averages);
std::cout << "The worst average is: " << averages.front().average << '\n';
auto end_of_worst_student_averages =
upper_bound(begin(averages), end(averages), averages.front(),
compare_student_averages);
std::cout << "The IDs of the students with the worst averages are:\n";
transform(begin(averages), end_of_worst_student_averages,
std::ostream_iterator<int>(std::cout, "\n"),
std::mem_fn(&Student_average::student_id));
}
Here is a more C++ way of doing this using std::accumulate and std::min_element (I removed the check for anything > 100, for brevity):
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
int main()
{
float avg[5];
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
cin >> x[i]; // ID
for (int j = 0; j < 5; ++j)
cin >> y[j]; // grades
// compute the average for this student
avg[i] = std::accumulate(y, y + 5, 0) / 5.0F;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg[i] << endl;
}
// compute the worst average
float* worst_average = std::min_element(avg, avg + MAX_NUM);
// get the position in the array where the worst is found
int position = std::distance(avg, worst_average);
// output results
cout << "This person has the worst average: " << x[position]
<<". The average is " << *worst_average << "\n";
}
Note that the averages are stored in an array. The way the average is computed for each person is to use std::accumulate to add up the y array values, and then divide by 5.0.
Since we now have the averages in an aray, we want to find the smallest item in the array. To do that, min_element is used to get us the position of where the element is stored.
The trick here is that min_element returns a pointer to the smallest item, so we need calculate how far this pointer is located from the beginning of the avg array. To do this, the std::distance function is used. This now gives us the position of the smallest item.
The rest of the code just outputs the results.
As you can see, the only loops involved were the input loops. The calculation of the average and the worst average were done using accumulate and min_element, respectively.