Close
Close

Displaying if a number entered is a number previously entered in an array (no answer to practice question)

   Ben

Practice question 2 on array level 2

 

The code I have is this :

 

#include<stdio.h>
int main()
{
    int a[10], i, j;
    for(i == 0 ; i < 10 ; i++)
    {
        printf("Enter a number.\n");
        scanf("%d", &a[i]);
    }
    printf("Enter another number.\n");
    scanf("%d", &j);
    if(j == a[i])
    {
        printf("The number you have entered is equal to one in the array.\n");
    }
    else if(j != a[i])
    {
        printf("The number you have entered is not one in the array.\n");
    }
    return 0;
    
}

 

 

But, no matter what the number at the end is, it still says my if statement of it is in the array, whether the number be 2 or 20. What is wrong with the code?


Answers

  •   

    Please fo through the comments.

    #include<stdio.h>
    int main()
    {
        int a[10], i, j;
        //use i = 0. i==0 is for comparision,
        //here you are assigning 0 to i. So, you
        //should use i=0
        for(i = 0 ; i < 10 ; i++)
        {
            printf("Enter a number.\n");
            scanf("%d", &a[i]);
        }
        //after the end of this loop i is 9
        printf("Enter another number.\n");
        scanf("%d", &j);
        //so here j is compared to a[9], as i is 9
        //you should use another loop for the purpose of checking
        int present = 0;
        for(i = 0 ; i < 10 ; i++)
        {
            if(j == a[i])
            {
                present = 1;
                break;
            }
        }
        if(present)
            printf("The number you have entered is equal to one in the array.\n");
        else
            printf("The number you have entered is not one in the array.\n");
        return 0;
        
    }
    

     


    • Thank you so much
      - Ben
    • Question, why am I using a loop to check, rather than a simple if/else statement? Like, why have a loop and then break it, instead of 1 if/else statement?
      - Ben
    • You have an array an a number now you want to check whether or not the number is present in the loop or not. So, the most common thing is to go through each element of the array and check if that element is equal to the number or not. This is what loop is doing, it is iterating through each element of the array. Now, if you found the number then there is no need to check further, so just break the loop.
      - Amit Kumar
    • Ohhhh I got it, okay, again, thanks so much :)
      - Ben

Ask Yours
Post Yours
Write your answer