Want to reverse an array of numbers C++ - c++

I have some code written but I'm not sure why the reversed array is not giving me the exact values I need. I created a second array the same size as the first and used nested for loops to fill the second with the contents of the first in reverse.
See below:
#include <iostream>
using namespace std;
int main()
{
// Ask for how big the array is
int n;
cout << "how big is the array?" << endl;
cin >> n;
// create array
int a[n];
// create second array
int b[n];
// ask for contents of the 1st array
cout << "what's in the array?" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
// reverse the array
for (int i = n - 1; i >= 0; i--)
{
for (int k = 0; k < n; k++)
{
b[k] = a[i];
break;
}
}
// print out the new array
for (int k = 0; k < n; k++)
{
cout << b[k] << endl;
}
return 0;
}

you don't need 2 bucles for fill the second array
try with:
//reverse the array
s = 0;
for (int i=n-1;i>=0;i--){
b[n]=a[s];
s++;
}

Try something like this:
#include <algorithm>
#include <iostream>
#include <vector>
namespace {
template <typename IStream>
[[nodiscard]] int readOneIntFrom(IStream& istream) {
int x;
istream >> x;
return x;
}
}
int main()
{
// Ask for how big the array is
std::cout << "how big is the array?" << std::endl;
auto n = readOneIntFrom(std::cin);
// create array
std::vector<int> a;
// ask for contents of the 1st array
std::cout << "what's in the array?" << std::endl;
for (int i = 0; i < n; i++)
{
a.emplace_back(readOneIntFrom(std::cin)); // Make a new entry at the end of a.
}
// Construct b from a backward. (Or do auto b = a; std::reverse(b.begin(), b.end());
auto b = std::vector<int>(a.rbegin(), a.rend());
// print out the new array
for (const auto& bi : b)
{
std::cout << bi << std::endl;
}
return 0;
}

Related

why can't I store values in my 2D vector by push back?

I got stuck in many problems where I was trying to store values in 2D vectors.
So I have written this simple code.
I am just storing and printing my values :
int main()
{
vector<vector<int>> vec;
vector<int> row{1,3,5,7,9,12,34,56};
int i,n,m,rs,vs;
rs=row.size();
cout<<"rs = "<<rs<<endl;
for(i=0;i<(rs/2);i++)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i+4));
}
vs=vec.size();
cout<<vs<<endl;
for(n=0;n<vs;n++)
{
for(m=0;m<2;m++)
{
cout<<vec[n][m]<<" ";
}
cout<<endl;
}
return 0;
}
First you should read Why is “using namespace std;” considered bad practice?.
Declare variables when you use them and not at the beginning of your program.
The vector vec is empty at the beginning. In the loop
for(i=0;i<(rs/2);i++)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i+4));
}
you are taking a reference to the i-th element in vec with
vec[i]
but this element does not exist. This is undefined behavior and can result in a segmentation fault. You can fix it by constructing the vector with the needed elements
#include <iostream>
#include <vector>
int main()
{
std::vector<int> row{1,3,5,7,9,12,34,56};
int rs = row.size();
std::vector<std::vector<int>> vec(rs / 2);
std::cout << "rs = " << rs << '\n';
for(int i = 0; i < rs / 2; ++i)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i + 4));
}
int vs = vec.size();
std::cout << vs << '\n';
for(int n = 0; n < vs; ++n)
{
for(int m = 0; m < 2; ++m)
{
std::cout << vec[n][m] << " ";
}
std::cout << '\n';
}
return 0;
}
In this example the line
std::vector<std::vector<int>> vec(rs / 2);
constructs a vector containing rs / 2 default constructed elements. Alternatively you can start with an empty vector and push back elements in the loop
#include <iostream>
#include <vector>
int main()
{
std::vector<int> row{1,3,5,7,9,12,34,56};
int rs=row.size();
std::vector<std::vector<int>> vec;
std::cout << "rs = " << rs << '\n';
for(int i = 0; i < rs / 2; ++i)
{
vec.push_back({row.at(i), row.at(i+4)});
//
// is similar to:
// vec.push_back({});
// vec.back().push_back(row.at(i));
// vec.back().push_back(row.at(i+4));
//
// is similar to:
// vec.push_back({});
// vec[i].push_back(row.at(i));
// vec[i].push_back(row.at(i+4));
}
int vs = vec.size();
std::cout << vs << '\n';
for(int n = 0; n < vs; ++n)
{
for(int m = 0; m < 2; ++m)
{
std::cout << vec[n][m] << " ";
}
std::cout << '\n';
}
return 0;
}
I recommend the first solution. It's better to allocate memory for all elements and work with it instead of allocate memory in each loop iteration.

