Home > front end >  Full pyramid from 5 digit int
Full pyramid from 5 digit int

Time:10-13

i'm having trouble with my C homework..

I need an algorithm that can turn an 5 (x4, x3, x2, x1, x0) digit number, into a pyramid like that:

   x2 
 x3x2x1
x4x3x2x1x0

Ex. => 12345

  3
 234
12345

How can I do that? Do I have to take each number individually and display them in order?

Edit* I did it, and the code looks like (for anyone that might have the same problem):

int num; 
  string str; 

  cout << "Type a 5-digit number: ";
  cin >> num;


  stringstream ss;  
  ss << num;  
  ss >> str;  

  char x0 = str[4];
  char x1 = str[3];
  char x2 = str[2];
  char x3 = str[1];
  char x4 = str[0];

  
  cout << "  " << x2 << endl;
  cout << " " << x3 << x2 << x1 << endl;
  cout << x4 << x3 << x2 << x1 << x0;

CodePudding user response:

Yes, you’d have to process the digits individually.

Generally I’d expect students to try and tackle it in following ways:

  1. Convert the number to a string, then index individual characters on that string and display them. There are multiple ways of doing the integer-to-string conversion. The simplest may be to use an std::ostringstream, say (std::ostringstream() << 1234).str().

  2. Use arithmetic to extract each digit of the string, and convert the digit to a character as it’s passed to a print function. By converting a digit to a character I mean 5 -> '5'. Incidentally, this conversion is as simple as adding '0' to the digit. So, 5 '0' == '5'. The '0' is a number, since in the C family of languages, characters are just small numbers.

There may be many approaches to formatting the pyramid, but since the assignment doesn’t require any flexibility, the simplest way would be the best: add necessary spaces by hand.

  •  Tags:  
  • c
  • Related