The task is to find the same values in the array. What is wrong in the code?
void main(void) { int a[5]={1,5,3,4,5},i=0,k; for(k=0;k<=4;k++) { do { if(a[k]==a[i]){ printf("%i",a[i]); } i++; } while((i-4)==0); } _getch(); }
The task is to find the same values in the array. What is wrong in the code?
void main(void) { int a[5]={1,5,3,4,5},i=0,k; for(k=0;k<=4;k++) { do { if(a[k]==a[i]){ printf("%i",a[i]); } i++; } while((i-4)==0); } _getch(); }
void main() { int a[5]={1,2,3,4,5}; int i=0;k=0; for (i=0; i<5; i++) { for(k=5;k>i;k-1){ if(a[i]==a[k]){Напечатать сообщение или убить всех человеков;} } } }
The point is that the program will compare 1 element with all in the array, then the 2nd element with all, etc.
Error in this line: while((i-4)==0);
. Replace it with while(i<5);
and also initialize i zero in the outer loop before do. Have you ever tried to look for a mistake? Before you run the code, you need to scroll the algorithm in your head. At once you will come across that in while will compare-4 with 0, and the cycle will stop.
The corrected version should work, but I don’t like it very much. Why interfere with different cycles? The do ... while loop always runs at least once, regardless of the condition. Here it is not necessary, you can do two for, as you wrote above.
Source: https://ru.stackoverflow.com/questions/68188/
All Articles