Functions 


Contents of this section:

  1. A Simple program finding the absolute value of an integer (without using function)
  2. A Simple program finding the absolute value of an integer (using a function)

1. A Simple program without using functions

    Code Listing: 

//
// File name: ~ftp/pub/class/cplusplus/Functions/Absolute1.cpp
// Purpose:   This program find the absolute value of an integer
//	      without using a function
//

#include <iostream>
using namespace std;

int main()
{
	int number;
	int abs_number;

	// Ask for input
	cout << "This program finds the absolute value of an integer." << endl;
	cout << "Enter an integer (positive or negative): ";
	cin >> number;
	
	// Find the absolute value
	if(number >= 0)
	{
		abs_number = number;
	}
	else
		abs_number = -number;
	
	// Print out output
	cout << "The absolute value of " << number << " is " << abs_number;
	cout << endl;
	return 0;
}

    Running session:

mercury[50]% CC -LANG:std Absolute1.cpp -o Absolute1
mercury[51]% Absolute1
This program finds the absolute value of an integer.
Enter an integer (positive or negative): -45
The absolute value of -45 is 45
mercury[52]% Absolute1
This program finds the absolute value of an integer.
Enter an integer (positive or negative): 0
The absolute value of 0 is 0
mercury[53]% Absolute1
This program finds the absolute value of an integer.
Enter an integer (positive or negative): 9
The absolute value of 9 is 9
mercury[54]% 

2. The same program using function

Code listing:

//
// File name: ~ftp/pub/class/cplusplus/Functions/Absolute2.cpp
// Purpose:   This program finds the absolute value of an integer
//	      using a function
//

int Abs(int i); // Function prototype
int main()
{
	int number;
	int abs_number;

	cout << "This program finds the absolute value of an integer." << endl;
	cout << "Enter an integer (positive or negative): ";
	cin >> number;
	
	// Calling the function Abs()
	abs_number = Abs(number);
	cout << "The absolute value of " << number << " is " << abs_number;
	cout << endl;
	return 0;
}
// Function definition
int Abs(int i)
{
	if( i >= 0)
		return i;
	else
		return -i;
}

Running session:

mercury[56]% CC -LANG:std Absolute2.cpp -o Absolute2
mercury[57]% Absolute2
This program finds the absolute value of an integer.
Enter an integer (positive or negative): -45
The absolute value of -45 is 45
mercury[58]% Absolute2
This program finds the absolute value of an integer.
Enter an integer (positive or negative): 0
The absolute value of 0 is 0
mercury[59]% Absolute2
This program finds the absolute value of an integer.
Enter an integer (positive or negative): -9
The absolute value of -9 is 9
mercury[60]% 


Last modified: Friday, 21-Aug-2020 15:28:15 CST
Copyright 2000 Department of Computer Science, University of Regina.

 CS Dept Home Page

Teaching Material

C++ Index Page