58.1k views
2 votes
-Write a function is_perfect, which accepts a single integer as input. If the input is not positive, the function should return a string "Invalid input." If the input is positive, the function should return True if the input is a perfect number and False otherwise.

1 Answer

3 votes

Answer:

// here is code in C++.

#include <bits/stdc++.h>

using namespace std;

// function

string is_perfect(int n)

{

// string variables

string str;

// if number is negative

if (n < 0)

{

str="invalid input.";

}

// if number is positive

else

{

int a=sqrt(n);

// if number is perfect square

if((a*a)==n)

{

str="True";

}

// if number is not perfect square

else

{

str="False";

}

}

// return the string

return str;

}

// main function

int main()

{

// variables

int n;

cout<<"enter the number:";

// read the value of n

cin>>n;

// call the function

string value=is_perfect(n);

// print the result

cout<<value<<endl;

return 0;

}

Step-by-step explanation:

Read a number from user and assign it to variable "n".Then call the function is_perfect() with parameter n.First check whether number is negative or not. If number is negative then return a string "invalid input".If number is positive and perfect square then return a string "True" else return a string "False".

Output:

enter the number:-3

invalid input.

enter the number:5

False

enter the number:16

True

User Cpg
by
4.8k points