• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Java Array sum up adjacants

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Given is an array filled with integer values. For each pass, the possible elements must be summed up. I want to repeat this process until only one element remains.And I want to give intermediate results, as well as the final result on the console.
for example Input : 1,2,3,4

Output:

20
8 12
3 5 7.

I wrote the following method but it only do "3 5 7", how can I work with the "new array" to sum up the actual elements ?

   

public static void sum(int [] array, int n){

       int summ = 0;

       for(int i = 0; i < n - 1; i++) {

           summ = array[i] + array[i + 1];

           System.out.print("[" + summ + "]" + " ");
 
Rancher
Posts: 4893
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can you show how you would get that output from the given array?
 
Saloon Keeper
Posts: 9743
80
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A method that creates and returns a new array that is the sum of adjacent elements in the given array. Don't print here, print in your main() or calling method. Also, to consistently print arrays use:

You calling method could be implemented in a loop to call sum() until the length of the returned array is zero.
 
straws are for suckers. tiny ads are for attractive people.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic