C++ to print 1 to the largest number of n digits

  • 2020-04-02 02:47:29
  • OfStack

This article presents an example of how C++ can print from 1 to the largest number of n digits. Share with you for your reference. Specific methods are as follows:

Title requirements:

Enter the number n and print out the largest n-digit decimal number from 1 in sequence, such as 3, and print out 1,2,3, all the way to 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;
Because of this break, takeOver does not have 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);
}

Hope that this article is helpful to the learning of C++ programming algorithm design.


Related articles: