简体   繁体   中英

I made a simple program in C which calculates the factorial of a number

I made a simple program in C which calculates the factorial of a number, but at the end I want to run the program (again). Instead of seeing "press any key to continue", I want it to show "press any key to find factorial of a number again".

code:

#include<stdio.h>
int main()
{
    int facto, i, m ;
    m=1 ;
    printf("Ener a Value : ");
    scanf("%d", &facto) ;
    for( i=facto-1 ; i>m ; i-- )  
        facto *= i ; 
    printf("My Reg num:SP-16/BBS/033\nFactorial of the number : =%d\n", facto );
    system ("pause") ;
} 

"press any key to continue"

This line comes from your system(pause) . If you want to:

1.. find another factorial

2.. print another msg

you should use a loop and a printf, like this

#include<stdio.h>
int main()
{
  int facto, i, m ;
  m=1 ;
  printf("Ener a Value : ");
  while( 0 < scanf("%d", &facto) && facto > 0){
    for( i=facto-1 ; i>m ; i-- )  
      facto *= i ; 
    printf("My Reg num:SP-16/BBS/033\nFactorial of the number : =%d\n",facto); 
  printf("press any key to find factorial of a number again : ");
  }
  return 0;
} 

First of all, let me point out that your question is still very unclear. If you meant that you want to run the program continuously as long as the user wants to, then I suggest putting the factorial finding code inside a do-while loop. The while condition will be based on a 'choice' variable. Only when the 'choice' variable receives an input of 'n' (Because the program has to end at some point), will the code cease to rerun.

#include <stdio.h>

int main(void) {
int facto, i, m ;
char choice='y';

do{
  printf("Ener a Value : ");
  scanf("%d", &facto);
  m=1 ;
  for( i=facto-1 ; i>m ; i-- )  
    facto *= i ; 

  printf("My Reg num:SP-16/BBS/033\nFactorial of the number : =%d\n",facto );
  printf("Press any key to find factorial of a number again");
  scanf("%c", &choice);
  } while(choice!='n');

}

Your code is very simple and clear . I'm not doing anything to adjust that.

However, if you want to rerun the whole program again and again until some point, you should always consider using a loop with a specific end condition .

Try this (press enter to end the program, anything else will repeat it)

#include<stdio.h>
int main()
{
    int facto, i, m ;
    m=1 ;
    do {
        fflush(stdin);
        system("cls");
        printf("Ener a Value : ");
        scanf("%d", &facto) ;
        getchar();
        for( i=facto-1 ; i>m ; i-- )  
        facto *= i ; 
        printf("My Reg num:SP-16/BBS/033\nFactorial of the number : =%d\n", facto );
        printf("press any key to find factorial of a number again (Enter to end): ");
    }
    while ( getchar()!='\n');
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM