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

Create a function that takes any integer and cuts it in half, storing and return

ID: 3816874 • Letter: C

Question

Create a function that takes any integer and cuts it in half, storing and returning the result using a static int. Call this function from within a loop and stop 'halving' when it can no longer be 'halved'. Print each iteration; displaying the total 'halving* steps that occur. Specifications: the program will print your info and a message that describes its mission. (Must use the function you created in Lab 04). Program will ask the user for an integer, N, which is not equal to zero (Exit if it's 0). the program then calls/invokes a function which halves N. This function call occurs in a loop, halving the value of N that was passed until it can no longer be halved (i.e. equals Program will repeat until a user inputs 0 to exit. Your function should take an integer data type and return one. This means that halving is always an integer, for example '25/2' should return 12 and not 12.5. static int will exist in your function body: sec the example in the pre-lab. To receive full marks with a working solution: Ensure you did not repeat bad-practice mistakes based on feedback from previous lab. Use the program header function you created in Lab04. Must use a function to halve N. Program must use the static modifier within the function body.

Explanation / Answer

#include <iostream>

using namespace std;

static int halves(int n)
    {
        cout<<"halving number: "<<n<<endl;
        return n/2;
    }

int main()
{
   int num,iteration;
   bool flag=true;
   while(flag)
   {
   cout << "Enter Value for N" << endl;
   cin>>num;
   if (num!=0)
    {
        iteration=1;
       while(num!=1)
        {
          num=halves(num);
          cout<<"iteration step: "<<iteration++<<endl;
        }
    }
   else
   {
       cout<<"Exiting Loop"<<endl;
       flag=false;
   }
    }

   return 0;
}


o/p:

Enter Value for N 5

halving number: 5

iteration step: 1

halving number: 2

iteration step: 2

Enter Value for N 0

Exiting Loop

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