Home / Programs / Square Root of Prime Number using Command Line Argument
🚀 Programming Example

Square Root of Prime Number using Command Line Argument

👁 881 Views
💻 Practical Program
📘 Step Learning

The square root of a Prime number by checking first if it is a prime number?

Write a C program which will check whether a given number N is a Prime or Not. If the Number N is a Prime, then find it’s square root and print that value to the STDOUT as floating point number with exactly 2 decimal precision. If the number is not Prime, then print the value 0.00 to STDOUT. The given number will be positive non zero integer and it will be passed to the program as first command line argument. Other than floating point No other information should be printed to STDOUT.

💻 Program Code

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>
bool isPrime(int n)
{
    if(n<2)
    return false;
    
    int i;
    for(i=2;i*i<=n;i++)
    {
        if(n%i==0)
        return false;
    }
    return true;
}


int main(int argc, char *argv[])
{
    if(argc==1)
    {
        printf("No arguments");
        return 0;
    }
    else
    {
        int n;
        n=atoi(argv[1]);
        float sq=0;
        
        if(isPrime(n))
        {
            sq=sqrt(n);
            printf("%.2f",sq);
        }
        else
        printf("%.2f",sq);

    return 0;
    }
}
                        

🖥 Program Output

13

3.16
                            

📘 Explanation

Nope
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.