Continue to Site

# [moved]array in if condition in C program

Status
Not open for further replies.

#### vilfred

##### Member level 1
Hi...I need to compare array with sequence of numbers using if condition in C. I tried the following steps but it doesn't produce the correct results please give me the right answer.

a).
Code:
int a[3]={4,1,2};
int b[3]={1,2,3};

if (a[0] ==4)  // checking the first element in array
{
if (a[1] ==1)  // checking second element in array
{
if(a[2]==2)  // checking third element in array
{
printf("the entered numbers are in 'a' array\n");
}
}
}
else
{
if (b[0] == 1)
{
if (b[1] == 2)
{
if (b[2] == 3)
{
printf("the entered numbers are in 'b' array\n");
}
}
}

b).
Code:
int a[3]={4,1,2};
int b[3]={1,2,3};

if(a[3] == 4,1,2)
{
printf("the entered numbers are in 'a' array\n");
}
else
{
if(b[3] == 1,2,3)
{
printf("the entered numbers are in 'b' array\n");
}

Last edited by a moderator:

Re: array in if condition in C program

At first glance there does not seem to be anything wrong with the above code, but it would help if you gave more details about what exactly is not working. By the way, to give you a clue to the probable cause, you could insert some "printf()" after each if evaluation (from the first) to know if you are at least comparing correctly.

the "printf" statement is located correctly because i need to check the sequence of number if the first number i've entered is '4' then it want to check next number if the next number is '1' it want to go for next check as '2'. if the three numbers are entered simultaneously then my printf statement should appear.

the "printf" statement is located correctly because i need to check the sequence of number if the first number i've entered is '4' then it want to check next number if the next number is '1' it want to go for next check as '2'. if the three numbers are entered simultaneously then my printf statement should appear.

I have not said anywhere that printf is in the wrong place; What I meant is that you can use this feature to debug the program, in which case you would not print the result of the comparison, but only useful information such as "the above condition was reached" or whatever.

vilfred

### vilfred

Points: 2
Code:
if (memcmp((char*)a, (char*)b, sizeof(a) * sizeof(int))) printf ("strings NOT equal"); else printf ("strings equal");

vilfred

Points: 2