C++ void reverse function - c++

We are converting base 10 to a number in a different base(B). I am having trouble with the void reverse function it will not reverse the order of the numbers.
string convertToBaseB(int num, int b){
int digit;
stringstream answer;
string x="";
while(num>0){
digit=num%b;
num/=b;
answer<<digit;
}
return answer.str();}
void reverse(int x[],int size){//reversing the
for(int k=0; k<size/2; k++){
int temp=x[k];
x[k]=x[size-k-1];
x[size-k-1]=temp;}
}

Your reverse function works fine. However it doesn't looks like C++ to me... In C++ I would have a vector and do:
std::vector<int> arr;
//... fill arr
std::swap_ranges(&arr[0], &arr[arr.size()/2], arr.rbegin());
If you want to stick with your for loop, at least use std::swap like this
void reverse(int x[],int size) {
for(int k=0; k<size/2; k++)
std::swap(x[k], x[size-k-1]);
}

Works for me:
#include <iostream>
using namespace std;
void reverse(int x[],int size)
{
for(int k=0; k<size/2; k++)
{
int temp=x[k];
x[k]=x[size-k-1];
x[size-k-1]=temp;
}
}
int main()
{
const int sz = 9;
int* digits;
digits = new int[sz];
for (int i=0; i < sz; ++i)
{
digits[i] = i;
}
reverse(digits, sz);
for (int i=0; i < sz; ++i)
{
cout<<digits[i]<<" ";
}
cout<<endl;
}

Related

sum of an array elements in cpp return wrong value

I tried to write a simple code to calculate an array elements' sum. every thing looks normal but the function return the sum value wrongly (it always multiply it by two). Although if I want just print the value, it works fine.
this is the code:
#include <iostream>
using namespace std;
void getElements(int[],int);
int sumOfElements(int[],int);
int number;
int sum=0;
int main()
{
int a[10];
getElements(a,5);
sumOfElements(a,5);
cout<<"The sum is "<<sumOfElements(a,5)<<endl;
return 0;
}
//Getting array's elements
void getElements(int numbers[],int size_)
{
for (int i=0; i<size_; i++)
{
cout<<"numbers["<<i<<"]: ";
cin>>number;
numbers[i]=number;
}
cout<<'\n';
}
//Calculation the sum of array's elements
int sumOfElements(int numbers[],int size_)
{
for(int i=0;i<size_;i++)
{
sum+=numbers[i];
}
cout<<sum<<endl;
return sum;
}
any idea? thank you in advance!
You defined int sum globally and were calling sumOfElementstwice, so sum contained twice what you expected.
Here is a modified version of your code that does what you want:
#include <iostream>
using namespace std;
void getElements(int[], int);
int sumOfElements(int[], int);
int main() {
int numbers[5];
getElements(numbers, 5);
cout << sumOfElements(numbers, 5);
return 0;
}
void getElements(int numbers[], int size) {
for (int i = 0; i < size; i++) {
cin >> numbers[i];
}
}
int sumOfElements(int numbers[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
return sum;
}
Here is a modified and simpler version of your program:
#include <array>
#include <iostream>
#include <numeric>
using namespace std;
int main(){
const int num_elements_to_sum = 5;
array<int, num_elements_to_sum> elements;
for(int i=0; i<num_elements_to_sum; ++i){
cin>>elements[i];
}
int sum = accumulate(elements.begin(), elements.end(), 0);
cout<<"Sum: "<<sum<<endl;
return 0;
}
C++ has a dedicated fixed size array container, use this instead of C-style arrays. This then allows to use standard library algorithms instead of your own implementation (e.g. accumulate).

How to print an array in descending order?

Basically this is my code and it works fine. I just don't know how to print it in descending order. This code basically shows the odd numbers:1,3,5,7. I want it to be printed 7,5,3,1. I know I need use the sort function but I dont know how.
#include <iostream>
using namespace std;
void fillArray(int arr[], int &n);
void printArray(int arr[], int n);
void findSum(int arr[], int &n);
int main()
{
int n;
cin>>n;
int arr[n];
fillArray(arr,n);
printArray(arr,n);
findSum(arr,n);
return 0;
}
void fillArray(int arr[], int &n)
{
int j=1;
for(int i=0;i<n;i++)
{
if(j%2==1)
arr[i]=j;
else
i--;
j++;
}
}
void printArray(int arr[], int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<", ";
}
}
void findSum(int arr[], int &n)
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+arr[i];
}
}
for(int i = n-1; i >= 0; i--)
{
cout << arr[i] << ", ";
}
example:
void printArray(int *tab, int size)
{
for (int i = size - 1; i >= 0; i--)
std::cout << tab[i] << std::endl;
}
int main() {
int tab[3] = { 1,2,3 };
printArray(tab, 3);
}
You should begin from last element array, and decrement iterator (i) to i == 0
You can simply use a sort function. There is one included with the algorithm header.
#include <algorithm> // this goes at the top
void printArray(int arr[], int n)
{
sort(arr, arr+n, [](int x, int y){return y<x;});
for(int i=0;i<n;i++)
cout << arr[i] << endl;
}
the [](int x, int y){return y<x;} part is just to make it descending. Normally it is y>x, at which point you can just omit the third parameter
Here is a repl:
https://repl.it/JQor/0

