Practice question 2 on array level 2 The code I have is this : #include<stdio.h> 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?
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;
}
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;
}