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(); } 

    2 answers 2

     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.

    • does not work, the output of similar elements displays the entire array - GALIAF95
    • What method output? - BlackOverlord
    • printf ("% i", a [i]) - GALIAF95
    • Aaaa ... when i = 0, a [i] = 1, 1 = 1 it outputs ... Clearly, it is necessary that the values ​​of i and k do not coincide, that is, if i = 0, then k must move from 1 to 4 and etc. - BlackOverlord
    • ^^^^^^^^ fixed - BlackOverlord

    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.