How to store each user input into array? - c++

I used a do while loop to ask user to enter integer as long as its not 0 or it will exit the program. I'm stuck on how to store every user input into the dynamically allocated array.
#include <iostream>
using namespace std;
int main() {
int *A;
A= new int();
int n;
do{
cout<<"Enter integer: "<<endl;
cin>>n;
cout<< *A + n << endl;
}while(n!=0);
return 0;
}

You are allocating a single int, not an array of ints.
Also, even if you were allocating an array, a statement like *A + n does not add n to the array. It dereferences A to access the value of the 1st int in the array, and then adds n to that value.
Try something more like this instead:
#include <iostream>
using namespace std;
int main() {
int *A = nullptr;
int count = 0, n;
do{
cout << "Enter integer: " << endl;
cin >> n;
if (n == 0) break;
int *newA = new int[count+1];
for(int i = 0; i < count; ++i) newA[i] = A[i];
newA[count] = n;
delete[] A;
A = newA;
++count;
cout << A[count-1] << endl;
}
while (true);
delete[] A;
return 0;
}
Alternatively, try to avoid reallocating the array on every input, eg:
#include <iostream>
using namespace std;
int main() {
int *A = new int[5];
int count = 0, cap = 5, n;
do{
cout << "Enter integer: " << endl;
cin >> n;
if (n == 0) break;
if (count == cap)
{
int newCap = cap * 1.5;
int *newA = new int[newCap];
for(int i = 0; i < count; ++i) newA[i] = A[i];
delete[] A;
A = newA;
cap = newCap;
}
A[count] = n;
++count;
cout << A[count-1] << endl;
}
while (true);
delete[] A;
return 0;
}
That being said, a better option is to use a std::vector, which will handle the dynamic memory for you, eg:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> A;
int n;
do{
cout << "Enter integer: " << endl;
cin >> n;
if (n == 0) break;
A.push_back(n);
cout << A.back() << endl;
}
while (true);
return 0;
}

Related

Code won't run, getting stuck at while loop

