Test your technical skills online, appear in Virtual Interview and be ready for job!
Twitter Twitter LinkedIn YouTube Google
Be Interview ready ! | Search
Make friends on DotNetFunda.com and expand your network!
Winners

Win Prizes

Announcements
Like us on Facebook
Sponsor
Top Articles Author
Sun, 20-Apr-2014 Authors
All Time Authors
Sourav.Kayal
39750
SheoNarayan
34800
Niladri.biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads

Getting different shapes of stars using For Loops

Nagasundar_Tn
Posted by under C# category on for Beginner level | Points: 250 | Views : 35020 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 5 out of 5
3 vote(s)


I am using two for loops to print stars in differnt shapes.

 Download source code for Getting different shapes of stars using For Loops


Introduction


I noticed some one has asked the question about printing collection of stars in rectangle shape. Here I submitted code snippets with description that prints stars in different shapes.  By just using for loops in different ways we can obtain the desired result.

Objective

To improve the logical thinking using For loops. In this part I am using only two for loops to print the different shapes.

Using the code

I am going to explain the how to get the collections of stars in following shapes. I used only two for loops

Left Alignment triangle - Straight and Reverse

Right Alignment triangle - Straight and Reverse

Square with crossed lines.

LEFT ALIGNMENT - straight

Here I am using number 5 as maximum value. Instead can use a variable to get a value from user

  Console.WriteLine("---------------------------");

            for (int i = 0; i <= 5; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            } 

 

In the above code I used two for loops. In the outer loop I used the variable "i" and it will run ascending order from 1 to 5.In the inner loop I used variable "j" runs from
zero to till the value of outer "i".

for (int j = 0; j < i; j++)

For an example
  When "i" value is zero, the inner loop will not run 
  When "i" value is one the inner loop will run 1 time prints single star --  *

  Now we have Writline() method which prints new line.

  When "i" value is two the inner loop will run 2 time prints single star --  **
  then prints new line.  

Like this the inner loop runs from 1 to current value of outer loop "i" . In our case it is up to 5. So we will get the output as follows : 

*
**
***
****
*****

LEFT ALIGNMENT - Reverse

If we want to print the stars in reverse triangle then we need to iterate the outer loop from max value to min value. The inner loop "j" runs from 0 to current iteration value of outer "i" 

  for (int i = 5; i >= 1; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            Console.WriteLine("---------------------------");

 

At the first iteration the "i' value will be 5.

Now the inner loop runs from 5 to 1 and prints *****
At the end of inner loop I print a new line. So that next iteration starts in new line

At next iteration **** will come. Similarly at the end of both loops we get the following triangle of stars


*****
****
***
**
*

         
If we write both codes one after another we will get a triangle facing right hand side.

*
**
***
****
*****
*****
****
***
**
*

RIGHT ALIGNMENT -Straight

The above code shows the triangle of stars facing right hand side. Similarly if we want to print the triangle of stars facing left hand side, we have the code as follows:

  Console.WriteLine("---------------------------");
            for (int i = 5; i >= 0; i--)
            {
                for (int j = 0; j < 5; j++)
                {
                    if (i > j)
                        Console.Write(" ");
                    else
                        Console.Write("*");
                }
                Console.WriteLine();
            }

 In the above code the outer loop starts from 5 to 0 and inner loop also runs from 0 to 5.So we will be having 25 iterations totally.Here I have added a if condition so that the stars start to print after leaving the required white spaces. I am printing SPACE if "if" condition is true and Star if condition fails.

At the first iteration of outer for loop, the "i" value will be 5.

So in inner loop, the i value will be checked for the each iteration of inner "j" loop.

So now -- if (i >j)
 
          if (5>0) condition true so it prints SPACE
   if (5>1) condition true so it prints SPACE.
    .
    .
   if (5>5) condition fails  so it prints SPACE. 

At the end of 1st iteration of outer for loop
 
          SPACE SPACE SPACE SPACE SPACE

In the 2nd iteration the i value will be 4, now in inner loop
 
 if (4>0) condition true so it prints SPACE
 ...
 if (4>5) condition fails so it prints *

At the end of the 2nd iteration of outer for loop we have
 
 SPACE SPACE SPACE SPACE *

Similarly after running other values of "i" and "j"

we get


    *
   **
  ***
 ****
*****

RIGHT ALIGNMENT -Reverse

TO print the stars in reverse directio with right alignment we have

           for (int i = 0; i < 5; i++)
            {
                for (int j = 1; j <= 5; j++)
                {
                    if (i < j)
                        Console.Write("*");
                    else
                        Console.Write(" ");
                }
                Console.WriteLine();
            }

In this code we have the made some changes of previous logic as of above code (Right alignment - Straight)
we need to iterate the outer for loop in ascending direction and checking the if condition.
We print * if condition is true and SPACE if condition fails
Here the outer loop starts from 0 to 5

At first iteration i=0; In inner loop j starts from 1

we are checking i less then j

so now  ---> if (i<j)


   if (0<1) condition true so it prints Star *
   if (0<2) condition true so it prints Star *
    .
    .
   if (0<5) condition true so it prints Star *

At the end of 1st iteration of outer for loop
 
          *****

In the 2nd iteration the i value will be 1, now in inner loop
 
 if (1<1) condition fails so it prints SPACE
 if (1<2) condition true so it prints Star *
 ...
 if (1<5) condition true so it prints Star *

At the end of the 2nd iteration of outer for loop we have
 
 SPACE ****

Similarly after running other values of "i" and "j"

*****
 ****
  ***
   **
    *


If we write both codes one after another we will get,

    *
   **
  ***
 ****
*****
*****
 ****
  ***
   **
    *

We get a triangle that faces towards left side.

SQUARES

To get the square with diagonals, horizontal and vertical lines like below:

***********************
**         *         **
* *        *        * *
*  *       *       *  *
*   *      *      *   *
*    *     *     *    *
*     *    *    *     *
*      *   *   *      *
*       *  *  *       *
*        * * *        *
*         ***         *
***********************
*         ***         *
*        * * *        *
*       *  *  *       *
*      *   *   *      *
*     *    *    *     *
*    *     *     *    *
*   *      *      *   *
*  *       *       *  *
* *        *        * *
**         *         **
***********************

At first we need to look at the square with whole stars

                  012...                22--->j values
i=0  ***********************
i=1  ***********************
i=2  ***********************
     ***********************
     ***********************
     ***********************
     ***********************
     ***********************

         ......

i=20 ***********************
i=21 ***********************

The code is as follows:

  int n = 23;
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if ((i == 0) || (j == 0) || (i == n - 1) || (j == n - 1) || (i == n / 2) || (j == n / 2) || (i == j) || (i + j == n - 1))
                    {
                        Console.Write("*");
                    }
                    else
                    {
                        Console.Write(" ");
                   }

                } Console.WriteLine();
            }

