15,881,559 members
1.00/5 (1 vote)
See more:
Given an integer array of size N, print the sum of first and last number, second first and second last number and so on.

Note: N is always even.

Boundary Condition:
1<= N <= 9999

Input Format:
The first line contains the size of the array N
The second line contains N integers separated by space.

Output Format:
The first line contains the output as specified.

Example Input/Output 1:
Input:
6
2 9 1 5 3 2

Output:
4 12 6

Example Input/Output 2:
Input:
10
97 94 66 99 17 78 70 44 67 86

Output:
183 161 110 169 95

What I have tried:

C++
```#include<stdio.h>
#include <stdlib.h>

int main()
{
int i,j,n,a[9999],b[9999];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
for(j=n-1;j>=0;j--)
{
b[i]=a[i]+a[j];
}
for(i=0;i<n;i++)
printf("%d ",b[i]);

}```
Posted
Updated 22-Feb-18 9:47am
v2

## Solution 1

You do not need two nested for loops, but rather a single loop with two variables.
C
```int i, j;
for (i = 0, j = N - 1; i <= j; ++i, --j)
b[i] = a[i] + a[j];```

CPallini 22-Feb-18 6:50am
5.
Maciej Los 22-Feb-18 16:12pm
5ed!

## Solution 3

Quote:
i am getting addtionaly 3 zeros in the output

Because you need to correct the printing part too.
C++
```for(i=0;i<n/2;i++)
printf("%d ",b[i]);```

[Update]
A little analyze show that `a` is never reused once `b` is calculated => you don't need `b`
C++
```#include<stdio.h>
#include <stdlib.h>

int main()
{
int i,j,n,a[9999],b[9999];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0,j=n-1;i<j;i++,j--)
{
b[i]=a[i]+a[j];
a[i]=a[i]+a[j];
}
for(i=0;i<n/2;i++)
printf("%d ",b[i]);
printf("%d ",a[i]);
}```

the memory footprint have just been divided by 2 and it is possible to go further.

v2
Maciej Los 22-Feb-18 16:12pm
Nice!

## Solution 2

#include<stdio.h>
#include <stdlib.h>

int main()
{
int i,n,a[9999],b[9999];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n/2;i++)
{
int j=i-n-1;
b[i]=a[i]+a[j];
}
for(i=0;i<n/2;i++)
printf("%d ",b[i]);
return 0;
}