Sum or Product
Send Feedback
Write a program that asks the user for a number N and a choice C. And then give him the possibility to choose between computing the sum and computing the product of 1 ,..., N.
If user enters C is equal to -
Input format :
Output Format :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 2 :
Sample Input 3 :
Sample Output 3 :
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int i,sum=0,pro=1;
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int n1 = s.nextInt();
if(n1==1)
{
for(i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println(sum);
}
else if(n1==2)
{
for(i=1;i<=n;i++)
{
pro=pro*i;
}
System.out.println(pro);
}
else
System.out.println(-1);
}
}
No comments:
Post a Comment