I’m having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn’t seem to work as they keep looping when the condition is reached:
#include<stdio.h> #define MAX 255 int main(){ int arr[MAX]={0}; int idx=0; /* Approach #1 */ printf('Enter elements, -1 to finish:\n'); scanf('%d', &arr[idx]); while(arr[idx-1] != -1 && idx < MAX){ printf('Enter elements, -1 to finish:\n'); scanf('%d', &arr[idx]); idx++; } /* Approach #2 */ do{ printf('Enter elements, -1 to finish:\n'); scanf('%d', &arr[idx]); idx++; }while(arr[idx-1] != -1 && idx < MAX); // Main func continues here. }
Any advice would be much appreciated!
Update:
Now it works! thanks MUCH all of you guys for such instant responses. This is definitely a great community, it’s helping me a lot.
should be
unless you are checking the item instead of the index.
You are also always checking the ‘next’ element for -1 (arr[idx] != -1) because you are incrementing idx prior to checking your added value.
so if you had
you would be fine.