Juan Carlos Piñeros Juan Carlos Piñeros - 3 months ago 6
C Question

I can't find why my loop is not working

I am new to programming and I am trying to solve some problem in C. I can't understand something and I could not find any explanation on Internet. My code is as follows (I am just testing something)

#include <stdio.h>

void sort(int[], int);

int main(void)
{
int myarray[5] = {3, 2, 9, 6, 5};
printf("%d, %d, %d, %d, %d\n", myarray[0], myarray[1], myarray[2], myarray[3], myarray[4]);

sort(myarray, 5);
printf("%d, %d, %d, %d, %d\n", myarray[0], myarray[1], myarray[2], myarray[3], myarray[4]);
}

void sort(int values[], int n)
{
for (int i = 0; i < n; i = i++)
{
if(values[i] > values[i + 1])
{
printf("%d\n", i);
int a = values[i];
int b = values[i + 1];
printf("%d, %d, %d, %d, %d\n", values[0], values[1], values[2], values[3], values[4]);
printf("%d, %d\n", a, b);
values[i] = b;
values[i + 1] = a;
printf("%d, %d, %d, %d, %d\n", values[0], values[1], values[2], values[3], values[4]);
}
}
}


And what I get is:


  • 3, 2, 9, 6, 5

  • 0

  • 3, 2, 9, 6, 5

  • 3, 2

  • 2, 3, 9, 6, 5

  • 2 //(Shouldn't it be 1?????)

  • 2, 3, 9, 6, 5

  • 9, 6

  • 2, 3, 6, 9, 5

  • 3

  • 2, 3, 6, 9, 5

  • 9, 5

  • 2, 3, 6, 5, 9

  • 4

  • 2, 3, 6, 5, 9

  • 9, -1076375724

  • 2, 3, 6, 5, -1076375724

  • 2, 3, 6, 5, -1076375724


Answer

In for loop check the i= i++. It should be only i++. Since i++ is i = i+1

for (int i = 0; i < n; i++)