Using C# for loops to create a "V" - c#

For homework I have been asked to write a C# console program that has the user define a character and size, and the program will output an n*n/2 sized "V" where n is the width of the "V". The best I can get is either triangles or one diagonal line going left and one going right below it. Any suggestions would be greatly appreciated.
public static void Main (string[] args)
{
int maxWidth = 40;
Console.WriteLine ("Please enter your desired character");
string userChar = Console.ReadLine ();
Console.WriteLine ("Please enter your desired width");
int userWidth = Convert.ToInt32 (Console.ReadLine ());
for (int i = 0; i < userWidth; i++) {///opposite diagonal lines
for (int j = 0; j < i; j++) {
Console.Write (" ");
}
Console.Write (userChar);
Console.WriteLine ();
}
for (int i = userWidth - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
Console.Write (" ");
}
Console.Write (userChar);
Console.WriteLine ();
}

You are approaching the logic wrong by trying to calculate both sides separately.
As a hint, there are 2 spots on each row that are far away from each other at the top, and close to each other at the bottom. Each row, they both move toward each other. So what you want to do is figure out where they are at the top (say, 1 and 10), then each row, add one to the first and subtract one from the last, so they move closer to the middle. at the bottom, they will meet each other.
As another hint, it is possible to complete this task using one loop.

Try this:
int lines = userWidth / 2;
for (var i = 1; i < lines; i++)
Console.WriteLine(userChar.PadLeft(i) + userChar.PadLeft(2 * (lines - i)));
Console.WriteLine(userChar.PadLeft(lines));
I get this:
X X
X X
X X
X X
X X
X X
X X
X X
X X
X X
X

Thanks for all your input, this is the code i ended up coming up with.
public static void Main (string[] args)
{
int maxWidth = 40;
Console.WriteLine ("Please enter your desired character");
string userChar = Console.ReadLine ();
Console.WriteLine ("Please enter your desired width");
int userWidth = Convert.ToInt32 (Console.ReadLine ());
for (int i = 0; i < userWidth; i++) {
for (int j = 0; j < i; j++) {
Console.Write (" ");
}
Console.Write (userChar);
for (int j = userWidth-1; j > i; j--) {
Console.Write (" ");
}
for (int j = userWidth-1; j > 0+i ; j--) {
Console.Write (" ");
}
Console.Write (userChar);
Console.WriteLine ();
}
}

Related

Re-prompt if input is less than or equal to 0 [duplicate]

