Printing Multidimensional Array C++ - c++

How do I print out this multi-dimensional vector? I just can't figure out what to put as a condition in the inner loop in my print section in the code below. I can't seem to figure out how to loop through the array to print grades. Any help would be appreciated.
#include <iostream>
using namespace std;
int main()
{
int course, grades;
int** crsgrd;
// get inputs and asign grades
cout << "Enter number of courses: ";
cin >> course;
crsgrd = new int * [course];
for (int c = 0; c < course; c++) {
cout << "Enter number of grades: ";
cin >> grades;
crsgrd[c] = new int[grades];
for(int g = 0; g < grades; g++) {
cout << "Enter your grade: ";
cin >> crsgrd[c][g];
}
}
// print grade report
for(int c = 0; c < course; c++) {
for(int g = 0; g <= ?????????; g++)
cout << crsgrd[c][g] << " ";
cout << endl;
}
// free the array
for(int i = 0; i < course; i++)
delete [] crsgrd[i];
delete [] crsgrd;
return 0;
}

g < crsgrd[c].size()
Alternatively, you could create your own size function if this is some kind of assignment that doesn’t allow built in functions.

You have created a 2D array, not a standard vector. Arrays do not store their length, so you have to either come up with a way to store the length or switch to another type of storage container.
Here is an example that stores the number of grades as the first element of the array for a given course:
#include <iostream>
using namespace std;
int main()
{
int course, grades;
int** crsgrd;
// get inputs and asign grades
cout << "Enter number of courses: ";
cin >> course;
crsgrd = new int * [course];
for (int c = 0; c < course; c++) {
cout << "Enter number of grades: ";
cin >> grades;
crsgrd[c] = new int[grades + 1]; // extra cell for # of grades
crsgrd[c][0] = grades;
// start storing grades at cell [c][1] as the first cell has the length
for(int g = 1; g < grades+1; g++) {
cout << "Enter your grade: ";
cin >> crsgrd[c][g];
}
}
// print grade report
for(int c = 0; c < course; c++) {
cout<< "Course #" << c+1 << " grades:" << endl;
// use first element as limit for for loop.
// Be sure to print one more element as we have an extra cell
// at the end.
for(int g = 1; g < crsgrd[c][0] + 1; g++)
cout << crsgrd[c][g] << " ";
cout << endl;
}
// free the array
for(int i = 0; i < course; i++)
delete [] crsgrd[i];
delete [] crsgrd;
return 0;
}

Related

2D integer array in c++ with uneven number of elements in each row

The number of rows and columns of this array are given by the user however the number of rows are not the same (the array is uneven) and also the user will fill the array by entering the elements.
This is the code that I wrote but when I try to take input from user, the code crashes after taking some inputs. Please could you help me out and correct my code and point my flaws. Thank you.
#include <iostream>
//2d array
using namespace std;
int main()
{
int row;
int col_x;
cout << "Enter the row number:" << endl;
cin >> row;
//cout<<"Enter the column number:"<<endl;
//cin>>col;
int **a = new int *[row];
for (int r = 0; r < row; r++)
{
cout << "Enter the column no.of array " << r << endl;
cin >> col_x;
a[r] = new int[col_x];
cout << "Enter the elements in the array:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col_x; j++)
{
cin >> a[i][j];
}
}
cout << "The elements in the array:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col_x; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
delete[] a;
a = NULL;
return 0;
}
There was an extra for loop. Also, you have to store the size of each row.
And make the proper deallocation of the 2D array.
#include <iostream>
//2d array
using namespace std;
int main()
{
int row;
cout<<"Enter the row number:"<<endl;
cin>>row;
int **a=new int *[row];
int *col_x = new int [row];
for(int r=0;r<row;r++){
cout<<"Enter the column no.of array "<<r<<endl;
cin>>col_x[r];
a[r]=new int[col_x[r]];
cout<<"Enter the elements in the array:"<<endl;
for(int j=0;j<col_x[r];j++){
cin>>a[r][j];
}
}
cout<<"The elements in the array:"<<endl;
for(int i=0;i<row;i++){
for(int j=0;j<col_x[i];j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
for (int i=0; i<row; ++i)
delete[] a[i];
delete []a;
delete []col_x;
return 0;
}
The way you are getting the input from the user is very vague, and is prone to accessing invalid memory. You are getting the same row many times in the inner loop.
Try something like this:
#include <iostream>
//2d array
using namespace std;
int main() {
int row;
int col_x;
cout << "Enter the row number:" << endl;
cin >> row;
//cout<<"Enter the column number:"<<endl;
//cin>>col;
int ** a = new int * [row];
for (int r = 0; r < row; r++) {
cout << "Enter the column no.of array " << r << endl;
cin >> col_x;
a[r] = new int[col_x];
cout << "Enter the elements in the array:" << endl;
for (int j = 0; j < col_x; j++) {
cin >> a[r][j];
}
}
cout << "The elements in the array:" << endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col_x; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
delete[] a;
a = NULL;
return 0;
}
Also, note that col_x will hold only the size of the last row. So, it's not working for the printing at the end of the code.
Not sure what you are trying to achieve, but the main issue with above code is, that you are accessing non-existing elements of your array. Maybe your loop over r should end in line 18? Even then, you would have to store the number of columns per row in some external variable. I would suggest to use a std::vector as the container instead of fixed arrays, in your case a std::vector< std::vector<int> >. The vector class has a method size() which stores its actual size.
Since you are using C++, you should take advantage of the containers it provides for you to store your data, in this case a vector of vectors would be appropriate:
Live Sample
#include <iostream>
#include <vector>
using namespace std; //<-- for test, souldn't be used
int main() {
int rows, cols, temp;
vector<vector<int>> matrix;
cout << "Enter the row number:" << endl;
cin >> rows;
for (int i = 0; i < rows; i++){
vector<int> v;
cout << "Enter the column no.of array " << i << endl;
cin >> cols;
cout << "The elements in the array:" << endl;
for (int j = 0; j < cols; j++){
cin >> temp;
v.push_back(temp);
}
matrix.push_back(v);
}
cout << endl;
for( auto i: matrix){ //print results
for(int j: i)
cout << j << " ";
cout << endl;
}
}

User input into array. I am confused with output

Most of the components for the array are in place.
I am however wondering what code is missing for the output to match what I am trying to do.
I tried searching for similar array coding. I would like to call the function and for the user to input numbers up to 20 different inputs.
#define size 20
using namespace std;
int i;
void Input(int student[]) {
for(int i = 0; i < size; i++)
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
void display(int student[]) {
for(int i = 0; i < size; i++)
cout << student[i];
}
int main() {
int student[size];
Input(student );
display(student);
return 0;
In your Input function:
void Input(int student[]) {
for(int i = 0; i < size; i++)
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
You not using brackets, so the cin >> student[i]; is outside of the loop. The i from the for loop is no longer in scope, so you are using the i here:
int i;
Which is never given a value, which leads to undefined behavior. Add brackets:
void Input(int student[]) {
for(int i = 0; i < size; i++) {
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
}

c++: how to use char / string 2d array to accept more than 1 sentense from an user?

Below code failed:
#include <iostream>
#include <string>
using namespace std;
int main(){
int a, b;
cout << "how many input you want to give ? ";
cin >> a;
b = a - 1;
string str[b];
for(int i = 0; i <= b; i++){
cout << "Enter a string: ";
getline(cin, str[i]);
}
for(int k = 0; k < a; k++){
cout << "You entered: " << str[k] << endl;
}
return 0;
}
But if I fix the value of 'int a' then the code is running. please help.
Arrays must have a constant size at compile-time so to create an array with dynamic size you can create it on the heap using keyword new and delete[] to free up memory.
Also what is the point in:
cin >> a;
b = a - 1; //?
You can easily do it like this:
int n;
cout << "how many input you want to give ? ";
cin >> n;
string* str = new string[n];
for(int i = 0; i < n; i++){
cout << "Enter a string: ";
getline(cin, str[i]);
}
for(int k = 0; k < n; k++){
cout << "You entered: " << str[k] << endl;
}
Don't forget to clean when you're done:
delete[] str;
You'll want to clear the input buffer, the newline from "How many input you want to give ?" is being fed into the first "Enter a string:".
Add this line after cin>>a;
cin.ignore(INT_MAX, '\n');
Use a vector to store the input.
#include <vector>
#include <string>
#include <iostream>
using names pace std;
int main ()
{
vector <string> input;
string tmp;
while (getline(cin, tmp))
input.push_back(tmp));
for(auto s : input)
cout << s << '\n';
}

2D ArrayLoops C++

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)

Dynamically Allocated Structures

So i am having troubles here. The program works perfectly fine when i enter in 1 for numStudents but get a segmentation fault: 11 when i enter anymore that 1 for numstudents. Am i doing something wrong with the dynamic allocation? I am just lost have done everything i can think of.
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;
//Structure Declaration
struct Student
{
string name;
long long ID;
double *score;
};
//Function prototypes
void calcAvg (int loc, Student test[], double average[], int tests);
int main()
{
int numStudents, numTests; //Get from user
double *averages; //For Dynamic allocation of averages
Student *info; //For Dynamic Allocation
cout << "Enter the number of students you will enter ";
cin >> numStudents;
info = new Student[numStudents];
averages = new double[numStudents];
cout << "\nEnter the number of tests that were taken by the students ";
cin >> numTests;
info->score = new double[numTests];
for(int s = 0; s < numStudents; s++)
{
cout << "Enter student #" << (s+1) << "'s name ";
cin.ignore();
getline(cin, info[s].name);
cout << "Enter " << info[s].name << "'s ID number ";
cin >> info[s].ID;
cout << endl;
for(int t = 0; t < numTests; t++)
{
cout << "\nEnter " << info[s].name << "'s score for test #" <<(t+1) << " ";
cin >> info[s].score[t];
while(info[s].score[t] > 100 || info[s].score[t] < 0)
{
cout << "The score you entered is invalid, try again. ";
cin >> info[s].score[t];
}
}
calcAvg(s, info, averages, numTests);
}
return 0;
}
void calcAvg (int loc, Student test[], double average[], int tests)
{
double total = 0;
for(int i = 0; i < tests; i++)
{
total += test[loc].score[i];
}
average[loc] = total/tests;
cout << average[loc] << endl;
}
You need to repeat this for each student
info->score = new double[numTests];
So you could move it into the loop:
for(int s = 0; s < numStudents; s++)
{
info[s].score = new double[numTests];
...
}
But all this is very error prone - I suggest you look into structures that can handle all this for you like std::vector.