pattern in C# don't know how to create - c#

I need help creating this certain shape on C#
Link to image of shape: https://drive.google.com/file/d/1-5xzVHPm8xG4wvkcGgtZ4IBx2uSgwS4u/view?usp=sharing
I have tried making this shape for a long while but can't seem to make it properly the code I currently have just prints the same first pattern twice back to back.
using System;
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
int i, j, k;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 6 - i; j++)
{
Console.Write("*");
}
for (k = 1; k < i; k++)
{
Console.Write(" ");
}
for (j = 1; j <= 6 - i; j++)
{
Console.Write("*");
}
Console.Write("\n");
}
for (i = 2; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
Console.Write("*");
}
for (k = 1; k <= 5 - i; k++)
{
Console.Write(" ");
}
for (j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
}

Whoa, that's a big block of unreadable code :) I think we need to simplify a bit:
int numOfStars = 5;
int numOfSpace = 2;
while(numOfStars > 0){
Console.Write(new string('*', numOfStars));
Console.Write(new string(' ', numOfSpace));
Console.WriteLine(new string('*', numOfStars));
numOfStars--;
numOfSpace+=2;
}
numOfStars = 2;
numOfSpace = 8;
while(numOfStars < 6){
Console.Write(new string('*', numOfStars));
Console.Write(new string(' ', numOfSpace));
Console.WriteLine(new string('*', numOfStars));
numOfStars++;
numOfSpace-=2;
}
There are a hundred different ways of doing is pattern, the object lessons here are:
name things well - as a developer coming by along to "maintain" your code I looked at it and thought "ugh; I'm not even going to bother to understand it, I'll just delete it and start over"
make your code describe what it does by the way it is written - my code doesn't really need any comments; the only trick that isn't too obvious is that string has a constructor that takes a char and an int and makes a string that is that char repeated that number of times
use things that make your life easier wherever possible, like that constructor
don't get too clever; I thought about exploiting the maths relationship that there are always 12 chars on a line, calculating the number of stars as (12-spaces)/2, printed twice la la, even adding a variable for step so that a single loop could be used, turning around the increment directions after half way.. but then I thought "why add the complexity?". Never confuse the difference between something that is short and something that is clear - just because fewer lines of code are used doesn't make them easier to understand

Here's another sort of hack-ey way to do it:
public static void DrawShape(int maxStars)
{
int lineLength = maxStars * 2 + 2;
for (int row = 0; row < lineLength - 1; row++)
{
int starCount = maxStars - row;
if (starCount == 0 || starCount == -1) continue; // This is the hackey line
if (starCount < 0) starCount *= -1;
int spaceCount = lineLength - starCount * 2;
string stars = new string('*', starCount);
string spaces = new string(' ', spaceCount);
Console.WriteLine(stars + spaces + stars);
}
}

A brute force approach. A simple method that takes two parameters, one for the number of spaces on a line, the second parameter for the number of “*” characters to write…
private static void WriteCharacters(int numSpaces, int numChars) {
Console.Write(new string('*', numChars));
Console.Write(new string(' ', numSpaces));
Console.Write(new string('*', numChars));
Console.WriteLine();
}
Then, write all nine lines…
static void Main(string[] args) {
WriteCharacters(2, 5);
WriteCharacters(4, 4);
WriteCharacters(6, 3);
WriteCharacters(8, 2);
WriteCharacters(10, 1);
WriteCharacters(8, 2);
WriteCharacters(6, 3);
WriteCharacters(4, 4);
WriteCharacters(2, 5);
Console.ReadKey();
}

Related

Magic square array filled with random numbers doesn't accept even numbers

