Swapping two initialized arrays in C++ using Void and Pointers - c++

I need to write a C++ program where it swaps between two 1-dimensional
arrays using pointers and functions. Firstly, a void function named showValues to display both arrays before swapping takes and also a void function named swap to swap the elements between both arrays.
My question is: I'm supposed to swap the function but for some reason it wont run and I am not sure where is the error in my code
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE = 5;
void showValues(int[],int[]);
void swap(int[],int[]);
int main() {
int array1[SIZE] = {10,20,30,40,50};
int array2[SIZE] = {60,70,80,90,100};
showValues (array1, array2);
swap(array1, array2);
return 0;
}
void showValues(int array1[], int array2[]){
cout<<"The original arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}
void swap(int array1[], int array2[])
{
int temp,i;
for(i=0; i<5; ++i)
{
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
}
cout << "\nThe swapped arrays are as shown below: " << endl;
cout << " Array 1 is: ";
for (int i = 0; i < 5; ++i) {
cout << array1[i] << " ";
}
cout << "\n Array 2 is: ";
for (int i = 0; i < 5; ++i) {
cout << array2[i] << " ";
}
}

This part of your code doesn't make sense:
temp = array1[SIZE];
array1[SIZE] = array2[SIZE];
array2[SIZE] = temp;
SIZE is 5. So, you are accessing array1[5] and array2[5], i.e. the 6th element of the array. Yet, your arrays have only 5 elements to begin with (array1[0] to array1[4], same for array2), so you are accessing elements beyond the end of the array, which is undefined behavior that is probably just corrupting memory somewhere!
You probably meant to use i here, not SIZE, then the code makes sense. Instead, it would be useful to replace the "magic number" 5 with SIZE:
for(i = 0; i < SIZE; ++i)
{
temp = array1[i];
array1[i] = array2[i];
array2[i] = temp;
}

The void swap(int array1[], int array2[]) function is where you are having trouble. You actually don't even need to have another function for the swapping. You could just use std::swap() which is defined in the #include <utility> header. Since both arrays have the same size.
For example you could do something along these lines:
#include <iostream>
#include <iomanip>
#include <utility>
const int SIZE = 5;
void showValues(int[], int[]);
void swap(int[], int[]);
int main() {
int array1[SIZE] = { 10,20,30,40,50 };
int array2[SIZE] = { 60,70,80,90,100 };
int n = sizeof(array1) / sizeof(array2[0]);
showValues(array1, array2);
std::swap(array1, array2);
std::cout << "\n\nThe swapped arrays are as shown below:\n ";
std::cout << "\nArray 1 is: ";
for (int i = 0; i < n; i++)
std::cout << array1[i] << ", ";
std::cout << "\nArray 2 is: ";
for (int i = 0; i < n; i++)
std::cout << array2[i] << ", ";
return 0;
}
void showValues(int array1[], int array2[]) {
std::cout << "The original arrays are as shown below: " << std::endl;
std::cout << "\nArray 1 is: ";
for (int i = 0; i < 5; ++i) {
std::cout << array1[i] << " ";
}
std::cout << "\nArray 2 is: ";
for (int i = 0; i < 5; ++i) {
std::cout << array2[i] << " ";
}
}
Also consider not using using namespace std;.

Related

How to properly insert and display data in an dynamically allocated arrays in C++?

I've been having trouble trying to properly display the correct memory address so I don't know in which memory address I'm inputting data.
#include <iostream>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i++) {
cout << "Enter value for address " << p << ": ";
cin >> p[i];
}
for(int i = 0; i < 2; i++) {
cout << *p << " " << p << endl;
p++;
}
}
Here is the output when inputting data:
Here is the output when displaying them:
My concern is it doesn't output the correct memory address when inputting data.
But when displaying them it seems to have no problem displaying the correct memory address.
Your input loop is displaying the p pointer as-is (ie, the base address of the array) on every iteration. It is not adjusting the pointer on each iteration, unlike your output loop which does.
You are also leaking the array, as you are not delete[]'ing it when you are done using it.
Try this instead:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i++) {
cout << "Enter value for address " << &p[i] << ": ";
cin >> p[i];
}
for(int i = 0; i < 2; i++) {
cout << p[i] << " " << &p[i] << endl;
}
delete[] p;
return 0;
}
Alternatively:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
int *elem = p;
for(int i = 0; i < 2; i++) {
cout << "Enter value for address " << elem << ": ";
cin >> *elem;
++elem;
}
elem = p;
for(int i = 0; i < 2; i++) {
cout << *elem << " " << elem << endl;
++elem;
}
delete[] p;
return 0;
}

