The program segment given below reads a number from the keyboard (in variable num of type float) and prints its square root. However, as the sqrt function requires a non-negative argument, the program uses a do ..while loop to read the data until valid data is entered.
printf(“Enter a non-negative number: “);
scanf (“%f”, &num);
if (num < 0)
printf(“Error: Invalid data.\n”);
} while (num < 0);
printf(“Number: %f Square root: %f \n”, num, sqrt(num));
The program containing this code is executed and the sample output is shown below.
Enter a non-negative number: -9
Error: Invalid data.
Enter a non-negative number: 9
Number: 9.000000 Square root: 3.000000