Click here to Skip to main content
15,893,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In the below code to find an element is present in an array or not,I am not getting the output if else part is uncommented.

C++
#include<stdio.h>
int main()
{
    int a[]={2,5,8},i,n=2,flag=0;
     
        for(i=0;i<10;i++)
        {
            if(a[i] == n )
            {
                flag = 1;
            }
            //else 
              //  flag = 0;
        }
        if(flag==1)
                printf("present %d\n",n);
}


What I have tried:

If else part is commented ,I am getting output.
Posted
Updated 22-Nov-16 21:02pm
v2

Simple: if you uncomment the line, then every time it doesn't find a match, it sets the flag to "no match". Which means that if you find a match in the first location, you set the "found it" flag, and overwrite it back to "not found" for every other character in the array.
The best solution to this is simple: exit from the loop when you find a match:
C#
int main()
    {
    int a[]={2,5,8},i,n=2
    for(i=0;i<10;i++)
        {
        if(a[i] == n )
            {
            printf("present %d\n",n);
            break;
            }
        }
    }
 
Share this answer
 
When the else part is present the flag is set according to the last checked item. Then the loop is not necessary because a similar check would be:
C++
if (a[9] == 2)
    flag = 1;
else
    flag = 0;

Writing it down this way you should also recognise that you are accessing items that are not part of the array (out of bound access) because your array has a size of three items so that the highest allowed index is two.
 
Share this answer
 
Comments
CPallini 23-Nov-16 2:57am    
5.
It is really obvious that the flag is set to 0 in your else. It happens EVERYTIME when the if statement fails.

You should use the debugger !!!

And make someTRACE output if something is unclear.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900