Hi all,

My problem is this: I'm doing a small game in C and the problem is that in my only while loop that I'm using, I call a function. Now when I enter a letter, as required by my code, the while loop executes twice and if I type just [Enter] than it executes only once. I have no idea what I'm doing wrong and I ask if anyone could help me solving this issue. Thank you and much appreaciate your help. Here is my code:

Code:/* Purpose: a C game used to implement a puzzle using an array */ #include <stdio.h> #include <conio.h> #include <ctype.h> //declare global variables used in program int table[4][4] = {{1,4,15,7},{8,10,2,11},{14,3,6,13},{12,9,5,0}}; int count = 0; //provide the prototype of each function void displayTable(void); void moveNumbers(void); void moveRight(void); void moveLeft(void); void moveUp(void); void moveDown(void); int checkForFinish(void); int keepCounting(int); //start the main function main(void){ displayTable(); int finished = 0; while(finished != 1){ moveNumbers(); finished = checkForFinish(); } printf("Congratulations! You finished the game!"); printf("\n\nPress any key to exit... "); getche(); } //function used to move the numbers in the grid void moveNumbers(){ int key; printf("\n\nEnter a letter(L,R,U or D): "); key = getchar(); key = tolower(key); if(key == 'l') moveLeft(); if(key == 'r') moveRight(); if(key == 'u') moveUp(); if(key == 'd') moveDown(); displayTable(); keepCounting(key); } //moves the number to the right void moveRight(){ int temp,i,j; for(i = 0; i < 4; i++){ for(j = 0; j < 4; j++){ if(table[i][j] == 0 && j != 0){ temp = table[i][j-1]; table[i][j-1] = 0; table[i][j] = temp; } } } } //moves the number to the left void moveLeft(){ int temp,i,j; for(i = 3; i >= 0; i--){ for(j = 3; j >= 0; j--){ if(table[i][j] == 0 && j != 3){ temp = table[i][j+1]; table[i][j+1] = 0; table[i][j] = temp; } } } } //moves the number up void moveUp(){ int temp,i,j; for(i = 3; i >= 0; i--){ for(j = 3; j >= 0; j--){ if(table[i][j] == 0 && i != 3){ temp = table[i+1][j]; table[i+1][j] = 0; table[i][j] = temp; } } } } //moves the number down void moveDown(){ int temp,i,j; for(i = 0; i < 4; i++){ for(j = 0; j < 4; j++){ if(table[i][j] == 0 && i != 0){ temp = table[i-1][j]; table[i-1][j] = 0; table[i][j] = temp; } } } } //function used to display the table void displayTable(){ int i,j; for(i = 0; i < 4; i++){ printf("\n\n"); for(j = 0; j < 4; j++){ if(table[i][j] == 0) printf(" "); else if(table[i][j] < 10) printf(" %d ",table[i][j]); else printf("%d ",table[i][j]); } } printf("\n"); } //function used to check if the grid is arranged from 1 to 15 int checkForFinish(void){ int i,j,temp,result; result = 0; temp = 1; for(i = 0; i < 4; i++){ for(j = 0; j < 4; j++){ if(table[i][j] == temp){ temp += 1; } } } if(temp == 15) result = 1; return result; } //function used to keep count of user moves int keepCounting(int userOption){ if (userOption != 0){ count += 1; } printf("\n\nTotal number of moves taken so far is: %d", count); }