for loop alphabet pattern

Hi this is a homewok...I can't figure out how to do. Write a program to accept a number and produce the following pattern. Enter only even number.

Line = 8
ABCDDCBA
BCD     DCB
CD         DC
D             D
D             D
CD         DC
BCD    DCB
ABCDDCBA

Below is what i have done.
#include <iostream>
using namespace std;

int main()
{

  int num, i, j, k;
  cout << "Line = ";
  cin >> num;
 
  if (num%2 ==0)
   for (i=0; i < num; i++)
   {
     for (j=0; j < num/2; j++)
        cout <<(char)(65+j);
      //cout << endl;
      //for (k=j; k < num ;k++)
      for (k=num/2-1; k >= 0 ;k--)
        cout <<(char)(65+k);
      cout <<endl;
    }
  else
    cout << "Please enter even number.";
}
LVL 3
dandeliondreamAsked:
Who is Participating?
 
peprCommented:
Some notes for improvements. When you #include <string> then one of the string constructors allows you to define a string of n given characters, like:

    string padding(5, 'a');

It defines the string named padding with the value "aaaaa". At least two of your most inner for loops could be replaced by

    cout << padding << padding;

when thinking in outputint mirrored halves of the line or you can simply produce one padding of the doubled length. See http://www.cppreference.com/cppstring/string_constructors.html for details.

You can also think about solving the problem as mirroring of this part (padded by spaces):

ABCD
BCD  
CD    
D      

The basic line "ABCD" can be generated for 8 into one string variable. Then you can create a copy into second variable and make it reversed using the standard algorithm -- see http://www.cppreference.com/cppalgorithm/reverse.html

The half-line for the next line can be generated from the previous by cutting the first character and appending the space. See:
    http://www.cppreference.com/cppstring/substr.html
    http://www.cppreference.com/cppstring/append.html
         or operator+ http://www.cppreference.com/cppstring/string_operators.html
         or push_back for string http://www.cppreference.com/cppstring/push_back.html 
             (I've probably ever tried this)
Then you can reverse it again for getting the right part of the line.

You can mirror the upper part of the picture by always outputing the line and pushing it also to the stack http://www.cppreference.com/cppstack/push.html. After outputing the upper part of the picture, you can pop all lines from the stack (the order is reversed) and output them. See http://www.cppreference.com/cppstack/empty.html, http://www.cppreference.com/cppstack/top.html and http://www.cppreference.com/cppstack/pop.html.
0
 
Infinity08Commented:
The easiest way to do this is to split the outer loop in half - ie. the first loop draws the upper half, and the second loop the lower half.

Then, inside of each of these loops, you also put two loops, for the left and right halfs respectively. So, in total, you have 4 areas to code. Note that the pattern is symmetric, so once you have one of the four, the others are easy.

Give it a shot with this hint, and post your new code here, and we'll be glad to help you further if needed.

Note that you don't have a return 0; at the end of the main. You need to have that line, since main has an int as return value.
0
 
peprCommented:
To add... In cases like that, I recommended to students thinking in terms "How would you do it manually, without computer, by hand, pencil and paper." It usually helped them to understand what they want to solve and what are the key points of the problem. Then you identify the things that could be generalized -- like how tho solve the problem by hand when you choose a different number, what is the same.

Then, as Infinity08 suggested, try the simplest solution first and be happy when it works. Firstly, you have the solution to present; secondly, you will become more confident; thirdly, you can then rewrite the parts to make it better (say, more general, more robust, more clever, nicer to please the eye). This is called refactorization ;-)
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
dandeliondreamAuthor Commented:
this is what i have done so far...pls help

#include <iostream>
using namespace std;

int main()
{

  int num, i, j;
  cout << "Line = ";
  cin >> num;
 
  if (num%2 == 0)
   for (i=0; i < num/2; ++i)//outer loop1
   {
     for (j=i; j < num/2; ++j) cout <<(char)(65+j);
       for (j=0; j <=i-1; ++j) cout << " ";
      
       for (j=0; j <=i-1; ++j) cout << " ";
       for (j=i; j < num/2; ++j) cout <<(char)(65+j);
      
    cout <<endl;
    }
  else
    cout << "Please enter even number.";
      
      return 0;
}
0
 
dandeliondreamAuthor Commented:
sorry pepr i don;t understand your answer...this is what i have so far.. what is the easier way to get the lower portion of the loop
D              D
CD          DC
BCD     DCB
ABCDDCBA

#include <iostream>
//#include <string>
using namespace std;

