cpp absolute value
#include <iostream>
using namespace std;
int absolute(int num) {
if (num < 0) {
return -num;
} else {
return num;
}
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
int result = absolute(number);
cout << "The absolute value of " << number << " is " << result << endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream library to perform input and output operations.using namespace std;
: Enables the use of names for objects and variables in the standard C++ library.int absolute(int num) { ... }
: Defines a function namedabsolute
that takes an integernum
as a parameter and returns an integer. Inside the function:if (num < 0) { return -num; }
: Checks if the input number is less than zero. If true, returns the negation of the number, making it positive.else { return num; }
: If the number is greater than or equal to zero, it returns the number itself.int main() { ... }
: Defines the main function where the program execution starts.int number;
: Declares an integer variable namednumber
.cout << "Enter a number: ";
: Displays the message to prompt the user to enter a number.cin >> number;
: Takes user input and stores it in thenumber
variable.int result = absolute(number);
: Calls theabsolute
function with the entered number and stores the returned absolute value in theresult
variable.cout << "The absolute value of " << number << " is " << result << endl;
: Displays the original number entered by the user along with its absolute value.return 0;
: Indicates successful completion of the main function. ```