Deitel C++ How To Program 9th Edition Chapter 2 Exercise 2.28

12 Jul 2024 - Syed Muhammad Shahrukh Hussain

Write a program which inputs 5 digit integer and separate the integer and print them with three spaces difference.

Terminal

Enter number:45768
Enter number size(no of digits):5
4   5   7   6   8

Solution

#include <iostream>
#include <cmath>

void split_integer(int num, int size) {
  long divisor = pow (10, size - 1);
  while (num > 0) {
    std::cout << num/ divisor << "   ";
    num %= divisor;
    divisor /= 10;
  }
  std::cout << std::endl;
}

int main() {
  int num = 0;
  int size = 0;
  std::cout << "Enter number:";
  std::cin >> num;
  std::cout << "Enter number size(no of digits):";
  std::cin >> size;
  split_integer(num, size);
  return 0;
}

Sources