Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
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

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];
 
Share this answer
 
Comments
CPallini 22-Feb-18 6:50am    
5.
Maciej Los 22-Feb-18 16:12pm    
5ed!
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.
 
Share this answer
 
v2
Comments
Maciej Los 22-Feb-18 16:12pm    
Nice!
#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;
}
 
Share this answer
 
Comments
Maciej Los 22-Feb-18 16:12pm    
And?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900