Challenge you guys : Re-write the reverse function for reversing faster !!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <cstring>
using namespace std;

int count = 0;

int fill_ary(double * ary, int size);
void show_ary(double * ary, int size);
double * reverse_ary(double * ary, int size);

int fill_ary(double * ary, int size){
    for(int i = 0 ; i < size - 1 ; i ++){
        cout << "Input double value " << (i+1) << endl;
        cin >> ary[i];
        if(!ary[i]){
            break;
        }
        count ++;
    }
    return count;    
}
void show_ary(double * ary, int size){
    for(int i = 0 ; i < size - 1 ; i ++){
        cout << ary[i] << ",";
    }
    cout << "" << endl;
}
double * reverse_ary(double * ary, int size){

    double *tmpAry = new double[size];
    int j = size - 2 ;
    
    for(int i = 0 ; i < size - 1 ; i ++){
            tmpAry[i] = ary[j];
            j--;
    }  
    
    ary = tmpAry;
    delete tmpAry;
    
    return ary;
}
int main(){
    
    int size = 10;
    double *ary = new double[size];
    
    cout << "Number of value " << fill_ary(ary, size) << " has inputed." << endl;
    show_ary(ary, size);
    ary = reverse_ary(ary, size);
    show_ary(ary, size);
    cout << endl;

    return 0;    
}



Input double value 1
1
Input double value 2
2
Input double value 3
3
Input double value 4
4
Input double value 5
5
Input double value 6
q
Number of value 5 has inputed.
1,2,3,4,5,0,0,0,0,
0,0,0,0,5,4,3,2,1,
Last edited on
Very bad program!

For example I see that number 6 was entered but it is not present in the output of the array. And though the array is declared with 10 elements only 9 elements are displayed.

And the program in whole is invalid because it will not work with arrays declared in stack or as static. To allocate every time new memory that to reverse an array is a bad idea.

All what you are doing can be written in three maximum in four statements.

1
2
3
4
5
6
std::copy( std::istream_iterator<double>( std::cin ), std::istream_iterator<double>(), a );

std::reverse( std::begin( a ), std::end( a ) );

for ( double x : a ) std::cout << x << ", ";
std::cout << std::endl;


EDIT: I am sorry. I was mistaken about number 6. Nevertheless the program is even worst because you are using global variable count. :)
Last edited on
Thanks for your help !!
Topic archived. No new replies allowed.