Free CoreJava Programs Source codes | Examples | Video Tutorials Download

Tuesday, January 20, 2009

Add N Numbers Program

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
* User enters any number of numbers and you are to give the addition product
*/
public class AddNNumber
{
/**
* add any number of Numbers and display the sum of them
* if error occured will pass to the caller
* @throws Exception
*/
public static void addNums() throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Howmany NOs you want to add : ");
String str=br.readLine();
final int nos=Integer.parseInt(str);

if(nos==0)
{
System.out.println("Invalid Input!!");
return;
}

int[] numbers=new int[nos];
long sum=0;
String msg="";

for(int i=0;i nos;i++)
{
System.out.println("Enter " + i + " No : ");
str=br.readLine();
numbers[i]=Integer.parseInt(str);
sum+=numbers[i];
if(i==0)
msg=str;
else
msg=msg + " + " + str;
}

System.out.println("Sum of ( " + msg + " ) = " + sum);
}

/**
* execution begin from here
* @param arg command line argument
*/
public static void main(String[] arg)
{
try
{
addNums();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

No comments:

Post a Comment

Followers