Mi sa che manca un

tmp=0;

dopo il secondo for