Wednesday 15 December 2010

ASCII Print

Few weeks back, someone I know got asked the following question in an interview:

Write a C++ program in 15 minutes to print the following in the output:
a
bcb
cdedc
defgfed
efghihgfe
fghijkjihgf
ghijklmlkjihg
hijklmnonmlkjih
ijklmnopqponmlkji
jklmnopqrsrqponmlkj
klmnopqrstutsrqponmlk
lmnopqrstuvwvutsrqponml
mnopqrstuvwxyxwvutsrqponm
nopqrstuvwxyz{zyxwvutsrqpon

You can do search on the web for any information but all your searches would be logged and used to assess your answer.

Well my obvious guess would be to take help of ASCII table. My only search was for Ascii table in google. I did try and make it in less than 15 mins. My solution is below but do try it on your own before looking at my solution.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

int
main()
{

char
c=(char)97; //'a' in ASCII
char loop = 0;
while
(c <= 'n')
{

char
x = 0;
for
(; x <=loop; x++)
{

cout<<char(c+x);
}

for
(char y = 1; y < x; y++)
{

cout<<char(c+x-y-1);
}

cout<<endl;
c++;
loop++;
}


return
0;
}



1 comment:

  1. #include
    using namespace std;
    int main(void){
    int len=1;

    for (char a = 'a' ; a <= 'n' ; a++ ){
    char b = a;
    for (int i = 1 ; i <= len ; i++ ){
    cout << b ;
    (i <= (len/2)) ? b++ : b--;
    }
    cout<<endl;
    len+=2;
    }
    return 0;
    }

    ReplyDelete