Sum or Product

 

Write a program that asks the user for a number N and a choice C. And then give them the possibility to choose between computing the sum and computing the product of all integers in the range 1 to N (both inclusive).

If C is equal to -

 1, then print the sum
 2, then print the product
 Any other number, then print '-1' (without the quotes)
Sample Input 1 :
10
1
Sample Output 1 :
55
import java.util.Scanner;
public class Main {
	
	public static void main(String[] args) {
		
        Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
               int c = sc.nextInt();
        
        if(c==1)
        {
            int s=0;
			for(int i=1;i<=n;i++)
            {
                s=s+i;
            }
            System.out.println(s);

        }
        else if(c==2)
        {
            
        int m=1;
            for(int j=1;j<=n;j++)
            {
                m=m*j;
            }
            System.out.println(m);

        }
        else
        {
            System.out.println("-1");

        }

	}
}

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern