what is the problem with my code, it is not returning value if b!=-1

Viewed 65

what is the problem with my code, it is not returning value if b!=-1

 #include <stdio.h>

int find_even(int k){
    int a,b,i=0;
    scanf("%d",&a);
    while (a>=0){
        if(i<k){
            if (a>=0 && a%2 == 0){
                b=a;
                i++;
            }

        }
        scanf("%d",&a);
    }
    if (i<k){
        b=-1;
    }
    return b;

}

void main(){
    int k;
    printf("Enter the value of K : ");
    scanf("%d",&k);
    printf("Enter the sequence of non negative integers and at end enter a negative integer  : ");
    if (find_even(k)<0)
        printf("No %dth even integer exist.",k);
    else
        printf("Result = %d. ",find_even(k));
}

I am trying to get the kth even digit but I am not getting any value returned whenever the value of b isn't equal to -1

1 Answers

The reason you do not seem to get output unless you enter -1 is because you must enter at least k even numbers for (i<k) to be true. Each time you enter a positive even number in the loop, i increments:

if (a>=0 && a%2 == 0){
    b=a;
    i++;  // here

So if you enter a positive even number (say 2) more than k times, you will get a result that isn't -1.

After you return from the function, if the result is negative, you do:

printf("No %dth even integer exist.",k);

If the result is positive, you go back into the function for a second time:

printf("Result = %d. ",find_even(k)); // This is going to re-enter find_even

I think what you want to here is save the result of the function call and act on that. Like this:

int result = find_even(k);
if (result<0)
    printf("No %dth even integer exist.",k);
else
    printf("Result = %d. ", result);

Edit: I think I understand what you are trying to do now. It was a bit confusing given the request and the way things line up on the screen. Add a \n to the end of the printf to make this less confusing on the terminal:

printf("Enter the sequence of non negative integers and at end enter a negative integer  :\n");

Now, all the input will be aligned and make more sense.

Also, be careful with scanf() as it is not the most reliable function. It is good for tinkering, but it is unsafe for general purpose use. Check out this little guide for more info on scanf and all of its intricacies to using it correctly.

Related