This question already has answers here:
C# How to loop user input until the datatype of the input is correct?
(4 answers)
Closed 3 years ago.
I have a function which asks for input from the user which will be parsed to an int and that will be used to create a pyramid.
I know I have to use a loop of some kind and I have tried a do/while loop but I don't seem to understand it. I can't declare n above the Console.Write outside the do/while and if I have it below inside of the do/while, the while condition wont accept it because it's out of the scope. It would seem so simple to say, do(ask for input and assign to n) while(n <=0), but I can't do that.
I also had an idea I tried which was to run the function within itself as long as n was <=0 but that runs the function infinitely. Not sure if I'm on the right track but I feel lost right now.
static void Pyramid()
{
Console.Write("Choose a pyramid height: ");
int n = Int32.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
Console.Write(" ");
}
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.Write(" ");
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.WriteLine();
}
}
It should works:
int n;
do
{
Console.Write("Choose a pyramid height: ");
n = Int32.Parse(Console.ReadLine());
if ( n <= 0) Console.WriteLine("Value must be greater than 0.");
}
while ( n <= 0 );
Just use an infinite while loop, and continue if the number is invalid:
static void Pyramid()
{
while(true)
{
Console.Write("Choose a pyramid height: ");
int n = Int32.Parse(Console.ReadLine());
if (n <= 0)
{
Console.Error.WriteLine("That's an invalid number");
continue;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
Console.Write(" ");
}
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.Write(" ");
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.WriteLine();
}
}
}
Let's extract method. We should implement 2 checks:
If input is an integer value at all (e.g. "bla-bla-bla" is not an integer)
If input is a valid integer (we don't accept -123)
Code:
public static int ReadInteger(string prompt,
Func<int, bool> validation = null,
string validationMessage = null) {
int result;
while (true) {
if (!string.IsNullOrEmpty(prompt))
Console.WriteLine(prompt);
string input = Console.ReadLine();
if (!int.TryParse(input, out result))
Console.WriteLine("Sorry, your input is not a valid integer value. Please, try again.");
else if (validation != null && !validation(result))
Console.WriteLine(string.IsNullOrEmpty(validationMessage)
? "Sorry the value is invalid. Please, try again"
: validationMessage);
else
return result;
}
}
then you can easily use it:
int n = ReadInteger(
"Choose a pyramid height:",
(value) => value > 0,
"Pyramid height must be positive. Please, try again.");
//TODO: your code here to draw the pyramid of height "n"
please, note, that you can easily restrict the upper bound as well (a pyramid of height 1000000000 will hang the computer):
int n = ReadInteger(
"Choose a pyramid height:",
(value) => value > 0 && value <= 100,
"Pyramid height must be in [1..100] range. Please, try again.");

printing matrix square shape c#

I have an 8*8 matrix and here is my code:
static void Main(string[] args)
{
const int matrix_rows = 8;
const int matrix_columns = 8;
double[,] matrix = new double[matrix_rows, matrix_columns];
for (int i = 0 ; i < matrix_rows ; i++)
{
for (int j = 0; j < matrix_columns; j++)
{
Console.WriteLine(matrix[i, j]+ "\t");
}
Console.WriteLine("\n");
}
Console.ReadKey();
I want it to be printed square shape but it prints one "0" in each line. what should I do?
You write a new line each time. Do Console.Write() instead of Console.WriteLine()
It's because you're using Console.WriteLine each time in your inner loop - so every value is printed on a new line.
Also, if you replace Console.WriteLine("\n"); with Console.WriteLine(string.Empty); you won't get an extra blank line between each line.
Try this for your loop and see what you think of the output:
for (int i = 0; i < matrix_rows; i++)
{
for (int j = 0; j < matrix_columns; j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine(string.Empty);
}
Because your array is empty!
Look, you create it
double[,] matrix = new double[matrix_rows, matrix_columns];
and then print it. The default value for double is 0

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 can I draw a triangle of asterisks using the while statement?

here is the (not working code) and it should print the shape below but its not :
static void Main(string[] args)
{
int i = 1;
int k = 5;
int h = 1;
while (i <= 5)
{
Console.WriteLine("");
while (k > i)
{
Console.Write(" ");
k--;
}
while (h <= i)
{
Console.Write("**");
h++;
}
i++;
}
Console.ReadLine();
}
but when I try to do the same using the while statement the shape gets totally messed up.
any help ?
You have to declare k and h within the loop:
static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
int k = 5;
int h = 1;
Console.WriteLine("");
while (k > i)
{
Console.Write(" ");
k--;
}
while (h <= i)
{
Console.Write("**");
h++;
}
i++;
}
Console.ReadLine();
}
With your current solution, after first outer loop iteration, inner loops do nothing.
int NumberOfLines = 5;
int count = 1;
while (NumberOfLines-- != 0)
{
int c = count;
while (c-- != 0)
{
Console.Write("*");
}
Console.WriteLine();
count = count + 2;
}
That's it, simplest implementation.
The problem is that i, k and h are initialised before the outermost loop is entered. Within the outer loop k and h are altered by the inner loops. On the second execution of the outer loop k and h have the same values as were left after running the inner loops previously. As i increments in the outer loop, the k loop will not be entered and the h loop will only run once.
Think about what values h and k should have inside the outermost loop on the second execution.
I'll not solve for you just will give you hint only:
Use 3 loop statements
1. for line change
2. for spaces (reverse loop)
3. for printing * (odd series in this case) i.e. 2n-1
check in third while statement h <= 2*i - 1;
and print only one * in place of **
Check here:
http://ideone.com/xOB2OI
Actually I've done this via 'for' loop, z is height and x is equal to length of side.
Isosceles triangle (x>z):
public void Print(int x, int z)
{
var peakStart = x;
var peakEnd = x;
for (int i = 0; i < z; i++)
{
for (int j = 0; j < 2 * x + 1; j++)
{
if (peakStart < 1.5 * x && j >= peakStart && j <= peakEnd)
Console.Write("*");
else
Console.Write(" ");
}
peakStart--;
peakEnd++;
Console.WriteLine("");
}
}

Categories