Add Numbers inside an Array using For Loop


import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the input you want to enter: ");
        int size = input.nextInt();
        int[] numArr = new int[size];
        int sum=0;
        
 System.out.print("Enter "+ size +" numbers: ");
        
 for(int i=0; i<numArr.length; i++)
        {
          numArr[i]=input.nextInt();
          sum = sum + numArr[i];
        }
    
        System.out.print("The sum of the numbers is: " + sum);
    }
}
Sample Output:
Enter the size of the input you want to enter: 5
Enter 5 numbers: 34 2 5 3 6
The sum of the numbers is: 50
If you want to make a method and segregate the implementation of sum for the sake of practice in Object Oriented Programming, just simply code it this way.
//java class

public class ArraySum
{
    public int sumOfArray(int[] array)
    {
        int sum = 0;
        for(int i=0; i<array.length; i++)
        {
            sum = sum + array[i];
        }

        return sum;
    }
}

//main class


import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the input you want to enter: ");
        int size = input.nextInt();
        int[] numArr = new int[size];
        
        System.out.print("Enter "+ size +" numbers: ");
        for(int i=0; i<numArr.length; i++)
        {
          numArr[i]=input.nextInt();
         
        }

        ArraySum access = new ArraySum();
        System.out.print("The sum of the numbers is:" + access.sumOfArray(numArr));        

    }
}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|