Sum or Product in c++

 Sum or Product in C++

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)

Input format :

Line 1 : Integer N
Line 2 : Choice C

Output Format :

 Sum or product according to user's choice

Constraints :

1 <= N <= 12

Sample Input 1 :

10
1

Sample Output 1 :

55

Sample Input 2 :

10
2

Sample Output 2 :

3628800

Sample Input 3 :

10
4

Sample Output 3 :

-1
C++ Code:
#include<iostream>
using namespace std;

int main() {
    int n,c,prod=1;
	cin>>n>>c;
    if(c==1)
    {
      int sum = (n*(n+1))/2;
      cout << sum;
    }
  else if(c==2)
  {
    for(int i=1;i<=n;i++)
    {
       prod=prod*i;
    }
    cout<<prod;
  }
  else
    cout<<-1;
}





SHARE

Milan Tomic

Hi. I’m Designer of Blog Magic. I’m CEO/Founder of ThemeXpose. I’m Creative Art Director, Web Designer, UI/UX Designer, Interaction Designer, Industrial Designer, Web Developer, Business Enthusiast, StartUp Enthusiast, Speaker, Writer and Photographer. Inspired to make things looks better.

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment