``````#include <iostream>

using namespace std;

class LoopEx
{
int x,y;
public:
void Ex;
{
x=3;
y=x; // y=3
while(y<=1) // 3<=1
y--;       // 3, 2
x=x*y;     // x= 3*3=9
cout<<x;

}
};
int main()
{
LoopEx F;
F.LoopEx();
return 0;
}``````

im trying to write a program for factorial of a number( 3 here), but its only calculating the last number in the loop ( 3 here) instead of calculating both 2 and 3. can some one please tell me whats wrong in the code.

``````#include <iostream>
using namespace std;

class LoopEx
{
public:
int x ,y;
void Ex(){
x = 1; // Point 1
y=3;
while(y>0){//Point 2
x=x*y;
--y;
}
cout<<x;

}
};
int main()
{
LoopEx F;
F.Ex();
return 0;
}``````

Point 1 : If you initialize x to zero, …

## All 2 Replies

``````#include <iostream>
using namespace std;

class LoopEx
{
public:
int x ,y;
void Ex(){
x = 1; // Point 1
y=3;
while(y>0){//Point 2
x=x*y;
--y;
}
cout<<x;

}
};
int main()
{
LoopEx F;
F.Ex();
return 0;
}``````

Point 1 : If you initialize x to zero, any multiplication done with x will always be 0.. Also, since x is to hold the result of 3!, it doesnt need to be initialized to 3.. if you do that< then you would be calculating (3*3)(3*2)(3*1).

Point 2: Your while loop did not encompass the code that was to be looped.. That was why only the last number in the loop was calculated..

thx.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.