Merging two arrays in ascending order

I know the logic how to merge two arrays but the problem is how to code.
This was my code n it is giving correct ans but my sir told me that do it again,please tell me what I have to add in this code,
#include<iostream>
using namespace std;
int mergeArrays(int array1[],int size1,int array2[],int size2);
int main()
{
const int size1=8;
const int size=12;
int arrayA[size1]={10,25,37,49,50,51,55,60};
int arrayB[size]={2,5,26,27,29,32,40,45,70,80,90,95};
mergeArrays(arrayA,size1,arrayB,size);
}
int mergeArrays(int array1[],int size1,int array2[],int size2)
{
int size3=size1+size2;
int *array3=new int[size3];
int k=0;
for(int i=0;i<size1;i++)
{
array3[k]=array1[i];
cout<<" "<<array3[k];
}
int j=0;
for(int i=size1;i<size2;i++)
{
array3[k]=array2[j];
}
for(int i=size1;i<size2;i++)
{
for(int j=0;j<size2;j++)
{
array3[i]=array2[j];
cout<<" "<<array3[i];
}
cout<<endl;
delete[]array3;
return array3[k++];
}
}
I had searched this in many places but could not corrected my code
I had written this code but it is not giving correct ans.
#include<iostream>
using namespace std;
int merge(int *a,int *b,int aSize,int bSize);
int main()
{
const int aSize={8};
const int bSize={12};
int arrayA[aSize]={10,25,37,49,50,51,55,60};
int arrayB[bSize]={2,5,26,27,29,32,40,45,70,80,90,95};
merge(arrayA,arrayB,aSize,bSize);
return 0;
}
int merge(int *a,int *b,int aSize ,int bSize)
{
int cSize=aSize+bSize;
int *c=new int[cSize];
int j=0,k=0;
int i=0;
while(i<=aSize&&j<=bSize )
{
if(a[aSize ]<=b[bSize])
{
c[k]=a[aSize];
k++;
i++;
}
else
{
c[k]=b[bSize];
k++;
j++;
}
}
for(int i=0;i<k;i++)
{
cout<<c[i]<<endl;
}
delete[]c;
return c[k++];
}
your sir request you do Merging two arrays in ascending order. so i think you should return a new array, fill with array1 and array2's element, and the elements should be ascending order. here is a implement.(suppose your input arraies is already in ascending order.)
#include <iostream>
using namespace std;
int mergeArrays(int array1[],int size1,int array2[],int size2, int outArray[]);
int main()
{
const int size1=8;
const int size=12;
int arrayA[size1]={10,25,37,49,50,51,55,60};
int arrayB[size]={2,5,26,27,29,32,40,45,70,80,90,95};
int outArray[size1+size];
int len = mergeArrays(arrayA,size1,arrayB,size, outArray);
cout <<" "<< len;
for (int i = 0; i< size1+size; ++i){
cout <<" " << outArray[i];
}
}
int mergeArrays(int array1[], int size1, int array2[], int size2, int outArray[])
{
int i=0, j=0, k=0;
int retSize = size1+size2;
while (k<retSize){
if (i==size1){// only left array2, copy it
for (; j<size2; ++j){
outArray[k++] = array2[j];
}
}else if (j == size2) { // only left array1, copy it
for (; i<size1; ++i){
outArray[k++] = array1[i];
}
}
else if (array1[i] > array2[j]){ // copy the min value to outArray
outArray[k++] = array2[j++];
}else{
outArray[k++] = array1[i++];
}
}
return k;
}
now, let's look at your first code:
int mergeArrays(int array1[],int size1,int array2[],int size2)
{
int size3=size1+size2;
int *array3=new int[size3];
int k=0;
for(int i=0;i<size1;i++)
{
array3[k]=array1[i]; // k is not changed, so you just assign array1's each value to array3[0]
cout<<" "<<array3[k];
}
int j=0;
// what's the purpose of this loop?
// and in loop, you don't use i, you just repeat set array3[0] = array2[0]!!
for(int i=size1;i<size2;i++)
{
array3[k]=array2[j];
}
for(int i=size1;i<size2;i++) // if array2's length bigger than array1's, will enter this loop.
{
for(int j=0;j<size2;j++)
{
array3[i]=array2[j]; // this just repeat assign array2's each value to array3[i]!!
cout<<" "<<array3[i];
}
cout<<endl;
delete[]array3;
return array3[k++]; // you delete array3, but at here you access it!! this will crash!
// also, in this for i loop, you have return, so it will only execute once.
}
// reach function end and no return if not enter for loop.
}
I haven't looked at your second code. I think you still need to do more study.

