Code won't run, getting stuck at while loop - c++

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;
}```

Related

How to store each user input into array?

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;
}

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;
}

Finding a specific number in a random array?

Below is the code I've written to find the largest and smallest number in an array of 100 integers(which are random).
My question is for the user to enter a number and find the location of the number the user entered. For example: "The number 230 was found at array location 34" or something like that.
How do I go about this question? My attempt looks something like
cout << "Enter #: ";
cin >> Input;
if(1){
for (int i = 0; i < 100 : i++){
if (Input == arr[i]
cout << "Location: " << i << endl;
} else
cout << "Input was not found ";
#include "stdafx.h"
#include <ctime>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
int small, big;
int arr[100];
srand(time(0));
for(int i=0; i < 100; i++) {
arr[i] = rand() % 1000;
}
for(int i=0; i < 100; i++) {
cout << arr[i] << " ";
}
cout << endl;
big = small = arr[0];
for (int i = 0; i < 100; i++) {
if (arr[i] > big) {
big = arr[i];
}
if(arr[i] < small) { // compares smallest value with current element
small = arr[i];
}
}
}
A simple (and not ideal) solution is to loop over the array until the desired number is found. Something along the lines of:
const int N = 100;
int arr[N];
for (int i = 0; i < N; i++) {
arr[i] = rand() % 1000;
}
// Number to search for
int target = 11;
// Single loop searching for target
int index = -1;
for (int i = 0; i < N; i++) {
if (arr[i] == target) {
index = i;
break; // break when target found
}
}
if (index != -1) {
cout << "Found at " << index << "\n";
}
else {
cout << "Not Found\n";
}
However, you should use a vector whenever possible instead of an array. One benefit of using a vector is the ability to use the standard library find function.
#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
vector<int> vec;
// fill vec with random numbers
for (int i = 0; i < 100; i++) {
int random_number = rand() % 1000;
vec.push_back(random_number); // adds random_number to end of vec
}
// Number we are searching for
int target = 7;
// find an iterator pointing to target if it exists
// else it will be vec.end()
auto it = find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
// find distance of it from beggining of vector
// i.e. vec[index] == target
int index = distance(vec.begin(), it);
cout << "Found " << target << " at " << index << "\n";
}
else {
cout << "Not Found\n";
}
}

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;
}

C++ array size by user input

I'm trying to write a program that will have a user input size for an array, and then take values into that array. I initially tried
int sz = 51;
double Arr[sz];
Which led to compilation errors. Apparently dynamic allocation of the variable has to happen, and I'd rather avoid that if possible. So I modified my code (current state as shown below) which now only throws "expected primary-expression before ']' token". Is there a way to fix this and I'm just not seeing it, or do I need to use dynamic allocation?
Thanks for your time!
#include <iostream>
#include <iomanip> //for setprecision
using namespace std;
int sz = 51;
double n=0;
double Arr[0];
void get_input(double Arr[], int &sz){ //gets input
do{
cout<< "Enter size: "<< endl;
cin>> sz;
if (sz<0 || sz>50){
cout<< "Invalid size, enter a value between 0 and 50"<<endl;
}
}while(sz<0 || sz>50);
for( int i=0; i<sz; i++){
cin>> Arr[i];
}
}
double calcSum( double Arr[], int sz){ //finds sum
for(int i=0; i<sz; i++){
n+= Arr[i];
}
return(n);
}
void printArray(double Arr[], int sz){ //prints array elements
for(int i=0; i<sz; i++){
cout<< Arr[i]<< setprecision(2)<<" ";
if(i%7 == 0)
cout<< endl;
}
}
int main()
{
double Arr[sz];
get_input(Arr[], sz); //error here
printArray(Arr[], sz); //error here
return 0;
}
VLAs (e.g. Arr[sz]) are only supported as extensions in C++. They aren't part of the official language standard. You should use std::vector instead.
Just use a std::vector, there's a standard library in C++ for this reason.
Demo:
notes: you don't need the globals (they are shadowed by the locals and you pass them by reference anyways)
Live On Coliru
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
using array_t = std::vector<double>;
void get_input(array_t& Arr) { // gets input
size_t sz = 51; // unsigned types cannot be negative
do {
cout << "Enter size: " << endl;
cin >> sz;
if (sz > 50) {
cout << "Invalid size, enter a value between 0 and 50" << endl;
}
} while (sz > 50);
for (size_t i = 0; i < sz; ++i) {
double v;
if (cin >> v)
Arr.push_back(v);
else
std::cerr << "Error reading input\n";
}
//assert(sz = Arr.size());
}
double calcSum(array_t const& Arr) { // finds sum
double n = 0;
for (size_t i = 0; i < Arr.size(); ++i) {
n += Arr[i];
}
return n;
}
void printArray(array_t const& Arr) { // prints array elements
for (size_t i = 0; i < Arr.size(); ++i) {
cout << Arr[i] << setprecision(2) << " ";
if (i % 7 == 6)
cout << endl;
}
}
int main() {
array_t Arr;
get_input(Arr);
printArray(Arr);
std::cout << "\nSum: " << calcSum(Arr) << "\n";
}
When entering 3 1 2 3 you get:
Enter size: 3
1 2 3
1 2 3
Sum: 6