Making a number absolute using If – Computer Sir Ki Class


Code Learning #CPP#1861 siteicon   siteicon   siteicon  

Making a number absolute using If

A number is made absolute by removing its negative sign if present.

Learning Objectives

  • Learning to save original values if selection constructs are likely to change the values given by the user.

Source Code

TC++ #1861

int main()
int n;
cout<<"Enter a negative or positive integer:";
int on=n;
if(n < 0) n=- n;
cout<<"The absolute value of "
< getch();
return 0;

Source Code


Test it !

Run Output

Enter a negative or positive integer:-95
The absolute value of -95 is 95

Enter a negative or positive integer:34
The absolute value of 34 is 34

Code Understanding

int n; cout<<“Enter a negative or positive integer:”; cin>>n;
Here we collect a positive or negative integer from the user to make it absolute (which means that the negative sign if present would be removed).

int on=n;
Here we reserve the number given by user in the variable n to another variable on so that the original number given can be printed later.

if(n < 0) n=- n;
Here we remove the sign by negating the negative number. For e.g. if the number is -3 , it would be negated as -(-3) which means 3. A negative number is tested by checking its value to be less than 0.

cout<<“The absolute value of ” <<on<<” is “<<n;
Here we print the original number and the new number. If the original number is already positive, then nothing will happen to the number and it will be printed as it is.


  • The approach of reserving or saving the original value is frequently used before selection or iteration or loops when they act on the given number for making deductions or changes. This we shall see in the topic of “Tricks for Loops”.
  • A programmer has a choice that subsequent code of selection or loops works on the original number or the saved number itself.

Suggested Filename(s): makeabsolute.cpp


sunmitra| Created: 22-Dec-2017 | Updated: 15-Sep-2018|