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

Define a class named PositiveInteger to represent positive integer. Your class s

ID: 3936901 • Letter: D

Question

Define a class named PositiveInteger to represent positive integer. Your class should have the following: 1. A default constructor to initialize the data field to zero. 2. A non default constructor to initialize a specified value. 3. An accessor and a mutator function 4. A getLength( ) function to return the length of the integer. 5. A data field to store the integer value. 6. Overload the subscript operator [] such that the index i will return the digit in position i, with i=0 being the position of least significant digit. The operator should return -1 if the index is out of bound. For example, if num is an object of PositiveInteger and the integer represented is 123, then num[0] will return 3, num[1] will return 2, num[2] will return 1 and num[3] is out of bound will return -1. Negative index value such as num[-1] will also return -1. Use the main method below to test your program: int main() { PositiveInteger num; int intNum, len; cout << "Please enter an integer: "; cin >> intNum; num.setInt(intNum); cout << "getInt returns: " << num.getInt() << endl; len = num.getLength(); cout<<"Length of integer is: "<< len<

Explanation / Answer

#include<bits/stdc++.h>
using namespace std;

class PositiveInteger
{
   char arr[100] ;
   int SIZE;

public:
   //Construcotrs
   PositiveInteger()
   {
       memset(arr,0,sizeof(arr));
       SIZE=0;
   }

   PositiveInteger(int num)
   {
      

        sprintf(arr, "%d", num);
        SIZE=strlen(arr);
        //cout<<"Size"<<SIZE;

   }

//Setter
   void setInt(int num)
   {
   sprintf(arr, "%d", num);
   SIZE=strlen(arr);

   }
//Getter
   int getInt()
   {
       int i;
       sscanf(arr, "%d", &i);
       return i;
   }

   int getLength()
   {
       return SIZE;
   }

//Overload subscript
   char &operator[](int i) {
if( i < SIZE ) {

return arr[SIZE-i-1];

}
else
{  

    cout<<"Out of bound ";
    char a[]={-1};

    return a[0];
       
        }
}
};

int main(int argc, char const *argv[])
{
   PositiveInteger num;
   int intNum, len;
   cout << "Please enter an integer: ";
   cin >> intNum;
   num.setInt(intNum);
   cout << "getInt returns: " << num.getInt() << endl;
   len = num.getLength();
   cout<<"Length of integer is: "<< len<<endl;
   return 0;
}

==================================

output:

akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Please enter an integer: 123
getInt returns: 123
Length of integer is: 3

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