Block of Code

Practical Examples for Programmers

  • Home
  • C++
  • Java
  • Visual Basic
  • Discrete Math
  • Ask a Question

Four Digits

Using C++, write a program that prompts the user to input a four-digit positive integer. The program then outputs the digits of the number, one digit per line. For example, if the input it 3245, the output is:

3
2
4
5

Hint:  

Use the modulus operator to separate the digits.

Write the Code:

/*
Project: Four Digits
Description: User is prompted to enter a four-digit number.
Each digit is printed on an individual line.
*/

#include <iostream>
using namespace std;

int main()
{
    int number, ones, tens, hundreds, thousands = 0;
    cout << "Please enter a four digit number:";
    cin >> number;
    cout << endl;
    thousands = number % 10000 / 1000;
    cout << thousands << endl;
    hundreds = number % 1000 / 100;
    cout << hundreds << endl;
    tens = number % 100 / 10;
    cout << tens << endl;
    ones = number % 10;
    cout << ones << endl;
    return 0;
}

Secondary Sidebar

This is the secondary sidebar

Copyright © 2025 · Metro Pro Theme on Genesis Framework · WordPress · Log in