I found this code that i need for an assigment, but it only reads odd numbers and i need it to read even numbers too, but i don't know whats wrong. I need it to make the random magic squares go from 1 to 10.
Still very much a beginner and don't understand functions yet, please let me know if there is a way to dolve this.
using System;
class GFG
{
// Function to generate odd sized magic squares
static void generateSquare(int n)
{
int[,] magicSquare = new int[n, n];
// Initialize position for 1
int i = n / 2;
int j = n - 1;
// One by one put all values in magic square
for (int num = 1; num <= n * n;)
{
if (i == -1 && j == n) // 3rd condition
{
j = n - 2;
i = 0;
}
else
{
// 1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
// 1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i = n - 1;
}
// 2nd condition
if (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
// set number
magicSquare[i, j] = num++;
// 1st condition
j++;
i--;
}
// print magic square
Console.WriteLine("The Magic Square for " + n
+ ":");
Console.WriteLine("Sum of each row or column "
+ n * (n * n + 1) / 2 + ":");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
Console.Write(magicSquare[i, j] + " ");
Console.WriteLine();
}
}
// driver program
public static void Main()
{
Console.WriteLine("Value of n: ");
int n = int.Parse(Console.ReadLine());
// Works only when n is odd
generateSquare(n);
}
}
Step through the program with a debugger. Using n = 2 as an example, on your second loop through the for loop you get to this with i = 1 and j = 1:
if (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
And that makes i = 2 on the next loop through. Because there is no 2 index in the array you have created, it crashes when it gets to this same check the next loop.
Presumably odd numbers are working because they are getting floored on division (in the case of n = 5 -> i = 2).
That should be enough to point you in the right direction.

C# print stars pattern

I want to print pattern like
but i have a problem with output.
my code is:
int i, j, k;
for (i = 5; i >= 1; i--)
{
for (j = 5; j > i; j--)
{
Console.Write(" ");
}
for (k = 1; k < (i * 2); k++)
{
Console.Write("*_");
}
Console.WriteLine();
}
Console.ReadLine();
There are just a couple of issues:
You're writing "*_" for every iteration, including the last. Instead, we should only write "*" on every iteration, followed by "_" on every iteration except the last one. We can do this with two different Console.Write calls, where the second one checks to see if our iterator is at the last position.
You're iterating twice as many times as you need to when you do k < (i * 2) (on the first iteration, i == 5, so i * 2 == 10, which means we'll iterate 9 times). We can fix this by changing it to k <= i
As a side note, we can declare our loop variables locally in the for loops. This reduces their scope, which is usually a good thing.
For example:
for (int i = 5; i >= 1; i--)
{
for (int j = 5; j > i; j--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("*");
if (k < i) Console.Write("_");
}
Console.WriteLine();
}
Console.ReadLine();
The code can be simplified a little bit if we use the string constructor that takes in a character and a number of times to repeat it to write our spaces, and if we iterate one less time in our inner loop we can write "*_" followed by a WriteLine("*"):
for (int i = 5; i >= 1; i--)
{
// Write (5 - i) spaces at once
Console.Write(new string(' ', 5 - i));
// Write 'i' count of "*", joined with a "_"
Console.WriteLine(string.Join("_", Enumerable.Repeat("*", i)));
}
Console.ReadLine();
So many ways to do this...here's another one using StringBuilder and a slight cheat by getting rid of the last "_" with Trim(). It's written generically to take the desired number of rows:
public static void Main()
{
StarPattern(7);
Console.WriteLine("Press Enter to Quit...");
Console.ReadLine();
}
public static void StarPattern(int numberStarsInTopRow)
{
StringBuilder sb = new StringBuilder();
for(int row=0; row<numberStarsInTopRow; row++)
{
sb.Clear();
sb.Append(new string(' ', row));
for(int stars=0; stars<(numberStarsInTopRow-row); stars++)
{
sb.Append("*_");
}
Console.WriteLine(sb.ToString().TrimEnd('_'));
Console.WriteLine();
}
}
Output:
*_*_*_*_*_*_*
*_*_*_*_*_*
*_*_*_*_*
*_*_*_*
*_*_*
*_*
*
Press Enter to Quit...
Here's a compact version using the trick posted in the comments by LarsTech:
public static void Main()
{
StarPattern(7);
Console.WriteLine("Press Enter to Quit...");
Console.ReadLine();
}
public static void StarPattern(int numberStarsInTopRow)
{
for(int row=0; row<numberStarsInTopRow; row++)
{
Console.WriteLine(new string(' ', row) + String.Join("_", Enumerable.Repeat("*", numberStarsInTopRow - row)) + Environment.NewLine);
}
}

How to print star like below in console application? I/p 5 O/p like = 1 212 32123 4321234 543212345 [duplicate]

