by Dinesh Thakur Category: Control Structures

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.

#include <stdio.h>

void main()

{    

       float num; 

       clrscr();

       do

        {

                 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));

                        getch();

}

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



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article