How to declare a variable in a loop and make it available in the template file

You are re-initializing your $x variable on every iteration of the loop. Maybe you want to move its initialization outside the loop? To get $x variable value in the content-right.php file you can declare it as global:

global $x;
$x = 0;
while( have_posts() ) {
    the_post();
    $x++;
    get_template_part( 'content', 'right' );
}

Then you can use it in the content-right.php file:

global $x;
# ... here you can use $x variable value