My question is how to make a pyramid using * and 'space' in C#? The output will be like this.
*
* *
* * *
* * * *
* * * * *
We only need to use "for loop" for this program. I only know how to make this one.
*
**
***
****
*****
I made a program like this:
static void Main(string[]args)
{
int i=o;
int j=o;
for(i=5;1>=1;i--)
for(j=1;j<=5;j++)
{
Console.Write("*");
}
Console.WriteLine(" ");
}
I'm confused when it comes to pyramid because it includes spaces. Thanks for your help!
think about how you'd print the pyramid manually.
suppose 5 levels deep.
1st line: 4 spaces, 1 star,
2nd line: 3 spaces, star, space, star
3rd line: 2 spaces, star space star space star
etc.
doesn't matter whether you print spaces after the last star or not - won't make a difference to how it looks.
what do we see?
if we have a total of X levels
line 1: (x-1) spaces, (star space)
line 2: (x-2) spaces, (star space) twice
line 3: (x-3) spaces, (star space) three times
line 4: (x-4) spaces, (star space) four times
that's the pattern. I'll leave the coding to you.
using System;
class Program
{
static void Main(string[] args)
{
int num, i, j, k;
Console.Write("enter the level:");
num=Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= num; i++)
{
for (j = 1; j < num-i+1; j++)
{
Console.Write(" ");
}
for (k = 1; k <= i; k++)
{
Console.Write(i);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
Your problem is spaces, therefore I suggest you think about the spaces. Tell me this: how many spaces are on each row to the left of the first star? You'll likely be able to solve your own problem if you think about this.
Try to think of it as a grid or a matrix and see where you want the '*' in each row and how it relates to your loop index.
sorry I missed this was homework... will give a strategy ... instead
it helps if you do it in notepad and think about what you are doing... you will start to understand the relationship between the line you are on and the spaces and what not...
Post my answer after 3 hours. I think now you have almost finished it under #iluxa's advice?
int height = 20;
for (int level = 1; level <= height; level++)
{
string text = string.Join(" ", Enumerable.Repeat("*", level));
Console.WriteLine(text.PadLeft(height - level + text.Length));
}
I used some build-in methods e.g. Enumerable.Repeat and String.PadLeft, not the pure C-language way. The purpose is that I want to tell you since you have chosen C# as the programming language(not C/Java/etc), you should resolve problems in the C# way.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pyramid_star
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter a number:");
int n = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
for (int x = i; x <= n; x++)
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)
{
Console.Write("*"+" ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
Program o = new Program();
o.show();
Console.ReadKey();
}
void show()
{
for (int i = 1; i <= 12; i++)
{
for (int j = 1; j <= 9 - i / 2; j++)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(" * ");
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
Console.Write("*");
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
}
}
Try this and follow this same logic in c, c++, php, java
using System;
class pyramid {
static void Main() {
/** Pyramid stars Looking down
Comment this if u need only a upside pyramid **/
int row, i, j;
// Total number of rows
// You can get this as users input
//row = Int32.Parse(Console.ReadLine());
row = 5;
// To print odd number count stars use a temp variable
int temp;
temp = row;
// Number of rows to print
// The number of row here is 'row'
// You can change this as users input
for ( j = 1 ; j <= row ; j++ ) {
// Printing odd numbers of stars to get
// Number of stars that you want to print with respect to the value of "i"?
for ( i = 1 ; i <= 2*temp - 1 ; i++ )
Console.Write("*");
// New line after printing a row
Console.Write("\n");
for ( i = 1 ; i <= j ; i++ )
Console.Write(" ");
// Reduce temp value to reduce stars count
temp--;
}
/** Pyramid stars Looking up
Comment this if u need only a downside pyramid **/
int rowx, k, l;
// Total number of rows
// You can get this as users input
// rowx = Int32.Parse(Console.ReadLine());
rowx = 5;
// To print odd number count stars use a temp variable
int tempx;
tempx = rowx;
//Remove this if u use
Console.Write("\n");
// Number of rows to print
// The number of row here is 'rowx'
for ( l = 1 ; l <= rowx ; l++ ) {
// Leaving spaces with respect to row
for ( k = 1 ; k < tempx ; k++ )
Console.Write(" ");
// Reduce tempx value to reduce space(" ") count
tempx--;
// Printing stars
for ( k = 1 ; k <= 2*l - 1 ; k++ )
Console.Write("*");
// New line after printing a row
Console.Write("\n");
}
}
}
The following code might help:
public static void print(int no)
{
for (int i = 1; i <= no; i++)
{
for (int j = i; j <= no; j++)
{
Console.Write(" ");
}
for (int k = 1; k < i * 2; k++)
{
if(k % 2 != 0)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
Console.ReadLine();
}
Here I have created a number pyramid:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("This is a number pyramid....");
var rows = 5;
for(int i = 1; i <= rows; i++)
{
for(int lsc = (-rows); lsc <= -2; lsc ++)
{
if(lsc < (-1)*i)
{
//write left sided blank spaces
Console.Write(" ");
}
else
{
//write left sided numbers
Console.Write(-1*(lsc));
}
}
for(int rsc = 1; rsc <= rows; rsc++)
{
//write right sided blank spaces
Console.Write(" ");
}
else
{
//Write sided numbers
Console.Write(rsc);
}
}
Console.WriteLine();
}
}
}
I have described here https://utpalkumardas.wordpress.com/2018/04/20/draw-number-pyramid
Out put is:
The is a number pyramid....
1
212
32123
4321234
543212345
I know it's javascript but might help
let n = 6;
for (let i = 1; i <= n; i++) {
let spaces = n-i;
let str = '';
for (let j=0; j < spaces; j++) {
str+=' ';
}
for (let j=0; j < i; j++) {
str+='* ';
}
console.log(str)
}
I have found two approaches:
//1st approach
int n = 6;
for (int i = 0; i < n; i++)
{
// need to print spaces
for (int j = 0; j < n - i - 1; j++)
{
Console.Write(" ");
}
// need to print * with one space
for (int k = 0; k <= i; k++)
{
Console.Write("* ");
}
Console.WriteLine();
}
// 2nd Approach
int rows = 6;
int temp = 0;
bool toggle = false;
for (int j = 0; j < rows; j++)
{
int counter = 0;
for (int i = 0; i < 2 * rows - 1; i++)
{
if (i < rows - temp - 1)
{
Console.Write(" ");
}
else
{
if (counter <= j + temp)
{
if (!toggle)
{
Console.Write("*");
toggle = true;
}
else
{
Console.Write(" ");
toggle = false;
}
}
counter++;
}
}
Console.WriteLine();
temp++;
toggle = false;
}

c# Loops with stars and spaces

I am currently breaking my head over this simple assignment for loops that I have to do.
Basically what I want to achieve is:
1) User gives imput how long the star pyramid should be
2) Make a pyramid with a for loop.
It needs to look something like this:
(If it needs to be 5 stories high; first row is 5 spaces 1 star; second row 4 spaces 2 stars and so on.
*
**
***
****
(Hard to format but you get my intention.)
I currently have this
public void Pyramid()
{
Console.WriteLine("Give the hight of the pyramid");
_aantal = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= _aantal; i++) // loop for hight
{
for (int d = _aantal; d > 0; d--) // loop for spaces
{
Console.Write(_spatie);
}
for (int e = 0; e < i; e++) // loop for stars
{
Console.Write(_ster);
}
Console.WriteLine();
}
}
The output is always the inserted number amount of spaces and it is not decremented correctly.
Although if I debug it it counts down correctly.
Thank you for responding.
You could use the constructor of the string class to create the repetition for you, and then print both values at once, then you don't need the extra for loops
static void Main(string[] args)
{
int rowHeight = 5;
for (int row = 1; row <= rowHeight; row++)
{
string spaces = new string(' ', rowHeight - row);
string stars = new string('*', row);
Console.WriteLine("{0}{1}", spaces, stars);
}
Console.ReadLine();
}
UPDATE
for the semantics, i will then also show it with 2 for loops
static void Main(string[] args)
{
int rowHeight = 5;
for (int row = 1; row <= rowHeight; row++)
{
int totalSpaces = rowHeight - row;
for (int j = 0; j < totalSpaces; j++)
{
Console.Write(" ");
}
for (int j = 0; j < row; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadLine();
}
well, your problem is
for (int d = _aantal; d > 0; d--) // loop for spaces
you really want
for (int d = _aantal - i ; d > 0; d--) // loop for spaces
but it really just mirrors what you currently have, and still doesn't create the pyramid look you seem to want.
I think the closest you'll get in a console app is by subtracting a space every other row:
for (int d = _aantal-i; d > 0; d-=2) // loop for spaces
which will give output:
Give the hight of the pyramid:
10
*
**
***
****
*****
******
*******
********
*********
**********
Got it !
static void Main(string[] args)
{
Console.WriteLine("Give the hight of the pyramid");
string _spatie = " ";
string _ster = "*";
int _aantal = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= _aantal; i++) // loop for height
{
for (int d = i; d < _aantal; d++) // loop for spaces
{
Console.Write(_spatie);
}
for (int e = 1; e <= i; e++) // loop for stars
{
Console.Write(_ster);
}
Console.WriteLine();
}
Console.ReadKey();
}
Check this out..!! You were missing out the iterator 'i' of the height loop inside the spaces loop.
You will get the triangle :-
*
**
***
****
You will need odd number of stars always for a symmetrical pyramid.
I know you wanted to do this as a console app but if you adapt this code it should work fine
Replace textbox1/2 with Consle.Readline/Write
int pyramidstories = int.Parse(TextBox2.Text);
int I = 1;
while (I <= pyramidstories)
{
for (int spacecount = 0; spacecount < (pyramidstories - I); spacecount++)
{
TextBox1.Text += " ";
}
for (int starcount = 1; starcount < I + 1; starcount++)
{
TextBox1.Text += "*";
}
TextBox1.Text += Environment.NewLine;
I++;
}
As your question states you need:
4 spaces 1 star
3 spaces 2 stars
2 spaces 3 stars
etc..
so your pyramid should look something like
*
**
***
****
*****
The code sample above displays a pyramid as illustrated above
To get a pyramid (with proper spacing) like this:
You can use:
static void Main(string[] args)
{
// The length of the pyramid
int lengte = 18;
// Loop through the length as given by the user
for (int i = 0; i <= lengte; i++)
{
// If its an even number (we don't want 1-2-3.. but 1-3-5.. stars)
if (i % 2 == 0)
{
// Calculate the length of the spaces we need to set
int spatieLengte = (lengte / 2) - (i / 2);
// Display spaces
for (int spaties = 0; spaties <= spatieLengte; spaties++)
{
Console.Write(" ");
}
// Display stars
for (int sterren = 0; sterren <= i; sterren++)
{
Console.Write("*");
}
// Newline
Console.WriteLine();
}
}
Console.ReadLine();
}
Obviously the if block and spaceLengte variable aren't really needed. But I thought it would make it somewhat easier for OP to read.
Good luck / Succes ermee ;)

