one occurrence

hi
in that code:

#include <iostream>

using namespace std;

int main()
{
int arr[]={5,4,3,6,7};
int num;
cin>>num;

for(int i=0;i<5;i++)
{
if(num==arr[i])
{
cout<<(i+1)<<endl;
break;
}
}

for(int j=0;j<5;j++)
if (num!=arr[j])
{
cout<<"not found"<<endl;
break;
}

return 0;
}

I want to enter number and show its order on the screen ... but if this number is not exist ... display mmessage " not found"
I have a bug in that code that when I find the number in the array ... the program doesn't stop ... it goes to the second for loop ... ho can I stop that?
What you write is what you get. I do not see any bug in your code. You simply should write a code that does what you want.
closed account (zb0S216C)
You really don't have to have two loops when you can easily merge the two:

1
2
3
4
5
6
7
8
9
for(int I_(0); I_ < 5; ++I_)
{
    if(Num_ == Arr_[I_])
    {
        // Are the same...
    }

    // Not the same...
}

To me, it sounds like you want to indicate whether the said number was found within the array. For this, I recommend using bool; a type that has two distinct values: true & false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool Found_(false); // Local to "main()".
for(int I_(0); I_ < 5; ++I_)
{
    if(Num_ == Arr_[I_])
    {
        // Are the same...
        Found_ = true;
        break;
    }

    // Not the same...
}

if(!Found_)
{
    // ... Not found...
}

Wazzak
but who can I modify it to get this out put
ex1:

4
2





55
not found




not to repeat any thing
no ... this code doesn't make what I want :(
Please use the CODE blocks when displaying code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

#include <iostream>

using namespace std;

int main()
{
    int arr[]= {5,4,3,6,7};
    int num;

    cin>>num;

    for(int i=0; i<5; i++)
    {
        if (num == arr[i])
        {
            cout << "Found At Element: " << (i+1) << endl;
            break;

        }else if (num != arr[i])
        {
            cout << "Not Found" << endl;
            break;
        }
    }
}


Is this what you're after?

Input:
100

Output:

Not Found

Input:
5

Output:

Found At Element: 1
Last edited on
thanks ^_^
Topic archived. No new replies allowed.