Home > OS >  To print factors of given number in C
To print factors of given number in C

Time:09-29

I'm trying to print the factors of a given number in C. But when I enter a number in console, nothing happens.

#include <stdio.h>
int main() {
    int n;
    printf("enter the number ");
    scanf("%d ", &n);
    for(int i = 1; i <= n; i  ) {
        if(n % i == 0) {
            printf("%d", i);
        }
    }
    return 0;
}

CodePudding user response:

This is why your code isn't working as you expected:

scanf("%d ",&n);

Change it to:

scanf("%d", &n); // Remove the space after %d

The reason is that scanf("%d ", &n) expects an int followed by one or more whitespaces. A whitespace can either be a , a tab \t or a newline \n. When you enter a number and then press Enter, scanf() normally consumes everything up to a newline, but in this case it also consumes the newline(s), so it continues to wait for input until you enter a non-whitespace character.

CodePudding user response:

There are multiple problems in the code:

  • scanf("%d ", &n); will convert user input as an integer in base 10 and attempt to consume any whitespace characters that follow. Hence scanf() will not return until the user types a non whitespace character... causing the program to do nothing after you hit the enter key. This key produces a newline ('\n') character in the input stream, which is a whitespace character. Remove the trailing space in "%d " to fix this problem.
  • you should test the return value of scanf("%d", &n) to check that a number was successfully converted by scanf. The return value will be 1 if so, or 0 if the first non whitespace character entered is not a digit, and EOF if the end of file is reached before a number can be converted.
  • printf("%d", i) does not output a space or a newline after the number, so all factors will be output as a single string of digits.

Here is a corrected version:

#include <stdio.h>

int main() {
    int n;
    printf("enter the number ");
    if (scanf("%d", &n) == 1) {
        for (int i = 1; i <= n; i  ) {
            if (n % i == 0) {
                printf("%d\n", i);
            }
        }
    }
    return 0;
}
  •  Tags:  
  • c
  • Related