Print out the numbers from the for loop

Tags: , ,



The Return type is void

No input parameters

Print out the numbers calculated results separated by a space using current number add the next number from 0 to (a+b).

An example would be if the numbers for the for loop are 0,1,2,3,4,5,6 then it would add 0+1, 1+2, 2+3, 3+4, 4+5, 5+6 and print out those values just like 0,1,2,3,4,5,6.

I honestly have no clue how to do this so I’m not going to lie about it so can someone help me code it and explain or just help me with it.

public class ForFogMe
{
   public int a, b;
   public String str;

    public void addUp(){  
       
     for(a = 0; a <= 6; a ++){
         System.out.print(a);        
        }
       
       String s = Integer.toString(a);
       System.out.println();
       System.out.print(s.substring(0,2) );
       
    }
   
   public static void main(String args[]){
        
       ForFogMe me = new ForFogMe();
       me.addUp();
    }
}

Answer

I believe this should do the trick:

public static void addUp(){
    final int[] array = {0,1,2,3,4,5,6};
    int[] result = new int[array.length-1];
    for(int i = 0; i < array.length-1; i++) {
        result[i]=array[i]+array[i+1];
    }
    result[3]=array[array.length-1];
    for(int i = 0; i < result.length; i++) {
        System.out.print(result[i]+" ");
    }
    

      
   }

Test case (array):

0,1,2,3,4,5,6

Outputs:

1 3 5 6 9 11 

Note: The array size does not matter.



Source: stackoverflow