Search code examples
cfunctionnumberscodeblocks

Function to find odd numbers returns extra value - C Language


I wrote a code in C to find the odd numbers from a given interval of min and max number. The function works well when it is inside the int main() but not well when outside the program as a function.

What's more is that it also prints the incremented number outside the max number given.

This is the code...

#include <stdio.h>
// My Function
int odd_numbers(int x, int y) {
    for (int i = x; i <= y; ++i) {
        if (i % 2 == 1) {
            printf("%d\n",i);
        }
    }
}

// Main Program
int main(void) {
    int min_num, max_num;

    printf("Input your minimum number: ");
    scanf("%d", &min_num);
    printf("Input your maximum number: ");
    scanf("%d", &max_num);

    printf("%d",odd_numbers(min_num,max_num));
}

and this is the output... As you can see, it adds an 11 besides the 9... How can I solve this? I've tried return 0; and it returns the value 0 but i only want to return no number except the odd numbers.


Solution

  • Here is the working code.

    Notes

    1. Change the return type of odd_numbers from int to void because you are not returning anything when the function is called.

    2. Only call the function odd_numbers, no need to printf anything because odd_numbers already does the job.

    #include <stdio.h>
    // My Function
    void odd_numbers(int x, int y) {
        for (int i = x; i <= y; i++) {
            if (i % 2 != 0) {
                printf("\n%d",i);
            }
        }
    }
    
    // Main Program
    int main(void) {
        int min_num, max_num;
    
        printf("Input your minimum number: ");
        scanf("%d", &min_num);
        printf("Input your maximum number: ");
        scanf("%d", &max_num);
    
        odd_numbers(min_num,max_num);
    }