the loop in the main() gets executed only once

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int factorial(int, int);

int main()
{
system("cls");
int x=1, n;
char ch;
do {
cout << "enter no." << endl;
cin >> n;
x = factorial(x, n);
cout << x << endl;
cout << "Again?y/n" << endl;
ch = getchar();
cout << "ended";
} while (ch == 'y');
getchar();
return 0;
}
int factorial(int a, int b)
{
while (b != 1)
{
a = a*b;
b--;

}
return a;
}
try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>

// Unless system("cls"); uses these header files, they should be removed.
//#include<stdio.h>
//#include<stdlib.h>

using namespace std;

int factorial(int, int);

int main()
{
    system("cls");
    int x=1, n;
    char ch;
    do {
        cout << "enter no.: ";
        cin >> n;
        x = factorial(x, n);
        cout << x << endl;
        cout << "Again? (y/n): ";
        cin >> ch;
        cout << "\n\n"; // this is same as endl x 2 
    } while (ch == 'y');

    cout << "ended\n\n";
    return 0;
}

int factorial(int a, int b)
{
    while (b != 1)
    {
        a = a*b;
        b--;

    }
return a;
}


system("cls"); doesn't work for me, so I left it where it is. If it works for you, then move it down to line 17 to get the result you're looking for.
Last edited on
Seems a typical problem with a dangling '\n'
cin >> n; will not remove the '\n' so getchar() will read it into ch and while (ch == 'y'); will be false.

This should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

int factorial(int, int);

int main()
{
  system("cls");
  int x = 1, n;
  char ch;
  do {
    cout << "enter no." << endl;
    cin >> n;
    x = factorial(x, n);
    cout << x << endl;
    cout << "Again?y/n" << endl;
    cin.ignore(255, '\n'); // read dangling '\n'
    ch = getchar();
    cout << "ended";
  } while (ch == 'y');
  cin.ignore(255, '\n'); // read '\n' left from previous getchar
  getchar();
  return 0;
}
int factorial(int a, int b)
{
  while (b != 1)
  {
    a = a*b;
    b--;

  }
  return a;
}

Output
enter no.
5
120
Again?y/n
y
endedenter no.
7
604800
Again?y/n
n
ended


system("cls"); doesn't work for me
cls works on Windows, for linux you can try
system("clrscr"); However it's rarely necessary to clear the screen
Topic archived. No new replies allowed.