SoFunction
Updated on 2025-03-09

C++ implements printing 1 to maximum n-digit number

This article describes the method of C++ to print 1 to the maximum n-digit number in an example form. Share it for your reference. The specific methods are as follows:

Question Requirements:

Enter the number n and print out the largest n-digit decimal number from 1 in order. For example, enter 3, print out 1, 2, 3 and the largest 3-digit number 999

The implementation code is as follows:

#include <iostream>

using namespace std;

void printArray(char *array, int size)
{
 if (array == NULL || size <= 0)
 {
 return;
 }

 int index = 0;
 while (array[index] == '0')
 index++;

 for (int i = index; i != size; i++)
 printf("%c", array[i]);

 cout << endl;
}

void printNumbers(int n)
{
 if (n <= 0)
 {
 return;
 }

 char *array = new char[n + 1];
 if (array == NULL)
 {
 throw("allocate memory error");
 return;
 }

 memset(array, '0', n);
 array[n] = 0;

 while (true)
 {
 int takeOver = 0;
 for (int i = n - 1; i >= 0; i--)
 {
  int num = array[i] - '0';
  if (i == n - 1)
  {
  num++;
  }
  else
  {
  num += takeOver;
  takeOver = 0;
  }

  if (num == 10)
  {
  if (i == 0)
   goto here;
  array[i] = '0';
  takeOver = 1;
  }
  else
  {
  array[i] = num + '0';
  break;
  }
 }

 printArray(array, n);
 }

here:
 delete []array;
}

void main()
{
 int n = 3;
 printNumbers(n);
}

Be sure to pay attention to the use of break here
array[i] = num + '0';
break;
Due to the existence of this break, takeOver does not need to be reset to 0
That is to say

while (true)
{
 int takeOver = 0;
 for (int i = n - 1; i >= 0; i--)
 {
 int num = array[i] - '0';
 if (i == n - 1)
 {
  num++;
 }
 else
 {
  num += takeOver;
  //takeOver = 0;
 }

 if (num == 10)
 {
  if (i == 0)
  goto here;
  array[i] = '0';
  takeOver = 1;
 }
 else
 {
  array[i] = num + '0';
  break;
 }
 }

 printArray(array, n);
}

I hope that this article will be helpful to everyone's learning of C++ program algorithm design.