Functions

Hi everyone, I'm fairly new to c++ and I'm working on an assignment that I have managed to work through most of it, however I do have some issues.

1. my function to reverse an array only seems to work properly half the time, the other half of the time the last element does not seem to be swapping accordingly.

2.Im also not getting a correct output for my difference between first and last array element function and my function that is supposed to print array values before the third index. These functions seemed straight forward to me, but I seem to be getting 0's for both of these functions and I'm stumped. Any input is appreciated.

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
  #include <iostream>
#include <cstdlib>
#include <ctime>


using namespace std;

void showArray ( int a[], int size );//Function prototype
void showReverse ( int a[], int size ); //Shows the array in reverse using the format "int
int  lowest ( int a[ ], int size );//Finds and returns the lowest value in the array
int  highest ( int a[ ], int size );
int  sumArray ( int a[ ], int size );
float averageVal ( int a[ ], int size );
int count5 ( int a[ ], int size );
int firstMinusLast ( int a[ ], int size );
void showBeforeIndex( int a [ ], int size, int index);
void done ( );


int main(){

   srand((time(0)));// to get truly random numbers
   const int size = 25; //size of array never changes
   int randNumber[size];// array to store random number
   int index = 3;

   cout <<"Making an array of 25 random integers from 3 to 7!" << endl;

   //for loop that will create random numbers and store in array
   for(int i=0; i < size; i++){
    randNumber[i]= 3 + rand() % 5; // rand number 3 to 7, %5 gives numbers up to 4 and by adding 3 it gives up to 7
   }

    cout << "Original array a[] = {";
        showArray(randNumber, size);// passes array and size to function
    cout << "}\n\n";

    cout << "Reversed array a[] = {";
        showReverse(randNumber, size);// passes array and size to function
    cout << "}\n\n";

    cout << "Lowest value is: ";// passes array and size to function
        int low =lowest(randNumber,size);
    cout << low <<"\n\n";

    cout <<"Highest value is: ";
        int high = highest(randNumber,size );
    cout << high << "\n\n";

    cout << "The sum of all array elements is: ";
        int sum = sumArray (randNumber,size);
    cout << sum <<"\n\n";

    cout << "The average of all array values is: ";
        int avg = averageVal(randNumber,size);
    cout << avg <<"\n\n";

    cout << "The number 5 appears: ";
        int count = count5(randNumber,size);
    cout << count <<" times.\n\n";

    cout << "The difference between the first and last array element is:  ";
        int diff = firstMinusLast(randNumber,size);
    cout << diff <<"\n\n";

    cout << "The array values before index 3 are ";


        showBeforeIndex(randNumber,size,index);


        done ( );


    return 0;
}

void showArray ( int a[], int size ){ // shows the array in the format "int a [ ] = { 3, 7,
        for(int i = 0; i < size;i++){
    cout << a[i] <<" ";
    }
}

void showReverse ( int a[], int size ){  // shows the array in reverse using the format "int
    for (int i=0, j= size-1; i <= j;j--){
        swap(a[i], a[j]);
    cout << a[i] << " ";
    }
}

int lowest ( int a[], int size ){// finds and returns the lowest value in the array
    int lowest = a[0];
    for(int i= 0; i<size; i++){
            if (a[i] < lowest){
                lowest = a[i];
            }
    }
    return lowest;
}

int  highest ( int a[], int size ){
    int highest = a[0];
    for(int i= 0; i<size; i++){
            if (a[i] > highest){
                highest = a[i];
            }
    }
    return highest;
}

int  sumArray ( int a[], int size ){
    int sum = 0;
    for(int i= 0; i < size; i++){
        sum = sum + a[i];
    }
    return sum;
}

float averageVal ( int a[ ], int size ){
    float average;
    float sum = 0;
    for(int i= 0; i < size; i++){
        sum = sum + a[i];
    }
    average = sum / size;
    return average;
}

int count5 ( int a[], int size ){
    int count = 0;
    for(int i= 0; i<size; i++){
        while(a[i]!=0)
        {
        if(a[i]%10==5){
            count++;
        }
            a[i]=a[i]/10;
        }
    }
    return count;
}

int firstMinusLast ( int a[ ], int size ){
    int difference = a[0]- a[size-1];
    return difference;
    }


void showBeforeIndex( int a [ ], int size, int index){
    for(int i=0; i < index; i++)
        cout << a[i];
}

void done ()
    {
        cout << "\n\nI am now a pro at functions!\n";
    }
> for (int i=0, j= size-1; i <= j;j--)
You seem to be missing i++

Otherwise you meet at the start, not meet in the middle.
where is i++ in reverse...
1
2
3
4
5
6
void showReverse ( int a[], int size ){  // shows the array in reverse using the format "int
    for (int i=0, j= size-1; i <= j; i++, j--){
        swap(a[i], a[j]);
    cout << a[i] << " ";
    }
}


When i update it with the i++, i only get half the array . Up to the point where i and j meet , how can i get past that?
Your function:
1
2
3
4
5
6
void showReverse ( int a[], int size ){
    for (int i=0, j= size-1; i <= j;j--){
        swap(a[i], a[j]);
    cout << a[i] << " ";
    }
}


Since you're swapping elements that means you must not traverse entry array, but instead just half of it, and then print the result.

First include mathematics header
#include <cmath>

Then update your formula as follows:

1
2
3
4
5
6
7
8
9
10
void showReverse(int a[], int size)
{
        // reverse array elements
	for (int i = 0, j = size - 1; i < std::trunc(size / 2.f); ++i, --j)
		swap(a[i], a[j]);

        // print array status
	for (int i = 0; i < size; ++i)
		cout << a[i] << " ";
}


Last edited on
When i update it with the i++, i only get half the array . Up to the point where i and j meet , how can i get past that?

12345
1 and 5 (I and J) ..swap that:
52341
increment /decrement, 2 and 4, swap those:
54321
increment/ decrement, i and j are equal, both at 3.
swapping it has no effect (swap with self is harmless) or you can stop the loop there (all done)
if you continued:
it swaps 3 with itself
then 2 and 4 swap a second time (back to original position
1 and 5 swap a second time... you don't want this, you wanted to stop!

if the goal is simply to print it in reverse, you can also just iterate over the array backwards...
that is likely 'not the spirit of the assignment' for this homework but it is worth a mention.
Last edited on
A simpler showReverse is to simply print from the last element down to the first element.
No worries about swapping.

1
2
3
4
void showReverse (int a[], int size)
{   for (int i=size-1; i==0; i--)
        cout << a[i] << " ";
}


wow, I don't know how I didn't think to just start from the back of the array and work my way back ..duh, thanks everyone.

Now what is the reason that I am getting 0s for these? They appear to be right to me, so at this point I feel like I'm just trying the same thing over and over again

1
2
3
4
5
6
7
8
9
10
11

    int firstMinusLast ( int a[ ], int size ){
    int difference = (a[0]- a[size-1]);
    return difference;
    }


void showBeforeIndex( int a [ ], int size, int index){
    for(int i=0; i < index; i++)
        cout << a[i];
}
@AbstractionAnon - are you sure about your for loop condition?
To show a reversed array, it's easier if you pass the array as a template. Consider:

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
#include <algorithm>
#include <iterator>
#include <iostream>

template<typename T, size_t N>
void showReverse1(const T (&a)[N]) {
	std::copy(std::crbegin(a), std::crend(a), std::ostream_iterator<T>(std::cout, " "));
	std::cout << '\n';
}

template<typename T, size_t N>
void showReverse2(const T(&a)[N]) {
	for (auto itr {std::crbegin(a)}; itr != std::crend(a); ++itr)
		std::cout << *itr << ' ';

	std::cout << '\n';
}

template<typename T, size_t N>
void showReverse3(const T(&a)[N]) {
	for (size_t e = N; e > 0; --e)
		std::cout << a[e - 1] << ' ';

	std::cout << '\n';
}

int main()
{
	int a[] {1, 2, 3, 4, 5, 6};

	showReverse1(a);
	showReverse2(a);
	showReverse3(a);
}

For the others, consider:

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
#include <algorithm>
#include <iterator>
#include <iostream>
#include <numeric>

template<typename T, size_t N>
T lowest(const T(&a)[N]) {
	return *(std::min_element(std::cbegin(a), std::cend(a)));
}

template<typename T, size_t N>
T highest(const T(&a)[N]) {
	return *(std::max_element(std::cbegin(a), std::cend(a)));
}

template<typename T, size_t N>
T sum(const T(&a)[N]) {
	return std::accumulate(std::cbegin(a), std::cend(a), 0);
}

template<typename T, size_t N>
auto average(const T(&a)[N]) {
	return sum(a) / (double)N;
}

template<typename T, size_t N>
auto firstMinusLast(const T(&a)[N]) {
	return *std::cbegin(a) - *std::crbegin(a);
}

template<typename T, size_t N>
void showBeforeIndex(const T(&a)[N], size_t indx) {
	std::copy_n(std::cbegin(a), indx, std::ostream_iterator<T>(std::cout, " "));
	std::cout << '\n';
}

template<typename T, size_t N>
auto count5(const T(&a)[N]) {
	return std::count_if(std::cbegin(a), std::cend(a), [](auto i) {return i % 5 == 0; });
}

int main()
{
	const int a[] {1, 2, 3, 4, 5, 6, 5};

	std::cout << "Highest is: " << highest(a) << '\n';
	std::cout << "Lowest is: " << lowest(a) << '\n';
	std::cout << "Sum is: " << sum(a) << '\n';
	std::cout << "First minus last: " << firstMinusLast(a) << '\n';
	std::cout << "Count 5's: " << count5(a) << '\n';
	std::cout << "Before index 3: ";
	showBeforeIndex(a, 3);

}



Highest is: 6
Lowest is: 1
Sum is: 26
First minus last: -4
Count 5's: 2
Before index 3: 1 2 3

Registered users can post here. Sign in or register to post.