When I try to run the program visual studio code gets stuck at the while look and won't run the code. When copy and pasting the code to an online compiler the code runs. Also I can't use vectors or reverse from the library.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <ctime>
using namespace std;
void reverse(double* a, int size)
{
double* left = a;
double* right = a + size - 1;
while (left < right)
{
double temp = *left;
*left++ = *right;
*right-- = temp;
}
}
int main()
{
int size = 0;
float input;
double* a = new double[size];
int capacity = 10;
cout << "Please enter the values: ";
while (cin >> input)
{
if (cin.fail())
{
cin.clear();
}
if (size == capacity) {
capacity *= 2;
}
a[size++] = input;
if (size == capacity)
{
capacity *= 2;
double* b = new double[capacity];
for (int i = 0; i < size; i++)
{
b[i] = a[i];
}
delete[] a;
a = b;
}
}
cout << "The input values are: ";
for (int i = 0; i < size; i++)
{
cout << a[i];
if (i < size - 1)
cout << ", ";
}
cout << endl;
reverse(a, size);
cout << "The reversed values are: ";
for (int i = 0; i < size; i++)
{
cout << a[i] << " ";
if (i < size - 1)
cout << ", ";
}
cout << endl;
return 0;
}
I tried using a break command it didn't work. I'm expecting the code to run the function and take in all the inputs and print the array and its reverse
can you check if this is the answer you wanted, I made the input variable integer type where you were using float/double type, I thought it is the problem, also you did not update the input in the while loop so I used while(input--) . These are the changes I have made I do not know if this is the answer you wanted. I added the comment where I made changes to the code. Hope it is helpful.
#include <iomanip>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <ctime>
using namespace std;
void reverse(double* a, int size)
{
double* left = a;
double* right = a + size - 1;
while (left < right)
{
double temp = *left;
*left++ = *right;
*right-- = temp;
}
}
int main()
{
int size = 0;
int input; // I made input variable integer type you were using float type
double* a = new double[size];
int capacity = 10;
cout << "Please enter the values: ";
cin >> input ; // took the value of the input variable here
while (input--) // you did not decrement the input variable
{
if (cin.fail())
{
cin.clear();
}
if (size == capacity) {
capacity *= 2;
}
a[size++] = input;
if (size == capacity)
{
capacity *= 2;
double* b = new double[capacity];
for (int i = 0; i < size; i++)
{
b[i] = a[i];
}
delete[] a;
a = b;
}
}
cout << "The input values are: ";
for (int i = 0; i < size; i++)
{
cout << a[i];
if (i < size - 1)
cout << ", ";
}
cout << endl;
reverse(a, size);
cout << "The reversed values are: ";
for (int i = 0; i < size; i++)
{
cout << a[i] << " ";
if (i < size - 1)
cout << ", ";
}
cout << endl;
return 0;
}```

c++ variable sized arrays from Hackerrank with vectors

I wanted to solve a challenge named "Variable sized Arrays" on Hackerrank and I wanted to do that using vectors. The Code I wrote, doesn't work properly and I tried debugging it, but I'm getting nowhere. I'll be grateful for
Here's the challenge:
Consider an n-element array,a, where each index i in the array contains a reference Kito an array of integers (where the value of Ki varies from array to array). See the Explanation section below for a diagram.
Given a, you must answer q queries. Each query is in the format i j, where i denotes an index in array and j denotes an index in the array located at a[i] . For each query, find and print the value of element j in the array at location on a[i]a new line.
Input Format
The first line contains two space-separated integers denoting the respective values of n (the number of variable-length arrays) and q (the number of queries).
Each line of the subsequent lines contains a space-separated sequence in the format k a[i]0 a[i]1 … a[i]k-1 describing the k-element array located at a[i].
Each of the q subsequent lines contains two space-separated integers describing the respective values of i (an index in array a) and j (an index in the array referenced by a[i]) for a query.
Sample Input
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Sample Output
5
9
So here's my code for this (I'll leave it with the couts for debugging):
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::endl;
int main() {
int numberOfQueries = 0;
int numberOfArrays = 0;
cout << "Enter Nr.Of Arrays followed by Nr.Of Queries:";
cin >> numberOfArrays >> numberOfQueries;
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
cout << "Nr.Of Queries: " << numberOfQueries << endl;
vector<vector<int>>multiArray;
cout << "MultiArray size: " << multiArray.size();
while (numberOfArrays != 0) {
int vsize = 0;
cout << "\nenter array starting by its size: ";
cin >> vsize;
cout << " Size entered is: " << vsize << endl;
vector<int> vec1(vsize);
cout << "Array Size is: " << vec1.size() << endl;
//int element = 0;
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
multiArray.push_back(vec1);
numberOfArrays--;
cout << "MultiArray size: " << multiArray.size();
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
};
while (numberOfQueries > 0) {
int i = 0, j = 0;
cout << "\nQuery indexes:";
cin >> i >> j;
cout << multiArray[i][j];
numberOfQueries--;
}
}
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
should be something like
for (int i = 0; i < vsize; ++i) {
int elem;
cin >> elem;
cout << "Element is: " << elem << "\n";
vec1.push_back(elem);
}
while (cin >> vsize) isn't going to stop asking for input until you get end of file or an error. But you know how many inputs to expect so code that in a for loop.
My answer.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q;
cin >> n >> q ;
vector<int> a[n];
int k;
for(int i = 0; i < n; i++)
{
cin >> k;
for (int j = 0; j < k; j++)
{
int val_a_i_j;
cin >> val_a_i_j;
a[i].push_back(val_a_i_j);
}
};
for (int i = 0; i < q; i++)
{
int a_i, j;
cin >> a_i >> j;
cout << a[a_i][j] << '\n';
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a , b;
cin >> a >> b;
vector<int> arr[a];
for(int i= 0 ; i < a ; i++)
{
int m;
cin >> m;
int o;
for(int j=0;j<m;j++)
{
cin >> o;
arr[i].push_back(o);
}
}
int r,s;
for(int k=1;k<b;k++)
{
cin>>r>>s;
cout <<a[r][s]<< endl;
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, q;
cin >> n >> q;
vector<int>* a;
a= new vector<int>[n];
int p;
int k;
for (p = 0;p < n;p++) {
cin >> k;
for (int i = 0; i < k; i++) {
int o;
cin >>o;
a[p].push_back(o);
}
}
int r, s;
for (p = 0;p < q;p++)
{
cin >> r >> s;
cout << a[r][s]<<endl;
}
return 0;
}
This problem is about handling vectors of the vector.
int main() {
int n,q;
cin>>n>>q;
vector<vector<int> > a;//creating vectors of vector
int k;
for (int i = 0; i < n; i++)
{
cin >>k;
vector <int> row; // creating vector
for (int j = 0; j < k; j++)
{
int val;
cin>> val;
row.push_back(val);
}
a.push_back(row);
}
for (int l=0; l < q; l++)
{
int i,j;
cin>>i>>j;
// checking boundary conditions
if ((i >= 0 && i < a.size() ) && (j >=0 && j < a[i].size()))
{
cout<<a[i][j]<<endl;
}
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<vector<int>> MultiArry;
vector<int> output;
int n1,n2, q;
int i,j;
cin >> n1 >> q;
MultiArry.resize(n1);
output.resize(q);
for(int i=0;i<n1;i++)
{
cin >> n2;
MultiArry[i].resize(n2);
for(int j=0;j<n2;j++)
{
cin >> MultiArry[i][j];
}
}
for(int ii=0;ii<q;ii++)
{
cin >> i >> j;
output[ii] = MultiArry[i][j];
}
for(int i=0;i<q;i++)
cout << output[i] << endl;
return 0;
}

Using dynamic memory allocation to add elements into an array

I'm supposed to write some code to ask the user to enter an array (1.3 4 5.2 16.3 9.99 7.21 4.5 7.43 11.21 12.5).
After that, I create a new array with a bigger size (double the size), copy all the elements from the old array to the new one, then ask the user to continue to enter 5 more elements to the new array: 1.5 4.5 9.5 16.5 7.5 11.5, and then print out the final array (15 elements).
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
double* read_data(int& size)
{
int max = 10;
double* a = new double[max]; // allocated on heap
size = 0;
cout << "Enter the array: " << endl;
while (cin >> a[size])
{
size++;
}
if (size >= max)
{
double* temp = new double[max * 2];
for (int i = 0; i < size; i++)
{
temp[i] = a[i];
}
delete[] a;
a = temp;
max = max * 2;
}
return a;
}
int main ()
{
int input1, input2, input3, input4, input5;
int size = 0;
double* arr = read_data(size);
cout << "Please enter 5 more elements: " << endl;
cin >> input1 >> input2 >> input3 >> input4 >> input5;
arr[10] = input1;
arr[11] = input2;
arr[12] = input3;
arr[13] = input4;
arr[14] = input5;
cout << "The final array is: " << endl;
for (int i = 0; i < 15; i++)
{
cout << arr[i];
}
system("pause");
return 0;
}
It doesn't let me enter 5 more elements and I don't know why.
Please help.
You are waiting for the input stream to enter a "false" state, that happens most visibly when there is an end of file character inputted to the stream. So while inputting code to the terminal if you type in a -d you should see the code move onto the segment after the while loop.
To get away from this problem you will have to specify a limit to the array you are getting from the user so as to not overwrite memory out of bounds.
So change your code to this
#include <iostream>
#include <string>
using namespace std;
double* read_data(int& size)
{
int max = 10;
double* a = new double[max]; // allocated on heap
size = 0;
cout << "Enter the array: " << endl;
while (size < 10 && cin >> a[size])
{
size++;
}
if (size >= max)
{
double* temp = new double[max * 2];
for (int i = 0; i < size; i++)
{
temp[i] = a[i];
}
delete[] a;
a = temp;
max = max * 2;
}
return a;
}
int main ()
{
int input1, input2, input3, input4, input5;
int size = 0;
double* arr = read_data(size);
cout << "Please enter 5 more elements: " << endl;
cin >> input1 >> input2 >> input3 >> input4 >> input5;
arr[10] = input1;
arr[11] = input2;
arr[12] = input3;
arr[13] = input4;
arr[14] = input5;
cout << "The final array is: " << endl;
for (int i = 0; i < 15; i++)
{
cout << arr[i] << ' ';
} cout << endl;
system("pause");
return 0;
}
Notice how I added in the check for the size variable before the "cin" statement, this is referred to as short circuiting (https://en.wikipedia.org/wiki/Short-circuit_evaluation). I do not consider this good style myself but I have included it here to show you how input statements are used in while loops and can cause bad behavior if you don't use it properly.
Also I added in a cout << endl; to flush the stream buffer so that the output does go to the screen before the pause
I just read what you said in the comments and I suggest the following code for the purpose to quit when a 'q' to exit.
#include <iostream>
#include <string>
using namespace std;
double* read_data(int& size)
{
int max = 10;
double* a = new double[max]; // allocated on heap
size = 0;
cout << "Enter the array: " << endl;
char character;
while (size < 10 && cin >> character)
{
if (character == 'q') break;
a[size] = character - '0';
size++;
}
if (size >= max)
{
double* temp = new double[max * 2];
for (int i = 0; i < size; i++)
{
temp[i] = a[i];
}
delete[] a;
a = temp;
max = max * 2;
}
return a;
}
int main ()
{
int size = 0;
double* arr = read_data(size);
cout << "Please enter 5 more elements: " << endl;
for (int i = size; i < size + 5; ++i) {
cin >> arr[i];
}
// add 5 to the size
size += 5;
cout << "The final array is: " << endl;
for (int i = 0; i < size; i++)
{
cout << arr[i] << ' ';
} cout << endl;
system("pause");
return 0;
}

can not swap array elements c++

I am new to C++. I am trying to solve a problem in the textbook: swap the first and last element in an array. But when I run the code I wrote, nothing happened and even the sentence "Please enter the numbers in the array: " does not show up. Anyone could give some help? Thanks.
#include <iostream>
using namespace std;
int swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
cout << "Please enter the numbers in the array: " << endl;
int input;
cin >> input;
for(int i=0; i<SIZE; i++)
{
test[i] = input;
}
swap(test, SIZE);
cout << test[SIZE] << endl;
return 0;
}
There were a few mistakes:
You should get the input inside the loop and then assign it to the test array.
When printing the swapped value, access the test array with SIZE-1 instead of SIZE, because array indexes run from 0 to SIZE-1, inclusive.
You declared swap() as returning int, but provided no return statement (this suggests that you haven't enabled enough warnings from your compiler).
#include <iostream>
using namespace std;
void swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
int input;
cout << "Please enter the numbers in the array: " << endl;
for(int i=0; i<SIZE; i++)
{
cin >> input;
test[i] = input;
}
swap(test, SIZE);
cout << test[SIZE-1] << endl;
return 0;
}
#include <iostream>
using namespace std;
//Here return type should be void as you are not returning value.
void swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
cout << "Please enter the numbers in the array: " << endl;
//USE LOOP TO TAKE INPUT ONE BY ONE IN AN ARRAY
for(int i = 0; i < SIZE; i++)
cin >> test[i];
swap(test, SIZE);
//USE LOOP TO DISPLAY ELEMENT ONE BY ONE
for(int i = 0; i < SIZE; i++)
cout << test[i] << endl;
return 0;
}

how to print an array backwards

The user enteres a number which is put in an array and then the array needs to be orinted backwadrds
int main()
{
int numbers[5];
int x;
for (int i = 0; i<5; i++)
{
cout << "Enter a number: ";
cin >> x;
numbers[x];
}
for (int i = 5; i>0 ; i--)
{
cout << numbers[i];
}
return 0;
}
You're very close. Hope this helps.
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int numbers[5];
/* Get size of array */
int size = sizeof(numbers)/sizeof(int);
int val;
for(int i = 0; i < size; i++) {
cout << "Enter a number: ";
cin >> val;
numbers[i] = val;
}
/* Start index at spot 4 and decrement until k hits 0 */
for(int k = size-1; k >= 0; k--) {
cout << numbers[k] << " ";
}
cout << endl;
return 0;
}
You are very close to your result but you did little mistakes, the following code is the correct solution of the code you have written.
int main()
{
int numbers[5];
int x;
for (int i = 0; i<5; i++)
{
cout << "Enter a number: ";
cin >> numbers[i];
}
for (int i = 4; i>=0; i--)
{
cout << numbers[i];
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
//get size of the array
int arr[1000], n;
cin >> n;
//receive the elements of the array
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
//swap the elements of indexes
//the condition is just at "i*2" be cause if we exceed these value we will start to return the elements to its original places
for (int i = 0; i*2< n; i++)
{
//variable x as a holder for the value of the index
int x = arr[i];
//index arr[n-1-i]: "-1" as the first index start with 0,"-i" to adjust the suitable index which have the value to be swaped
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = x;
}
//loop for printing the new elements
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
//print numbers in an array in reverse order
int myarray[1000];
cout << "enter size: " << endl;
int size;
cin >> size;
cout << "Enter numbers: " << endl;
for (int i = 0; i<size; i++)
{
cin >> myarray[i];
}
for (int i = size - 1; i >=0; i--)
{
cout << myarray[i];
}
return 0;
}
of course you can just delete the cout statements and modify to your liking
this one is more simple
#include<iostream>
using namespace std;
int main ()
{
int a[10], x, i;
cout << "enter the size of array" << endl;
cin >> x;
cout << "enter the element of array" << endl;
for (i = 0; i < x; i++)
{
cin >> a[i];
}
cout << "reverse of array" << endl;
for (i = x - 1; i >= 0; i--)
cout << a[i] << endl;
}
answer in c++. using only one array.
#include<iostream>
using namespace std ;
int main()
{
int array[1000] , count ;
cin >> count ;
for(int i = 0 ; i<count ; i++)
{
cin >> array[i] ;
}
for(int j = count-1 ; j>=0 ; j--)
{
cout << array[j] << endl;
}
return 0 ;
}
#include <iostream>
using namespace std;
int main ()
{
int array[10000];
int N;
cout<< " Enter total numbers ";
cin>>N;
cout << "Enter numbers:"<<endl;
for (int i = 0; i <N; ++i)
{
cin>>array[i];
}
for ( i = N-1; i>=0;i--)
{
cout<<array[i]<<endl;
}
return 0;
}