Angus
Angus

Reputation: 12621

if condition in the for loop

This program outputs 1. I could not understand how it outputs 1 as the for loop will fail at a[2][3] which contains the value 12. So 12 will get assigned to k and the output will have to be 12.

#include<stdio.h>

int main()
{
    int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
    int i,j,k=99;
    for(i=0;i<3;i++)
    {
        for(j=0;j<4;j++)
        {
            if(a[i][j]<k)
            {
                k=a[i][j];
                printf("%d\n",k);
            }
        }
    }
    printf("Res:%d\n",k);
    return 0;
}

Upvotes: 0

Views: 639

Answers (3)

rossum
rossum

Reputation: 15685

Some comments:

Calling a variable k tells us nothing about what you are using it for. Had you called it arrayMin then it would have been clearer to us. Using i and j for loop indexes is fine, that is expected.

Assigning k=99 makes assumptions about the contents of the array and hence makes for fragile code. Better not to make assumptions and to start by assigning arrayMin = a[0][0]

Your program is small and simple enough that you could run through it yourself on paper. Doing that would have helped you see what was going on. Using a debugger to single-step through it would have helped as well.

Upvotes: 1

Elemental
Elemental

Reputation: 7491

The first time through the loop the if is evaluated as a[0][0] < k which is 1 < 99 which is true. The second time through he loop if the if is a[1][0] < k which is 2 < 1 which evaluates as false thus the value of k is not updated k is never reassigned another value, thus at the end k=1.

Upvotes: 2

Yurii Hohan
Yurii Hohan

Reputation: 4171

In this line you are changing the K value

k=a[i][j];

And the first itteration you run would change k to 1, that's why the second itteration would fail. On every itteration your k would be one unit less than it should be for if statement to work

Upvotes: 1

Related Questions