Why this Selection sort code in Cpp, not giving required Output

#include<iostream>
using namespace std;
int min_arr(int arr[],int size);
void swap(int *,int *);
int main()
{
int arr[10]={31,2,55,3,77,12,89,98,43,34},loc;
int* arr1;
arr1 = &arr[0];
for(int i=0;i<10;i++)
{
for( int j=i;j<9;j++)
{
loc = min_arr(arr1,(10-i));
swap(&arr[loc],&arr[i]);
arr1++;
}
}
for(int i =0; i<10;i++)
cout<<arr[i]<<endl;
return 0;
}
int min_arr(int arr[],int size)
{
int k=0;
int temp=arr[0];
for(int i=1;i<size;i++)
{
if(arr[i]<temp)
{
temp=arr[i];
k=i;
}
}
return k;
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Why this Selection sort code in Cpp, not giving required Output? Kindly find the flaw! I have taken two functions to find min of the sub arrays as we procede. And as i find the min, i return its index and swap the first position of the sub array and minimum valued element!
After rearranging the code and adding some debug lines, it's pretty easy to find out what's wrong:
Firstly, the second loop (j loop) is completely pointless
Secondly loc variable is not 0-based but i-based (as you searched over arr1, which is incremented by the loop), so arr[loc] should be arr[loc+i]
Corrected, smartly indented (that's important to make tour code easily readable) code:
#include<iostream>
#define ARRAY_SIZE 10
using namespace std;
int min_arr(int arr[],int size);
void swap(int *,int *);
int main()
{
int arr[ARRAY_SIZE]={31,2,55,3,77,12,89,98,43,34},loc;
int* arr1;
arr1 = &arr[0];
for( int i = 0; i < ARRAY_SIZE; i++ )
{
//for( int j = i; j<ARRAY_SIZE-1; j++ )
{
loc = min_arr(arr1,(ARRAY_SIZE-i));
// for debug:
//std::cout << "min found at " << loc << std::endl;
swap(&arr[loc+i],&arr[i]);
// for debug:
//for( int i =0; i<ARRAY_SIZE; i++ )
// cout << arr[i] << " ";
//cout << std::endl;
arr1++;
}
}
for( int i =0; i<ARRAY_SIZE; i++ )
cout<<arr[i]<<endl;
return 0;
}
int min_arr( int arr[], int size )
{
int k=0;
int temp=arr[0];
for( int i=1; i<size; i++ )
{
if( arr[i] < temp )
{
temp=arr[i];
k=i;
}
}
return k;
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
It will output:
2
3
12
31
34
43
55
77
89
98
In your version you just go with pointers beyond the area mapped for the array.
First of all, call of the function min_arr. It requires array, not pointer:
loc=min_arr(arr,(10-i));
Second, the function itself. You always start from the beginning of the array, that's why already sorted elements go resorted.
int min_arr(int arr[],int size)
{
int k=10-size;
int temp=arr[k];
for(int i=k+1;i<10;i++)
{
if(arr[i]<temp)
{
temp=arr[i];
k=i;
}
}
return k;
}
for(int i=0;i<10;i++)
{
for( int j=i;j<9;j++) //shouldn't this be j < 10 ?
......

c++ function that fills array

What I'm trying to do:
User inputs two numbers.
Array is declared using those numbers as dimensions.
Function outside main() is filling the array.
Array is accessed in main() for further thingies.
What I have problem with:
Function + array combination doesn't seem to work as I think.
What I did:
void tablica1(int h, int w)
{
int m,n;
for(m=0; m<h; m++)
for(n=0; n<w; n++)
{
arr[h][w]=1;
}
}
What happens:
array arr is inaccessible in tablica1() because it has not been declared in that function.
Of course, when I declare the array in tablica1() it becomes inaccessible in main().
Possible solutions:
Passing arr to tablica1() as a reference - no idea how to do that
Declaring arr in tablica1() and somehow passing it to main() - no idea how to do that
Other possible solutions?
You can declare the array outside of both, at compilation unit level:
int arr[10][10];
void func() {
for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
arr[i][j] = i + j;
}
}
}
int main(int argc, const char *argv[]) {
func();
std::cout << arr[3][4] << "\n"; // Output will be 7
return 0;
}
If you want handle a dynamically-sized matrix the most common pattern is to use an std::vector of std::vectors (it's a little more general and therefore a little less efficient than a 2d matrix because each row can have a different length, but in most cases the cost difference is not a big issue)
#include <vector>
std::vector< std::vector< int > > arr;
void func() {
int height = arr.size();
int width = arr[0].size();
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
arr[i][j] = i + j;
}
}
}
int main() {
int height = 13;
int width = 7;
arr = std::vector< std::vector<int> >(height, std::vector<int>(width));
func();
...
}
the two solutions you mentioned
1、Passing arr to tablica1() as a reference
void tablica1(int h, int w,int **arr)
{
int m,n;
for(m=0; m<h; m++)
for(n=0; n<w; n++)
{
arr[h][w]=1;
}
}
void main()
{
const int h=100,w=100;
int arr[h][w];
tablica1(h,w,arr);
}
2、Declaring arr in tablica1() and somehow passing it to main()
int **tablica1(int h, int w)
{
int m,n;
int **arr=new int*[h];
for(int i=0;i<h;i++)
{
arr[i]=new int[w];
}
//it is best to initialize arr by setting each element 0
for(m=0; m<h; m++)
for(n=0; n<w; n++)
{
arr[h][w]=1;
}
return arr;
}
void main()
{
const int h=100,w=100;
int **arr=tablica1(h,w);
//do somting
//delete arr
for(int i=0;i<h;i++)
{
delete []arr[i];
}
delete []arr;
}
If you want to declare a dynamic multidimensional array you can do that with the template give below.
#include<iostream.
#include <vector>
using namespace std;
typedef vector<int> vi;
vector<vi> arr; // arr is a dynamic two dimensional array.
vi.assign(10,vi());//10 rows of type vi .
If you want to enter values in arr you can do that by
vi[0].push_back(a);
vi[0].push_back(b); // a,b,c are some example values..
vi[1].push_back(c);
You can understand using this code
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
typedef vector <int> vi;
vector<vi> arr;// dynamic multidimensional array
int main(){
cout<<"enter array size\n";
int h,w,temp;;
cin>>h>>w;
arr.assign(h,vi());
int i, j;
for(i=0; i < h ;i++)
for(j=0; j < w; j++)
{
cin>>temp;
arr[i].push_back(temp);
}
// for printing
for(i=0; i < h ;i++){
for(j=0; j < w; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
return 0;
}