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

The square of an integer n can be calculated by adding the first n odd integers.

ID: 3766829 • Letter: T

Question

The square of an integer n can be calculated by adding the first n odd integers. For example, 1 + 3 + 5 = 9 = 32 1 + 3 + 5 + 7 = 16 = 42 1 + 3 + 5 + 7 + 9 = 25 = 52 Write a program that uses this method to calculate and print the square of each integer entered by the user. For each integer, the program should read the integer, then use this method to calculate and print the square of the integer. The program should read until the user enters 0. If the user enters a negative integer, the square can be calculated with this method, by using the complement of the integer. (Remember, the complement of a number is the same number but with the opposite sign.) So the complement of 5 is -5.

Explanation / Answer

For the method given above, following C++ code implements it.

#include <iostream>
using namespace std;

int main() {
   int i, n, odd_sum, square;
   cout<<"Enter an number: ";
   cin>>n;
   if (n<0)
        n = n * (-1);
   square = 0;
   odd_sum = 1;
   if (n == 0)
        square = 0;
   else{
        for(i=1; i<=n; i++){
            square +=odd_sum;
            odd_sum += 2;
        }
   }
   cout<<"The square of "<<n<<" is "<<square;
   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