How to know that the loop was breaked early?

186 views Asked by At
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;
    }
5

There are 5 answers

0
JBarberU On BEST ANSWER

I find Luka Rahne's solution the most ideomatic.

If you really want to do the loop you could do it like this:

for(size_t i(0); i <= len_arr; ++i)
{
    if(i == len_arr)
    {
        std::cout << "Number not found." << std::endl;
    }
    else if(arr[i] == some_num)
    {
        std::cout << "Found " << some_num << " at index: " << i << std::endl;
        break;
    }
}
0
Chris R. On

If you don't want to use std like Luka suggests and only want to do a simple loop, you can do as I always do:

int i;
for(i = 0; i < len_arr && arr[i] != some_num; i++);
if(i < len_arr)
    printf("The idx of %d is: %d\n", some_num, i);
else
    printf("Number not found.\n");
3
Sergii Khaperskov On

There are many ways to achieve this goal. I used to do like this:

bool found = false;
for(int i=0; i<len_arr; i++)
{
    if(arr[i] == some_num)
    {
        printf("The idx of %d is: %d\n", some_num, i);
        found = true;
        break;
    }
}
if(!found)
    printf("Number not found.\n");

This variation looks the most clear/readable to me.

1
Luka Rahne On

If you cant express this easily, dont use loop at all. You can use dedicated function for searching in this concrete case.

auto start = arr;
auto end = arr + len;
auto val = std::find(start,end,some_num);
if (val != end)
   printf("The idx of %d is: %d\n", some_num, std::distance(start,val));
else
   printf("Number not found.\n");
0
rammar On

Personally i don't like a break in a loop and this is my solution:

bool found = false;
for(int i=0; i<len_arr && !found; i++){
    if(arr[i] == some_num){
        printf("The idx of %d is: %d\n", some_num, i);
        found = true;
    }
}
if(!found)
    printf("Number not found.\n");