0
#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.

Edited by Srinivas0: n/a

2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by Srinivas0
0
#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..

Edited by tkud: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.