array elements not printing when trying to print in the main function

I want to find the factors of a product by using arrays to check whether they equal it or not
the values do not print
here is the code
#include <iostream>
using namespace std;
int main() {
int arr[5] = { 1,3,5,7,2 };
int arr1[5] = { 0,6,5,4,9 };
int X;
cout << "Please enter X:"; cin >> X;
for (int i = 0, j = 0; i < 5 && j < 5; ++i, ++j) {
if (arr[i]*arr[j]==X) {
cout << arr[i] << " ";
cout << arr1[j] << " ";
}
}
}
Use this nested loops
for (int i = 0; i < 5 ;++i) {
for(int j=0 ;j<5;++j){
if (arr[i]*arr1[j]==X) {
cout << arr[i] << " ";
cout << arr1[j] << " ";
}
}
}

Program wont run to the end after function is called

I wrote a program to accept 15 integer values in an array, then pass this array to a function which will multiply each even index value by 4.
Currently the program displays the initial array, but seems like it's getting hung up before it displays the modified array.
Please help me understand why the program is getting stuck here!
int main(){
const int SIZE = 15;
int quad[SIZE] = {};
void quadruple(int[], const int);
cout << "Enter 15 integer values into an array." << endl;
for (int i = 0; i < SIZE; i++) // Accept 15 int values
{
cout << i << ": ";
cin >> quad[i];
}
cout << "Before quadruple function is called: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
quadruple(quad, SIZE);
cout << "After even index value multiplication: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
return 0;
}
void quadruple(int values[], const int SZ){
for (int i = 0; i < SZ; i + 2) // Multiply even values by 4
{
if ((i % 2) == 0)
{
values[i] = values[i] * 4;
}
else // Keep odd values the same
{
values[i] = values[i] * 1;
}
}
}
for (int i = 0; i < SZ; i + 2)
"i + 2" doesn't do anything.
You probably meant "i += 2;".
Your homework assignment is to find some documentation about your system's debugger. And find where your rubber duck is, as it's been suggested in the comments.

Print an array in C++

I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}

why v[0] and *v.begin() printing 0 even though i am not passing some 0 as input value for array

#include <iostream>
#include <vector>
using namespace std;
int main()
{
int testcases = 0;
int length;
int item =0;
std::vector<int> v;
cin>>testcases;
for (int i=0; i<testcases; ++i)
{
cin>>length;
v.resize(length);
for (int j=0; j<length; ++j)
{
cin >> item;
cout << "item entered:" << item << endl;
v.push_back(item);
}
cout << v[0] << " ";
cout << *v.begin() << " ";
int loop=0;
cin>>loop;
int range1=0, range2=0;
int result = 0;
for (int k=0; k<loop; ++k)
{
result = 0;
cin>>range1;
cin>>range2;
cout << v[range1]<< " "<< v[range2] <<endl;
while (range1<=range2)
{
result = result^v[range1];
++range1;
}
cout << result << endl;
}
}
return 0;
}
why v[0] and *v.begin() printing 0 even though i am not passing some 0 as input value for array
It's because the push_back calls add to the end of the vector, which is after the items created by the resize call.
If you want to set specific entries in the vector, you need to use array indexing syntax in the input loop.