int main()
{

  int num, i, j;
  char lastAlphabet;
  //string padding(5, ' ');
  cout << "Line = ";
  cin >> num;
 
  if (num%2 == 0)
  {
         for (i=0; i < num/2; ++i)//outer loop1
         {
           for (j=i; j < num/2; ++j) cout <<(char)(65+j);
                   if (j = num/2) lastAlphabet = (char)(65+j);
      
             for (j=0; j <=i-1; ++j) cout << " ";
            
             for (j=0; j <=i-1; ++j) cout << " ";
             for (j=0; j < num/2-i; ++j) cout << static_cast<char>(lastAlphabet-j-1);
      
                cout <<endl;
          }
      
         for (i=0; i < num/2; ++i)//outer loop1
         {
           for (j=i; j < num/2; ++j) cout <<(char)(65+j);
                   if (j = num/2) lastAlphabet = (char)(65+j);
      
             for (j=0; j <=i-1; ++j) cout << " ";
            
             for (j=0; j <=i-1; ++j) cout << " ";
             for (j=0; j < num/2-i; ++j) cout << static_cast<char>(lastAlphabet-j-1);
      
           cout <<endl;
          }
      }
  else
    cout << "Please enter even number.";
      
      return 0;
}

0
 
peprCommented:
The first part says that you can replace your two loops

for (j=0; j <=i-1; ++j) cout << " ";
for (j=0; j <=i-1; ++j) cout << " ";

by

string padding(i * 2, ' ');
cout << padding;

or by even shorter command

cout << string(i * 2, ' ');

By the way, It is also more usual to write the loops in C this way (testing for the end of loop):

for (j=0; j < i; ++j) cout << " ";

Another simplification, you have a lot of num/2 expressions in your code. It is a bit more readable and probably also more efficient to assign the result to a local variable and use that (see the cnt below).

In C++, you should always prefer static_cast<some_type>(expression). The older C form (some_type)(expression) is somehow more dangerous. Anyway, you do not need any type conversion in the code because you can simply assign an int number to the char variable (automatic conversion).

In C++, you should define a variable as close to the place where it is to be uses as possible. If the compiler is not too old, you should even define the loop variable inside the for construct.

As a beginner, you should keep perfect indentation of the source code just not to be lost in what is done. Place a body (indented) BELOW -- the for and if constructions.

As it is a homework, I am not going to give you the full solultion. Just study the first part:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int num;
    cout << "Line = ";
    cin >> num;
 
    if (num%2 == 0)
    {
        int cnt = num / 2;
        const char A = 65;
        char maxChar = A + cnt -1;

        for (int i = 0; i < cnt; ++i)            // outer loop1
        {
            char c = A;
            for (int j = i; j < cnt; ++j)
                cout << c++;

            cout << string(2 * i, ' ');

            c = maxChar;
            for (int j=0; j < cnt-i; ++j)
                cout << c--;
     
            cout << endl;
        }
... etc

Basically, the second big loop will have exactly the same body (the fact that should always tell you that some code should be centralised, i.e. written only once, on one place). The only difference is that the index of lines should go from cnt-1 to zero.

Please, do study the above code so that you understand perfectly what is done. After having the solution, we can return back to the second suggestion -- using reverse and stack for mirroring the quarter of the ASCII image.
0
 
peprCommented:
The

    char maxChar = A + cnt -1;

should also be

    const char maxChar = A + cnt -1;

(Not necessary, but better when writing more robust code. Compiler will warn you if you forget that the maxChar is a constant in that block of  your code.)
0
 
peprCommented:
I made a mistake in the body of the loop. The line

            char c = A;

must be replaced by the line

            char c = A + i;
0
 
peprCommented:
It is also more readable and understandable to define

char c = 'A' + i;

and to use 'A' instead of the variable A and omit the  const char A = 65; completely
0
 
dandeliondreamAuthor Commented:
Is there any c++ book touching on this...i hope to borrow it to study....thanks
0
 
Infinity08Commented:
A good C++ book is :

    "The C++ Programming Language" < Bjarne Stroustrup (third edition)

And you can find a free (also good) book on C++ here :

    "Thinking in C++" < Bruce Eckel :
        http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html

You can also consider checking out this (basic) tutorial on C++ :

        http://www.cplusplus.com/doc/tutorial/
0
 
Jinesh KamdarCommented:
Were you able to complete your homework task based pepr's suggestions?
0
 
dandeliondreamAuthor Commented:
no, i still dunno how.
0
 
peprCommented:
Then pick a single thing that you do not understand and formulate a question...
0
 
Infinity08Commented:
What do you already have ? Where are you stuck ? What questions/problems do you have ?

We're here to help you ... :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.