You are here:

C++/Recursive Problem


I have a problem..
My program will ask the user to input any number to be squared.

Basically, using stdio.h and conio.h

The usual code goes:
int Square(int x)
return x*x;

I want to use a recursive way in squaring the x. SO instead of x*x, i don't know what to substitute.
My code is this:
int Square(int x)
if (x==0) return 0;
if (x==1) return 1;
return x + Square(x);

i don't know what to do...

if the given is 4: (the answer is 16)
the process for the usual code is:
answer = 4*4

the process i need for my code is:
answer = 4+4+4+4

The restrictions: No using of brutal or the 'obvious x+x+x+x' procedure. No loops. Just the if else statement.

Please reply. Tnank you.
Summary: My question is: can u give me a code of a recursive square procedure? ...Thanx

Hello Gerard, thank you for the question.

I'm going to have to assume this is some kind of assignment, because recursion is supposed to always be the last course of action. Recursion is extremely slow due to all of the function calls stored on the call stack. Your first solution to the problem is by far the optimal one. Lets take a look at a recursive solution(note, the if checks if x == 1 or x == 0 are unnecessary because those will be handled):

int Square(int x)
// make sure to handle the case of a negative number
if(x < 0)
x = -(x);

// keep track of the ORIGINAL number passed in
static int temp = x;

// are we done recursing?
if(x == (temp * temp))
return x;

// try the next number
x += temp;

// recurse

And that function should do the trick. It adds the new recursed paramter to the original paramter passed in, and continues recursing based on if it is the square yet. There perhaps may be some oddball situation where a number doesn't have a perfect aquare, so you could modify as necessary. I hope the recursive function isn't painful to look at, as I always find them to be.

I hope this information was helpful.

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 All rights reserved.