Kelly C Kelly C - 1 month ago 7
C++ Question

Iterates and square the odd numbers less than 30 with class in c++

I'm working on a C++ program which iterates through numbers less than 30 and finds out the odd numbers among then square it.
I am required to use class function in the program but my output was a list of '0'. I am not sure whether I am having issues in declaring my constructors that gives me such output.

So my code looks like this:

#include <iostream>
using namespace std;

class Square // class to square integers
{
private:
int x;

public:
Square()//no argument constructor
{
x = 0;
}

Square(int num)//constructor with argument
{
x = num;
}

int square()//member function with no argument
{
return x;
}
int square(int num)// member function with argument
{
x *= num;

return x * x;
}
};

int main()
{
//int x = 0;
Square odd;

cout << "This program iterates through the odd numbers less than 30." << endl;
cout << "The program will output the Square of the numbers." << endl;

for (int x = 0; x < 30; x++)
{
if (x % 2 != 0)
{
cout << odd.square() << endl;
}
}

return 0;
}

Answer

You're initializing Square to its default value of 0. You need to do this

Square odd;

for (int i = 1; i < 30; i += 2) {
  Square odd(i);
  cout << odd.square(1) << endl;
}
Comments