#include "std_lib_facilities.h"
usingnamespace std;
int square (int x) //x is the base
{
for(int c=0;c<=x;++c) //How many times the base should be repeated
{
x+=x; //base being repeated
}
return x;
}
int main()
{
int v=0;
cout<<"ready"<<endl;
cin>>v; // v is the input
cout<<square(v)<<endl;
return 0;
}
Instead of adding x times, you are doubling the value of x each time. In other orders, your program produces x*(2^x). If x is a large number, then probably you must be exceeding the int limit.
Change it to:
1 2 3 4 5 6 7 8 9 10
int square (int x) //x is the base
{
int initial_x = x;
for(int c=0;c<x-1;++c) // only x-1 iterations because initial value is x, not 0.
{
x += initial_x;
}
return x;
}
There is a problem in both examples of trying to hit a moving target.
Original code:
1 2 3 4
for (int c=0; c<=x; ++c)
{
x+=x;
}
Code from abhishekm71:
1 2 3 4
for (int c=0; c<x-1; ++c)
{
x += initial_x;
}
Notice in both cases c is being compared with x or x-1. But x is changing each time around the loop, so the loop will not terminate as expected, that is not until x overflows and becomes negative.
You could do something like this:
1 2 3 4 5 6 7 8 9 10 11
int square (int x)
{
int sq = 0;
for (int c=0; c<x; ++c)
{
sq += x;
}
return sq;
}
Note that this won't give the correct result for negative values of x. You could fix that by inserting this at the start:
1 2
if (x < 0) // allow for negative value
x = -x; // x squared is always positive or zero.