Number Pyramid

This is some trivial question people ask on Yahoo! Answers all the time when it comes to programming. They want to know how to enter a number (let’s say 7) and loop and display the number in a pyramid like this:

1
22
333
4444
55555
666666
7777777
666666
55555
4444
333
22
1


Well I’m going to post some code for doing that in 3 languages.
Batch:

@echo off
:start
cls
set /p num=Enter a number between 1 ^& 10:
if not defined num exit
setlocal enabledelayedexpansion
for /l %%i in (1,1,%num%) do (
   set ii=%%i
   for /l %%j in (1,1,!ii!) do (
      set str=!str!!ii!
   )
   echo !str!
   set str=
)
set /a num-=1
for /l %%i in (%num%,-1,1) do (
   set ii=%%i
   for /l %%j in (1,1,!ii!) do (
      set str=!str!!ii!
   )
   echo !str!
   set str=
)
echo.
pause
goto start


VBScript:

do
x=inputbox("Enter a number between 1 & 10:","Type 'stop' to quit")
if x="stop" then wscript.quit
str=""
dim i, j
for i=1 to x
   for j=1 to i
      str=str&i
   next
   str=str&vbcrlf
next
for i=(x-1) to 1 step -1
   for j=1 to i
      str=str&i
   next
   str=str&vbcrlf
next
msgbox(str)
loop


C

#include <cstdio>
#include <cstdlib>
#include <cstring>

int main() {
while (true) {
   int x;
   int i,j;
   char str[256]="";
   char num[3];
   printf("Enter a number between 1 & 10: ");
   scanf("%d",&x);
   if (x==0) { return 0; }
   for (i=1;i<=x;i++) {
      for (j=1;j<=i;j++) {
         itoa(i,num,10);
         strcat(str,num);
      }
   strcat(str,"\n");
   }
   for (i=(x-1);i>=1;i--) {
      for (j=1;j<=i;j++) {
      itoa(i,num,10);
      strcat(str,num);
   }
   strcat(str,"\n");
   }
   printf("%s",str);
   system("echo.&pause");
   system("cls");
}
return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: