For Programmers: Free Programming Magazines  


Home > Archive > C > February 2006 > Printing Patterns using for loops









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Printing Patterns using for loops
priyam.trivedi@gmail.com

2006-02-28, 6:55 pm

I saw this in one article but I cannot understand why the coder has
used z--. I did it without z-- and it still works the same.

Please help.

Priyam


Trying to print the following pattern but...

$$$$$
$$$$5
$$$55
$$555
$5555



The Code
----------

void PrintPatternThree (int PatternSize)
{
int Row = 0;
int Col = 0;
int Temp = 0; // used to hold the new value of PatternSize for
evaluating

Temp = PatternSize;

for (Row = 1; Row <= PatternSize; Row++)
{
for (Col = 1; Col <=PatternSize; Col++)
{
if (Row <= Col)
printf ( "$" );
else
printf ( "%d", PatternSize);
} // end Col
Temp--;
printf ( "\n" );
} // end Row

return;

} /* end PrintPatternFour()

$$$$$
$$$$5
$$$55
$$555
$5555 */

Vladimir S. Oka

2006-02-28, 6:55 pm


priyam.trivedi@gmail.com wrote:
> I saw this in one article but I cannot understand why the coder has
> used z--. I did it without z-- and it still works the same.


There's no `z--` in the code you posted, but I think I still get what
you mean (Temp--).

<snip... the pattern>

> void PrintPatternThree (int PatternSize)
> {
> int Row = 0;
> int Col = 0;
> int Temp = 0; // used to hold the new value of PatternSize for
> evaluating


These initialisations are superflous and hence confusing, as you
immediatelly re-initialise these variables with different values.

> Temp = PatternSize;


This actually does not get used at all (apart from decrementing it).

> for (Row = 1; Row <= PatternSize; Row++)
> {
> for (Col = 1; Col <=PatternSize; Col++)
> {
> if (Row <= Col)
> printf ( "$" );
> else
> printf ( "%d", PatternSize);
> } // end Col
> Temp--;
> printf ( "\n" );
> } // end Row


Don't use `//` for comments, at least in newsgroups, as it may foul the
quoting.

> return;
>
> } /* end PrintPatternFour()
>
> $$$$$
> $$$$5
> $$$55
> $$555
> $5555 */


I guess `Temp` is a leftover from a different way of implementing this.
E.g. `Temp` could be used instead of `Row` in a `while` loop.

int Temp = PatternSize;

while (Temp)
{
/* do stuff with Col; use Temp instead of Row (not a straight
replacement!) */;
--Temp;
}

OTH, you could also use PatternSize. C passes arguments by value, so
you wouldn't mess whatever is passed in the function call.

--
BR, Vladimir

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com