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

Why does the function return zero?

The function should print numbers that are divisible by 3 in the given range. For example if I give the range [3,9] it should print 3,6,9 but it prints 0,3,6,9. Why is that? How to fix it?

#include <stdio.h>
int main()
{
    printf("enter the value of a \n");
    int a;
    scanf("%d",&a);

    printf("enter the value of  b \n");
    int b;
    scanf("%d",&b);

   if(a>b)
    {
        printf("[%d,%d]\n",b ,a);


        for(  int b; b<=a; b=b+3)
        {
            printf("%d\n", b);
        }
    }

return 0;
}

>Solution :

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

In this line

for(  int b; b<=a; b=b+3)
{
    printf("%d\n", b);
}

you are doing int b which you might know is who you declare variables, that means you are declaring a b inside the block of the loop, and since int’s are initialized as 0 by default, your b is always going to be 0. Try removing that redeclaration and see if that fixes your problem

Yes, something like this is still valid:

for(; b<=a; b=b+3)
{
    printf("%d\n", b);
}
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