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:

  1. #include <iostream>: Includes the input/output stream library to perform input and output operations.
  2. using namespace std;: Enables the use of names for objects and variables in the standard C++ library.
  3. int absolute(int num) { ... }: Defines a function named absolute that takes an integer num as a parameter and returns an integer. Inside the function:
  4. 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.
  5. else { return num; }: If the number is greater than or equal to zero, it returns the number itself.
  6. int main() { ... }: Defines the main function where the program execution starts.
  7. int number;: Declares an integer variable named number.
  8. cout << "Enter a number: ";: Displays the message to prompt the user to enter a number.
  9. cin >> number;: Takes user input and stores it in the number variable.
  10. int result = absolute(number);: Calls the absolute function with the entered number and stores the returned absolute value in the result variable.
  11. cout << "The absolute value of " << number << " is " << result << endl;: Displays the original number entered by the user along with its absolute value.
  12. return 0;: Indicates successful completion of the main function. ```