dynamic memory allocation using vectors and bubble sort

I need help in adding the user to enter value that becomes array size and will sort array by bubble sort its sorting however I need user to enter the value and it becomes value of an array ie. allocation memory dynamically
#include <iostream>
#include <vector>
//function to swap values
//need to pass by reference to sort the original values and not just these copies
void Swap (int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void BubbleSort (std::vector<int> &array)
{
std::cout<<"Elements in the array: "<<array.size()<<std::endl;
//comparisons will be done n times
for (int i = 0; i < array.size(); i++)
{
//compare elemet to the next element, and swap if condition is true
for(int j = 0; j < array.size() - 1; j++)
{
if (array[j] > array[j+1])
Swap(&array[j], &array[j+1]);
}
}
}
//function to print the array
void PrintArray (std::vector<int> array)
{
for (int i = 0; i < array.size(); i++)
std::cout<<array[i]<<" ";
std::cout<<std::endl;
}
int main()
{
std::cout<<"Enter array to be sorted (-1 to end)\n";
std::vector<int> array;
int num = 0;
while (num != -1)
{
std::cin>>num;
if (num != -1)
//add elements to the vector container
array.push_back(num);
}
//sort the array
BubbleSort(array);
std::cout<<"Sorted array is as\n";
PrintArray(array);
return 0;
}
I tried cin using while however array doesn't print
I modified your version and show you, how you can get the number of elements to sort from the user and hot to dynamically allocate memory in your array.
You will simply use the std::vectors constructor to define a size. Looks then like: std::vector<int> array(numberOfElements);.
The whole adapted code:
#include <iostream>
#include <vector>
//function to swap values
//need to pass by reference to sort the original values and not just these copies
void Swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void BubbleSort(std::vector<int>& array)
{
std::cout << "Elements in the array: " << array.size() << std::endl;
//comparisons will be done n times
for (size_t i = 0; i < array.size(); i++)
{
//compare elemet to the next element, and swap if condition is true
for (size_t j = 0; j < array.size() - 1; j++)
{
if (array[j] > array[j + 1])
Swap(&array[j], &array[j + 1]);
}
}
}
//function to print the array
void PrintArray(std::vector<int> array)
{
for (size_t i = 0; i < array.size(); i++)
std::cout << array[i] << " ";
std::cout << std::endl;
}
int main()
{
std::cout << "Enter the number of data to sort: ";
size_t numberOfElements{ 0 };
std::cin >> numberOfElements;
std::vector<int> array(numberOfElements);
size_t counter{ 0 };
std::cout << "\nEnter "<< numberOfElements << " data\n";
int num = 0;
while ((counter < numberOfElements) &&(std::cin >> num) )
{
array[counter] = num;
++counter;
}
//sort the array
BubbleSort(array);
std::cout << "Sorted array is as\n";
PrintArray(array);
return 0;
}
But, I would recomend to use modenr C++ elements, like algorithms to solve the problem.
See:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t numberOfElements{ 0 };
std::vector<int> array{};
std::cout << "Enter the number of data to sort: ";
std::cin >> numberOfElements;
std::cout << "\nEnter " << numberOfElements << " data values:\n";
std::copy_n(std::istream_iterator<int>(std::cin), numberOfElements, std::back_inserter(array));
std::sort(array.begin(), array.end());
std::cout << "\n\nSorted data:\n\n";
std::copy(array.begin(), array.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}

C++ Array of Pointers not assignable

I need to create 2 arrays, each with 4 elements. One array contains four int values gotten from the user, and the other array contains pointers to the elements of the first array. I keep getting the following error:
array type 'int *[4]' is not assignable
on this line:
my_ptrs = &my_ints;
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int my_ints[4];
int *my_ptrs[4];
float temp;
int num;
for (int x=0; x< 4; x++)
{
cout << "Enter Integer:" << endl;
cin >> num;
my_ints[x] = num;
}
my_ptrs = &my_ints;
for(int k=0; k<=3; k++)
{
for(int j=k+1; j<=3; j++)
{
if(my_ptrs[k]>my_ptrs[j])
{
temp=*my_ptrs[k];
my_ptrs[k]=my_ptrs[j];
*my_ptrs[j]=temp;
}
}
cout << my_ptrs[k] << " ";
}
return 0;
}
Your apparent intent is to have each pointer in my_ptrs to point to the corresponding value in my_ints.
I'm afraid there are no shortcuts here, using a single assignment. You have to do it the hard way:
for (int i=0; i<4; ++i)
my_ptrs[i]=&my_ints[i];
You cannot assign a pointer-to-an-array to an array variable, like you are trying to do. But what you can do instead is either:
initialize the second array in its declaration directly:
int my_ints[4];
int* my_ptrs[4] = {&my_ints[0], &my_ints[1], &my_ints[2], &my_ints[3]};
populate the array in a separate loop:
int my_ints[4];
int* my_ptrs[4];
for (int i = 0; i < 4; ++i)
my_ptrs[i] = &my_ints[i];
That being said, based on what you are trying to do ("i want to print the my_ptrs array in ascending order"), you could just get rid of the second array altogether and use the std::sort() algorithm instead:
Sorts the elements in the range [first, last) in ascending order.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int my_ints[4];
for (int x = 0; x < 4; ++x)
{
cout << "Enter Integer:" << endl;
cin >> my_ints[x];
}
std::sort(my_ints, my_ints+4);
for(int k = 0; k < 4; ++k)
cout << my_ints[k] << " ";
return 0;
}

