Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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 void to int 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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading