Replace your for loop with:
$('.gallery img').each(function(i) {
$(this).attr('id', 'img' + i);
// You can also add more code here if you wish to manipulate each IMG element further
});
This block of code loops through each IMG element with a counter i incrementing after every instance, and this counter is suffixed to the id string.