Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

c for and while

What is the role of 'flag' in your code? You initialize it to zero, and then during the loop, you only continue if it's equal to 'y' (in C, char is just byte with fancy formatting, so 'y' = 121)

Link to post
Share on other sites
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
    int x=0, fact=0, number=0;
        printf("Enter Number:");
        scanf("%d", &number);
        if(number<1) printf("Invalid Input!\n");
        else {
            for(x=1; x<=number; x++) fact *= x;
            printf("Your factorial of %d is %d.\n", number, fact);
        printf("Would you like to try again? 'y' to continue.\n");
        if(getchar() != 'y') break;
    return 0;

You could do a while loop and break if the flag isn't set to y. Though the user will need to press enter.

If you want to accept immediate input for 'y' you will need to either watch for a actual keypress or use getch from the nonstandard C library header conio.h

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now