[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
Solved

# for loop alphabet pattern

Posted on 2007-08-05
Medium Priority
2,186 Views
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.";
}
0
Question by:dandeliondream
• 7
• 4
• 3
• +1

LVL 53

Assisted Solution

Infinity08 earned 600 total points
ID: 19633597
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

LVL 29

Expert Comment

ID: 19633760
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

LVL 3

Author Comment

ID: 19671128
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

LVL 29

Accepted Solution

pepr earned 900 total points
ID: 19673925
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:

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

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

LVL 3

Author Comment

ID: 19675622
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;
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

LVL 29

Expert Comment

ID: 19681830
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, ' ');

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

LVL 29

Expert Comment

ID: 19681846
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

LVL 29

Expert Comment

ID: 19681983
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

LVL 29

Expert Comment

ID: 19682007
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

LVL 3

Author Comment

ID: 19861567
Is there any c++ book touching on this...i hope to borrow it to study....thanks
0

LVL 53

Expert Comment

ID: 19861640
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

LVL 18

Expert Comment

ID: 19861973
0

LVL 3

Author Comment

ID: 19865588
no, i still dunno how.
0

LVL 29

Expert Comment

ID: 19866524
Then pick a single thing that you do not understand and formulate a question...
0

LVL 53

Expert Comment

ID: 19866596
What do you already have ? Where are you stuck ? What questions/problems do you have ?

0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there isâ€¦
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why tâ€¦
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor anâ€¦
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relatâ€¦
###### Suggested Courses
Course of the Month18 days, 6 hours left to enroll