I'm working on inserting new number into existing string. The code seems to be working fine but it has thrown up a related issue - while trying to make sure that the position in which the new number is to be inserted, I can check only once if the position index is in the correct range but if an incorrect position index is re-entered then the code proceeds with the wrong position number and throws up funny results. How can I keep sending warning messages to the user until the position is entered within correct range? Thanks; the code is as follows:
Code:
#include <stdio.h>
int main()
{
int arr[100];
int i, size, num, position, temp_position;
/*
* Reads size and elements of array
*/
printf("Enter size of the array : ");
scanf("%d", &size);
printf("Enter elements in array : \n");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/*
* Read element to insert and position of the element
*/
printf("Enter element to insert : ");
scanf("%d", &num);
printf("Enter the element position : ");
scanf("%d", &temp_position);
/*
* If the position of element is not valid
*/
if(temp_position>size+1 || temp_position<=0)
{
printf("Invalid position! Please enter position between 1 to %d: ");
scanf("%d", &position);
}
else
position = temp_position;
{
/*
* Inserts element in array and increases the size of the array
*/
for(i=size; i>=position; i--)
{
arr[i] = arr[i-1];
}
arr[position-1] = num;
size++;
/*
* Prints the new array after insert operation
*/
printf("Array elements after insertion : ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
}
return 0;
}