How do I print the output in one row below another?

For example I am trying to print the output in following way:
disk: 1 2 3 4 5
move: 1 3 7 15 31
How can I do that, can someone help me out please?
{
class Program
{
static void Main(string[] args)
{
int n = 2;
for (int j = 1; j <= 5; j++)
Console.WriteLine("disk: {0}", j);
for (int i = 1; i <= 5; i++)
Console.WriteLine("moves: {2:N0}",
n, i,(long)Math.Pow(n, i) - 1);
}
}
}
Console.WriteLine will, as it sounds, write a new line each time. If you don't want that behavior, use Console.Write.
Console.Write("Disk:");
for (int j = 1; j <= 5; j++)
Console.Write(" {0}", j);
Console.WriteLine();
Console.Write("Moves:");
for (int i = 1; i <= 5; i++)
Console.Write(" {2:N0}", (long)Math.Pow(n, i) - 1);
Console.WriteLine();
Use the string.PadLeft() method to justify your text. Of course you can replace the magic numbers with a constant value. This gives you the advantage of not having to count spaces, and automatically adds the right amount of spaces to bring the string up to the desired length.
Note that you can also get rid of the format insertion (i.e. no more curly braces).
static void Main(string[] args)
{
int power = 2;
Console.Write("disk:".PadLeft(8));
for (int j = 1; j <= 5; j++)
Console.Write(j.ToString().PadLeft(5));
Console.WriteLine();
Console.Write("moves:".PadLeft(8));
for (int i = 1; i <= 5; i++)
Console.Write(((long)Math.Pow(power, i) - 1).ToString().PadLeft(5));
Console.WriteLine();
Console.ReadLine();
}
This is the result:
You can use Console.Write and it wont print a carriage return.
However you dont need a for loop in this case. Just use Enumerable.Range
var n = 2;
var disks = Enumerable.Range(1, 5).ToList();
var moves = Enumerable.Range(1, 5).Select(i => (long) Math.Pow(n, i) - 1);
Console.WriteLine("disk: {0}", string.Join(" ", disks));
Console.WriteLine("moves: {0:N0}", string.Join(" ", moves));
Results:
disk: 1 2 3 4 5
moves: 1 3 7 15 31

Categories