for(int i=0; i<len_arr; i++)
if(arr[i] == some_num){
printf("The idx of %d is: %d\n", some_num, i);
break;
}
if(i == len_arr)
printf("Number not found.\n");
This doesn't work. Because that i
can't be accessed outside the loop.
I have thought of two ways to achieve what effect I want.
But my question is, is there any other more elegant way to do the effect?
Way 1:
int i;
for(i=0; i<len_arr; i++)
if(arr[i] == some_num){
printf("The idx of %d is: %d\n", some_num, i);
break;
}
if(i == len_arr)
printf("Number not found.\n");
Way 2:
for(int i=0; (i<len_arr) && (printf("Number not found.\n")); i++)
if(arr[i] == some_num){
printf("The idx of %d is: %d\n", some_num, i);
break;
}
I find Luka Rahne's solution the most ideomatic.
If you really want to do the loop you could do it like this: