10. Display Numbers with Sign

Easy ⏱️ 3 min

Problem Statement

Accept an integer and print the number along with its sign.

Input Format

Accept an integer as a input

Output Format

Print the number along with its sign.

Constraints

10^-15 <= N <= 10^15

Examples

Sample Input 1
-15
Sample Output 1
-15
Sample Input 2
8
Sample Output 2
+8

💡 Learning Guide

Key Concept: This problem introduces showpos, a stream manipulator that automatically displays a + sign for positive numbers without using any conditionals.
📚 What is showpos?

showpos is a stream manipulator in C++.

  • It comes from the <iostream> header
  • Its purpose: force positive numbers to display a + sign when printed
  • Works with all standard output streams: cout, cerr, clog, or any ostream

Example:

#include <iostream>
using namespace std;

int main() {
    int a = 5;
    int b = -3;
    
    cout << showpos;   // Enable + for positive numbers
    cout << a << " " << b << endl;  // Output: +5 -3
}
🔄 Normal vs showpos Behavior

Without showpos (normal behavior):

int x = 10;
int y = -7;

cout << x << " " << y << endl;

// Output: 10 -7

Notice positive numbers don't get a + by default.

With showpos:

cout << showpos;
cout << x << " " << y << endl;

// Output: +10 -7

✅ Automatically prints + for positive numbers and - for negatives.

⚙️ Syntax & Usage Patterns

A. Permanent for the stream

Once you do cout << showpos;, all subsequent numbers in that stream will have the + for positives, until you reset it.

cout << showpos;
cout << 3 << endl;   // +3
cout << -4 << endl;  // -4
cout << 0 << endl;   // +0

B. Temporary for a single print

You can combine it in a single cout statement:

cout << showpos << 7 << endl;  // +7

C. Disabling showpos

If you later want to stop showing + for positives:

cout << noshowpos;
cout << 5 << endl;  // 5

So showpos / noshowpos are like on/off switches for the stream.

🚫 Why It Doesn't Use Conditionals

showpos is purely formatting – the stream handles printing internally.

Your code doesn't need if (n >= 0) to add a +.

Therefore: This is perfect for questions that explicitly forbid conditions!

No conditionals needed:
  • No if statements
  • No ternary operators ? :
  • The stream decides automatically based on the number's sign
✅ Key Points to Remember:
  • Default behavior: positives have no +, negatives have -
  • showpos → adds + automatically for positives
  • noshowpos → disables it again
  • Works with integers and floating-point numbers
  • Does not use any conditionals — stream decides internally
  • Can combine with other formatting manipulators (setw, setfill, etc.)

✅ Solution

#include <iostream>
using namespace std;

int main() {
    int a;
    cin >> a;
    cout << showpos << a;
    return 0;
}