Program Discussion :: Basics
310 / 279
Write a C program which will check whether a given number N is prime or not.
If the number N is prime, then find its square root and print that value to stdout as floating point number with exactly 2 decimal precision.
If the given number N is not prime, then print the value 0.00 to stdout.
The given number N will be a positive non Zero integer and it will be passed to the program using the first command line parameter. Other than the floating point result, no other information should be printed to stdout.
Answer:
#include
#include
#include
int main(int argc, char * argv[])
{
int n, i, flag = 0;
double x;
if (argc == 1 || argc > 2)
{
printf("Enter String \r\n");
exit(0);
}
n = atoi(argv[1]);
x = n;
for(i=2; i
Asked In ::
Language:
Sumit
27 Oct, 2017 12:42 AM
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
int n, i, flag = 0;
double x;
if (argc == 1 || argc > 2)
{
printf("Enter String \r\n");
exit(0);
}
n = atoi(argv[1]);
x = n;
for(i=2; i<= n/2; ++i)
{
if(n%i == 0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%.2lf \r\n", sqrt (x) );
else
printf("%.2lf \r\n",0.00);
return 0;
}
Language:
Amit
28 Jan, 2018 7:40 PM
#include <stdio.h> // for printf
#include <stdlib.h> // for function atoi() for converting string into int
// Function to return fact value of n
int fact(int n)
{
if (n == 0)
return 1;
else {
int ans = 1;
int i;
for (i = 1; i <= n; i ) {
ans = ans * i;
}
return ans;
}
}
// argc tells the number of arguments
// provided 1 1 for file.exe
// char *argv[] is used to store the
// command line arguments in the string format
int main(int argc, char* argv[])
{
// means only one argument exist that is file.exe
if (argc == 1) {
printf("No command line argument exist Please provide them first \n");
return 0;
} else {
int i, n, ans;
// actual arguments starts from index 1 to (argc-1)
for (i = 1; i < argc; i ) {
// function of stdlib.h to convert string
// into int using atoi() function
n = atoi(argv[i]);
// since we got the value of n as usual of
// input now perform operations
// on number which you have required
// get ans from function
ans = fact(n);
// print answer using stdio.h library's printf() function
printf("%d\n", ans);
}
return 0;
}
}
Language:
Singh
29 Jan, 2018 12:11 AM
#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;
}
}