Reputation: 57
For searching an element in array I divided the array of size 20 in two parts. a will search from 0-9 and b will search from 10-19. But this code is not working. What is wrong with it?
for( a=0,b=10; a<9,b<20 ; a++,b++ )
{
if(x[a]==n)m=a;break;
if(x[b]==n)m=b;break;
if(x[c]==n)m=c;break;
if(x[d]==n)m=d;break;
}
Upvotes: 0
Views: 167
Reputation: 1198
One of the problems in your code is in the condition of the for
loop. It should be:
for (a = 0, b = 10; a < 9 && b < 20; a++, b++) { ... }
Notice the &&
between a < 9
and b < 20
.
There is also a logic flaw in your for
loop. Indeed, for each iteration of the loop, a
and b
get incremented by 1. This means that when a = 9
, then a < 9
will be false
, and the for
loop stops. But, when a = 9
, then b = 19
, so you will never look at x[19]
because the loop has already ended.
I think the correct condition is: a < 10 && b < 20
.
Fact is, you don't really need both a
and b
. Look at the following example:
for (a = 0; a < 10; a++) {
if (x[a] == n || x[a + 10] == n) {
m = a;
break;
}
}
Also, when you have more than one statement in an if
block, you must wrap them in { ... }
brackets.
// Incorrect
if (x[a] == n) m = a; break;
// Correct
if (x[a] == n) {
m = a;
break;
}
// Also correct
if (x[a] == n) { m = a; break; }
As pointed out by other users, you use c
and d
inside your loop, but what are they?
Upvotes: 4
Reputation: 471
Your code has many errors you can try this
for( a=0,b=10; a<10 && b<20 ; a++,b++ )//&& between conditions and a<10 otherwise 9th element will be skipped
{
if(x[a]==n)
{
m=a;break;//parenthesis used because it contains 2 statement
}
if(x[b]==n)
{
m=b;break;//parenthesis used because it contains 2 statement
}
//extra statements were removed
}
Upvotes: 0