Here I have a integer variable "n" value 23. For this example the odd numbers woule be better to use to see the results.
Here also I have two loops and both starts from zero to "n" value.

As per our example:

The outer "i"  loop will run from 0 to 23 and  for each iteration of outer loop, the inner "j" will run from 0 to 23.

I have written 8 conditions. Note that I am using OR operator so that if any one conditon gets true the star will be printed. In else part SPACE will be printed.

The first condition i==0

This condition gets true at the first iteration of outer loop. So we get top most horizontal line of square.

***********************


The second condition is j==0, this condition gets true on each first iteration of "j" loop so we will get vertical line at the left most line of square.

*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

The third condition prints bottom most horizontal line of square at the last iteration of i loop ---------->     (i==n-1)
and fourth condition prints the right most vertical line of square when last iteration of "j" loops occurs each time. ------------> (j==n-1)
If we have only these four condition we will be having a square as follows:

***********************
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
*                     *
***********************

Now in fifth condition i== n/2 , in our case the value will be 23/2 --> 11. Hence in 11th row that is when outer i in 11th value the horizontal line will be printed at the middle of square.
Similarly to get the vertical line in middle of square we have the sixth condition j== n/2 which is also 11.

To Print Diagonals:

when i==j prints diagonal from left to right.

If we look at square left to right diagonal will come when i value is equal to j


*   ---> i=j=0
 *
  * ---> i=j=2
   *
    *
     *
      *
       *
        *
         *
          *
           *
            *
             *
              *
               *
                *
                 *
                  *
                   *
                    *
                     *
                      * ---> i=j=22

For printing right to left diagonal of square, I am adding i and j and checking the sum is 22. Because when i is zero and j starts from 1 then the condition gets true when j is 22

so when i is 0

 0+22(j value) = 22

when i is 1

       1+21(j value) = 22

like this

when i is 22

       22+0(j value) = 22

Like this we will get

                             * ----> i val is 0 j val is 22
                     * ----> i val is 1 j val is 21
                    * ----> i val is 2 j val is 20
                   *
                  *
                 *
                *
               *
              *
             *
            *
           *
          *
         *
        *
       *
      *
     *
    *
   *
  *
 * ----> i val is 21 j val is 1
* ----> i val is 22 j val is 0

Conclusion

  I just used only two for loops to get these shapes. In my next article let us see how can we print diamond shapes of stars using three for loops.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:




About the Author

Nagasundar_Tn

Full Name: Nagasundar Nagarajan
Member Level:
Member Status: Member
Member Since: 3/15/2010 2:07:41 PM
Country: India
Regards, T.N.Nagasundar
http://www.dotnetfunda.com

I am software Developer having more then 4 years of experince in C#,ASP.NET,SQL Server,LINQ,WCF,HTML,CSS,Javascript and JQuery
Login to vote for this post.

Comments or Responses

Posted by: Laurenrodriguez on: 11/22/2012 | Points: 25

There are certainly a lot more details to take into consideration, but thanks for sharing this post.

Posted by: Self-Innovator on: 2/19/2013 | Points: 25

Very nice...Post


Login to post response.

Comments / Responses
Select text & click toolbar to format. Formatting appears in viewmode only. HTML Tags are not allowed.
Bold Italic Underline Paragraph Title Code  Link 
 Wait ... Processing ..... please wait.

Comment using Facebook