Finding the size of an array

The idea of the program is to input elements in an array. Then give the integer 'x' a value. If 'x' is 3 and the array a[] holds the elements {1,2,3,4,5,6}, we must "split" a[] into two other arrays. Lets say b[] and c[].
In b[] we must put all values lower or equal to 3 and in c[] all values greater than 3.
My question is- How can i express the 3 elements in b[i]?
#include <iostream>
using namespace std;
int main()
{
int a[6];
int b[6];
int c[6];
int d;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
cin >> d;
for (int i = 0; i < 6; i++) {
if (d >= a[i]) {
b[i] = a[i]; // if d is 3, then i have 3 elements. How can i express them?
}
}
for (int i = 0; i < 6; i++) {
if (d< a[i]) {
c[i] = a[i];
}
}
for (int i = 0; i < 3; i++) {
cout << b[i];
}
cout << endl;
for (int i = 3; i < 6; i++) {
cout << c[i];
}
return 0;
}
I think all you're trying to do is have a way to determine how many int values you're copying from a[] to either b[] or c[]. To do that, introduce two more counters that start at zero and increment with each item copied to the associated array:
Something like this:
#include <iostream>
using namespace std;
int main()
{
int a[6];
int b[6], b_count=0; // see here
int c[6], c_count=0; // see here
int d;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
cin >> d;
for (int i = 0; i < 6; i++) {
if (d >= a[i]) {
b[b_count++] = a[i]; // see here
}
}
for (int i = 0; i < 6; i++) {
if (d< a[i]) {
c[c_count++] = a[i]; // see here
}
}
for (int i = 0; i < b_count; i++) { // see here
cout << b[i];
}
cout << endl;
for (int i = 3; i < c_count; i++) { // and finally here
cout << c[i];
}
return 0;
}
Now, if you want b[] or c[] to be dynamic in their space allocation, then dynamic-managed containers like st::vector<> would be useful, but I don't think that is required for this specific task. Your b[] and c[] are already large enough to hold all elements from a[] if needed.
WhozCraigs answer does a good job showing what you need to solve this using traditional arrays according to your tasks requirements.
I'd just like to show you how this can be done if you were allowed the full arsenal of the standard library. It is why people are calling for you to use std::vector. Things gets simpler that way.
#include <algorithm>
#include <iostream>
int main()
{
int a[6] = {1, 2, 3, 4, 5, 6 }; // Not using input for brevity.
int x = 3; // No input, for brevity
// Lets use the std:: instead of primitives
auto first_part = std::begin(a);
auto last = std::end(a);
auto comparison = [x](int e){ return e <= x; };
auto second_part = std::partition(first_part, last, comparison);
// Print the second part.
std::for_each(second_part, last, [](int e){ std::cout << e; });
// The first part is first_part -> second_part
}
The partition function does exactly what your problem is asking you to solve, but it does it inside of the array a. The returned value is the first element in the second part.
use std::vectors. do not use int[]s.
with int[]s (that are pre-c++11) you could, with a few heavy assumptions, find array length with sizeof(X)/sizeof(X[0]); This has, however, never been a good practice.
in the example you provided, probably you wanted to:
#define MAX_LEN 100
...
int main() {
int a[MAX_LEN];
int b[MAX_LEN];
int c[MAX_LEN];
int n;
std::cout << "how many elements do you want to read?" << std::endl;
std::cin >> n;
and use n from there on (these are common practice in programming schools)
Consider a function that reads a vector of ints:
std::vector<int> readVector() {
int n;
std::cout << "how many elements do you want to read?" << std::endl;
std::cin >> n;
std::vector<int> ret;
for (int i=0; i<n; i++) {
std::cout << "please enter element " << (i+1) << std::endl;
int el;
std::cin >> el;
ret.push_back(el);
}
return ret;
}
you could use, in main, auto a = readVector(); auto b = readVector(); a.size() would be the length, and would allow to keep any number of ints
Here's an example of how you'll approach it once you've a little more experience.
Anything you don't understand in here is worth studying here:
#include <iostream>
#include <vector>
#include <utility>
std::vector<int> get_inputs(std::istream& is)
{
std::vector<int> result;
int i;
while(result.size() < 6 && is >> i) {
result.push_back(i);
}
return result;
}
std::pair<std::vector<int>, std::vector<int>>
split_vector(const std::vector<int>& src, int target)
{
auto it = std::find(src.begin(), src.end(), target);
if (it != src.end()) {
std::advance(it, 1);
}
return std::make_pair(std::vector<int>(src.begin(), it),
std::vector<int>(it, src.end()));
}
void print_vector(const std::vector<int>& vec)
{
auto sep = " ";
std::cout << "[";
for (auto i : vec) {
std::cout << sep << i;
sep = ", ";
}
std::cout << " ]" << std::endl;
}
int main()
{
auto initial_vector = get_inputs(std::cin);
int pivot;
if(std::cin >> pivot)
{
auto results = split_vector(initial_vector, pivot);
print_vector(results.first);
print_vector(results.second);
}
else
{
std::cerr << "not enough data";
return 1;
}
return 0;
}
example input:
1 2 3 4 5 6
3
expected output:
[ 1, 2, 3 ]
[ 4, 5, 6 ]

C++ How to change the output on a new array

So I wrote a program that is supposed select the perfect squares from an array and put it into another array. Example: (2,4,13,5,25,66) and the second array(the result) should look like this (4,25)
My result looks like this (0,4,0,0,25,0) ...so its half good ...how to make it show only 4,25 ?
#include<iostream.h>
#include<math.h.>
int main()
{
int A[100],i,n,p,j;
cout << "Number of array elements=";
cin >> n;
for(i=1;i<=n;i++)
{
cout<<"A["<<i<<"]=";
cin>>A[i];
}
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
A[j]=A[i];
else
A[i]=0;
cout << A[i] << " ";
}
return 0;
}
USING ONLY c++ basic commands...as i did
You need to keep a separate count of how many perfect squares you've found and use that to place your answers into an array of perfect squares:
int squares[???];
// ...
if(p*p==A[i]) {
squares[squaresFound]=A[i];
squaresFound++;
}
The problem now will be to decide how long the squares array should be. You don't know ahead of time how many squares you're going to get. Are you going to have it the same size as A and fill the rest with 0s? Or do you want the array of squares to be exactly the right size?
If you want it to be the right size, you're much better off using a std::vector:
std::vector<int> squares;
// ...
if(p*p==A[i]) {
squares.push_back(A[i]);
}
But I think your silly "only basic C++ commands" restriction will not allow you to do this.
You talk about a second array (the result), yet your code declares only one array! Additionally, you reference A[j], but your j has not be initialized.
You should declare another array B[100], initialize j to zero, and then use this code when you find a square:
int j = 0;
for (int i=0 ; i != n ; i++) {
int p = sqrt(A[i]);
if(p*p==A[i]) {
B[j++] = A[i];
}
}
Make another array, remove all occurrences of 0 from the resultArray and add non-0 to newArray.
OR
int j=0
if(A[i]==p*p)
squares[j++]=A[i];
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int A[100];
int n;
cout << "Number of array elements = " << endl;
cin >> n;
for(int i = 0; i < n; i++)
{
cout << "A[" << i << "] = ";
cin >> A[i];
}
int B[100];
int cnt_sqr = 0;
for(int i = 0; i < n; i++)
{
int p = sqrt(A[i]);
if (p * p == A[i])
{
B[cnt_sqr++] = A[i];
}
}
for (int i = 0; i < cnt_sqr; i++)
{
cout << B[i] << ' ';
}
return 0;
}
Full code of that about what you were told above
If you do not want to modify your code you can write the following:
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
{
cout << A[i] << " ";
}
}
It will print you only perfect squares.
If you want to copy elements to another array:
int squares[100] = {0}; // Assuming that all values can be perfect squares
int square_count = 0;
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
{
squares[square_count++] = A[i];
}
}