0

// To find the index of an array element int main(){ int arr[20]; int n; int x;

printf("enter the no. of                  elements you want");
scanf("%d",&n);

printf (" enter the array elements of your wish");
for( int i =0;i<=n-1;i++){
   scanf("%d\n",&are[i]);
 }

printf("the array elements are");
for( int i =0;I<=n-1;i++){
printf("%d\n",are[i]);
}

printf("enter any value and you will see it's index");
scanf("%d",&x);

for( int i=0;i<=n-1;i++){
if( x==arr[I]){ printf("%d",i);}
}

return 0;
}

I expected to get the following: enter the number of elements you want (say5) Enter the array elements of your wish (1 2 3 4 5....say) The array elements are 1 2 3 4 5 Enter any number and you will see it's index ( say 5) 4

But,this is what I am getting: enter the number of elements you want (say5) Enter the array elements of your wish (1 2 3 4 5....say) The array elements are 1 2 3 4 5 Enter any number and you will see it's index

  • From here I can't scan and intake value and the following loop is not running. I don't understand why.
  • You have: `scanf("%d\n", &are[i]);` — that input won't terminate until after you type a number and then something else after the number other than white space (and white space includes newlines). Drop the `\n` from the format string. And you MUST check the return value from `scanf()` to ensure you got a valid value. Every time you use it, check it. And testing against EOF is almost always wrong; you want to ensure you got as many values as you expected. You expect 1, so `if (scanf("%d", &are[I]) != 1) { …report error…; …break or return or exit…; }`. – Jonathan Leffler Apr 20 '23 at 05:00

0 Answers0