Object

Write a program to read a number and display its absolute value.

Algorithm

  1. Declare integer variable n.
  2. Read n.
  3. IF (n < 0), then
    • n = -n.
    • Write n.
    • ELSE
      • Write n.
    • [End of IF-ELSE structure.]
  4. Exit.

Flowchart

 C++ Source Code

// program 16
#include<iostream>
using namespace std;

int main()
{
  int n;
  cout << "Enter a number (negative or positive): ";
  cin >> n;

  if (n < 0)
  {
    n = -n;
    cout << "The absolute value of number is " << n << ".";
  }
  else
  {
    cout << "The absolute value of number is " << n << ".";
  }
  return 0;
}

 C Source Code

/*program 16*/
#include<stdio.h>

int main()
{
  int n;
  printf("Enter a number (negative or positive): ");
  scanf("%d", &n);
  if (n<0)
     {
     n = n * -1;
     printf("The absolute value of number is %d.", n);
     }
  else
     printf("The absolute value of number is %d.", n);
  return 0;
}

Output

Enter a number (negative or positive): -6
The absolute value of number is 6.

Design a site like this with WordPress.com
Get started