Scanner class
import java.util.Scanner;
public class Pl {
public static void main(String[] args) {
int n,sum=0,num;
System.out.print("Enter length : ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
int []a=new int[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter Num :");
num = in.nextInt();
a[i]=num;
sum = sum+a[i];
}
for(int i =0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.print("Sum is "+sum);
}
}
output:
Enter length : 3
Enter num : 1
Enter num : 2
Enter num :3
1 2 3
sum is : 6
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Pl {
public static void main(String[] args) throws IOException {
int sum=0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter length");
int n = Integer.parseInt(br.readLine());
int []a=new int[n];
for(int i =0 ;i <n;i++)
{
System.out.print("Enter num:");
int k = Integer.parseInt(br.readLine());
a[i]=k;
sum= sum + a[i];
}
for(int i =0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.print("Sum i :"+sum);
}
}
sum is : 6
BufferedReader
package pl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Pl {
public static void main(String[] args) throws IOException {
int sum=0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter length");
int n = Integer.parseInt(br.readLine());
int []a=new int[n];
for(int i =0 ;i <n;i++)
{
System.out.print("Enter num:");
int k = Integer.parseInt(br.readLine());
a[i]=k;
sum= sum + a[i];
}
for(int i =0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.print("Sum i :"+sum);
}
}
No comments:
Post a Comment