Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that asks the user for a positive integer N, and then uses that

ID: 3566052 • Letter: W

Question

Write a program that asks the user for a positive integer N, and then uses that integer to compute and display the following four sums and products:

1. The sum of integers 1 ... N inclusive.

2. The sum of the powers of 2: 20 + 21 + 22 + ... + 2(N-1)

3. The sum of the inverse of the powers of 2: 1/20 + 1/21 + 1/22 + ... + 1/2(N-1)

4. The product of the integers 1 ... N inclusive

Here is an example execution of the program with input 6 (the user inputs 6 in response to the request "Input N: ", but the program displays everything else). Note that your output should be formatted exactly as shown in the example below:

Input N: 6
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 4 + 8 + 16 + 32 = 63
1 + 0.5 + 0.25 + 0.125 + 0.0625 + 0.03125 = 1.96875
1 * 2 * 3 * 4 * 5 * 6 = 720

Make sure you test your program! Your program should work for any positive integer (i.e., greater than 0)!

Hint: Do this question in stages. Get the first sum working perfectly (tested and everything!) before going on to the second. You will cause yourself a lot of grief if you try to do this one all at once. And you can use the ideas you develop from earlier parts to solve later parts.

Explanation / Answer

#include <iostream>
#include <math>

using namespace std;

int main()
{
   int num = 0, i = 0, sum = 0, product = 1, twoPower = 0;
   double invTwo = 0.0, parts = 0.0;

   cout << "Enter number" << endl;
   cin >> num;

    // The sum of integers 1 ... N inclusive.
    i = 0;
   while (i <= num)
   {
       sum = sum + i;
       i++;
   }
   cout << "Sum is: " << sum << endl;

   // The sum of the powers of 2
   i = 0;
   while (i < num)
   {
       twoPower = twoPower + pow(2, i);
       i++;
   }
   cout << "Sum is: " << twoPower << endl;

   // The sum of the inverse of the powers of 2
   i = 0;
   while (i <= num)
   {
       parts = (1.0 / pow(2, i));
       invTwo = invTwo + parts;
       i++;
   }
   cout << "Sum is: " << invTwo << endl;

   // The product of the integers 1 ... N inclusive
   i = 1;
   while (i <= num)
   {
       product = product * i;
       i++;
   }
   cout << "Product is: " << product << endl;

   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote