merging arrays

Hey guys. i need some help with my code so i am required to
1- Write a program that performs the following:
a- Declares and initializes an array a of 10 integers.
b- Finds the sum of the array elements
c- Finds the largest and smallest array element
d- Declares an array b of 10 integers. Copy the content of a into b, in reverse order.
e- Merges a and b into an array c of size 20 by alternating the elements

now i am having trouble in part e.
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
#include <iostream>
using namespace std;

int main() {

	int a[10]={12, 54 , 22, 55 , 77 ,445, 62 , 1 , 2 ,3 };
	int b[10];
	int c[20];
	
	int max = a[0];
	int min = a[0];

	int sum=0;

	for (int i=0; i < 10 ; i++){

		sum += a[i];

		if( max <= a[i] )
			max = a[i];
		
		if( min >= a[i] )
			min = a[i];
	}

	
	cout << "smallest array element :" << min << endl;
	
	cout << "largest array element :" << max << endl;

	for (int i = 9; i <=0 ; i++ ){

		b[i] = a[i];
	
	}

	system ("pause");
	return 0;
}
	
Last edited on
You can alternate the elements using a bool and doing
x= !x, or you can use a modulus operator... whatever floats your boat. I bet there are other ways to do it as well.

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

int main()
{
    int a[10]={12, 54 , 22, 55 , 77 ,445, 62 , 1 , 2 ,3 };
    int b[10];
    std::reverse_copy(a, a + 10, b);
    int c[20];

    for (int i = 0; i < 20; ++i)
    {
        if (i % 2)
        {
            c[i] = a[i / 2];
        }
        else
        {
            c[i] = b[i / 2];
        }
    }

    for (int x : c)
    {
        std::cout << x << std::endl;
    }
    return 0;
}
for d: you do not copy in reverse order. if you want to reverse the order one index must go from begin -> end and the other end -> begin

you can merge the array with a second index (j):
like so:
1
2
3
4
c[j] = a[i];
j++;
c[j] = b[i];
j++;
with reverse ....
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
#include <iostream>
using namespace std;

int main() 
{

	int a[10]={12, 54 , 22, 55 , 77 ,445, 62 , 1 , 2 ,3 };
	int b[10];
	int c[20];
	
	int max = a[0];
	int min = a[0];

	int sum=0;

	for (int i=0; i < 10 ; i++){

		sum += a[i];

		if( max <= a[i] )
			max = a[i];
		
		if( min >= a[i] )
			min = a[i];
	}

	
	cout << "smallest array element :" << min << endl;
	
	cout << "largest array element :" << max << endl;
	
	int x=9;
	for (int i=0; i <=9 ; i++ )
	{
		b[i] = a[x];
		x--;
		cout<<b[i]<<endl;
	
	}

	system ("pause");
	return 0;
}
Topic archived. No new replies allowed.