c# I cannot print a message from a loop - c#

I am trying to make a simple program that takes in 2 integers: a number and a width. I want it to print a triangle with that width using that number. Should I use a double for loop instead if not can it be done my way?
class Program
{
public static int readInt()
{
int result;
string resultString = Console.ReadLine();
result = int.Parse(resultString);
return result;
}
static void Main(string[] args)
{
int number, width;
Console.WriteLine("Enter a number: ");
number = readInt();
Console.WriteLine("Enter a width: ");
width = readInt();
do {
for (int i = width; i < 0; i--)
{
Console.Write(number);
width--;
Console.WriteLine();
}
} while (width < 0);
Console.ReadLine();
}
}
Output:
number:7
width:4
7777
777
77
7

Just for fun, this version will print a rectangle centered
int space = 0;
do
{
// Prints initial spaces
for(int x = 0; x < space; x++)
Console.Write("-");
// Print the number for the current value of width
for (int i = 0; i < width; i++)
Console.Write(number);
// Print final spaces -
// Not really needed
for (int x = 0; x < space; x++)
Console.Write("-");
// Start the new line
Console.WriteLine();
//Decrease width by one space for each end (2)
width-=2;
// Increment the spaces to print before and after
space++;
} while (width > 0);
A part from the logic completely rewritten note that Console.WriteLine appends a newline, so you need to use Console.Write

Related

Printing characters using Nested loops

today while I was coding I ran into a problem I couldn't figure out.
So my task is to print a chosen amount of characters, the catch is I need to also specify how much characters are in one line.
For example:
I need to print 24 characters '*'
I select the character.
Select how many: 24.
Select how many character per each line: 7.
Result should look something like this:
*******
*******
*******
***
I have to strictly use nested loops!
Code example:
static void Main(string[] args)
{
char character;
int charAmount;
int charAmountInLine;
Console.WriteLine("Select character");
character = char.Parse(Console.ReadLine());
Console.WriteLine("Select total amount of characters");
charAmount = int.Parse(Console.ReadLine());
Console.WriteLine("Select amount of characters in each line");
charAmountInLine = int.Parse(Console.ReadLine());
Console.WriteLine("");
for (int i = 0; i < charAmount; i++)
{
for(int j = 0; j < charAmountInLine; j++)
{
}
}
}
}
}
In this program, you need to identify:
Number of lines that print full characters in a line (row)
Print the remaining characters (remainder)
Concept:
Iterate each row (first loop).
Print character(s) in a line (nested loop in first loop).
Once print character(s) in a line is completed, print the new row and repeat Step 1 to Step 3 to print full characters in a line if any.
Print the remaining character in a line (second loop).
int row = amount / characterPerLine;
int remainder = amount % characterPerLine;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < characterPerLine; j++)
{
Console.Write(character);
}
Console.WriteLine();
}
// Print remaining character
for (int i = 0; i < remainder; i++)
{
Console.Write(character);
}
Demo # .Net Fiddle
First of all count number of rows for outer loop
int numberOfRows = (int)Math.Ceiling((double)charAmount / charAmountInLine);
for (int i = 0; i < numberOfRows; i++)
{
charAmount -= charAmountInLine;
charAmountInLine = charAmount> charAmountInLine? charAmountInLine: charAmount;
for (int j = 0; j < charAmountInLine; j++)
{
Console.Write(character);
}
Console.WriteLine("");
}
Try this one:
int row = (int)Math.Ceiling((double)charAmount/(double)charAmountInLine);
int column = 0;
int temp = 0;
for (int i = 1; i <= row; i++)
{
temp = (i * charAmountInLine);
column = temp < charAmount ? charAmountInLine : temp - charAmount;
for(int j = 0; j < column; j++)
{
Console.Write(character);
}
Console.WriteLine();
}

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;
}

How to display a simple hollow asterisk rectangle in console?

Could someone advise me on a simple way to implement hollow rectangles in C#?
I have been able to make a simple rectangle, but hollow rectangle programs I've looked at either contained or arrays or were pretty convoluted. For instance, the solution on another forum that seems too challenging, and this answer on CodeReview.SE is too difficult to understand.
This is what I've done, which displays a simple (filled) rectangle. How to output a hollow rectangle using if logic if possible?
class Nested_Loops_Hollow_Rectangles
{
public void RunExercise()
{
// how are now supposed to make this hollow?
// columns are side by side, rows is number of top to bottom
// see tut
Console.WriteLine("Welcome to the HollowRectanglePrinter Program.");
Console.WriteLine("How many columns wide should the rectangle be?"); //i.e. 4
int iColMax, iRowMax;
string userChoiceC = Console.ReadLine();
Int32.TryParse(userChoiceC, out iColMax);
Console.WriteLine("How many rows tall should the rectangle be? "); //i.e. 4
string userChoiceR = Console.ReadLine();
Int32.TryParse(userChoiceR, out iRowMax);
Console.WriteLine("Here you go:");
if (iRowMax > 0 || iColMax > 0)
{
for (int iRow = 0; iRow < iRowMax; iRow++)
{
for (int iCol = 0; iCol < iColMax; iCol++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
}
The essential part of your application can be reduced to:
private void DrawFillRectangle(int width, int height)
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
This, by the way (separating the logic and the input by putting the logic in a dedicated method) is what you should be doing. See Separation of concerns for more information.
The previous method draws a filled rectangle, so how can you draw a hollow one?
Start looking at the output. For instance, for (5, 3), the output is:
*****
*****
*****
and what you want is to have:
*****
* *
*****
How can you do that? Probably by replacing stars by spaces in some cases. Which ones?
Well, look again at the output. The first row is untouched, so the condition where you use spaces instead of stars is limited to rows other than the first one, that is:
private void DrawRectangle(int width, int height)
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (y > 0)
{
// Print either a star or a space.
}
else
{
Console.Write("*");
}
}
Console.WriteLine();
}
}
Now you must include the other cases in your condition: the first column, and the last column and row.
In order to combine conditions, you can use && and || operators. The first one means that the condition is true if both operands are true, and the second one means that either the first or the second operand is true.
It might be that your final condition will become too difficult to read. There are two things you can do. The first thing is to use intermediary variables. For instance:
if (a && b && c && d)
{
}
can be refactored into:
var e = a && b;
var f = c && d;
if (e && f)
{
}
if it makes sense to regroup a with b and c with d. A second thing you can do is to put the condition in a separate method, which may improve readability if you find a good name for the method:
private void DrawRectangle(int width, int height)
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (this.IsInsideRectangle(x, y))
{
// Print either a star or a space.
}
else
{
Console.Write("*");
}
}
Console.WriteLine();
}
}
private bool IsInsideRectangle(int x, int y)
{
return y > 0 && ...
}
This is hopefully all you need to do the exercise. Depending of your progression in the course, you may also be interested in those aspects:
You may avoid repeating code in an if/else block, so instead of:
if (...)
{
Console.Write(" ");
}
else
{
Console.Write("*");
}
you may end up writing only only Write():
Console.Write(...)
What C# operator can you use for that?
It is a good practice for a method to validate its input before doing its job. If you've already learnt what exceptions are, how can they be used to validate width and height? Why in the current situation it may make sense to not filter negative and zero values (in other words, would the application crash if, for instance, width is equal to -5)?
class emptyRectangle:Shape
{
byte width;
byte height;
public emptyRectangle(byte width,byte height)
{
this.width = width;
this.height = height;
}
public override void area()
{
Console.WriteLine("\n----------");
for (int i = 0; i < height; i++)
{
Console.WriteLine("");
for (int k = 0; k < width; k++)
{
if (i > 0 && k > 0)
{
if (i < height - 1 && k < width - 1)
{
Console.Write(" ");
}
else
Console.Write('*');
}
else
Console.Write("*");
}
}
}
}
Add a single IF statement where you are drawing the character:
if it is the first or last row or the first or last column, write the *
else the space.
For more fun, make a variable sized rectangular "hole" in the rectangle.
static void Main()
{
int width = 0, height = 0;
width = int.Parse(Console.ReadLine());
height = int.Parse(Console.ReadLine());
for (int i = 1; i <= height; i++)
{
for (int j = 1; j <= width; j++)
{
if ((i == 1 || i == height || j == 1 || j == width))
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
Console.ReadKey();
}

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 ;)

Using C# for loops to create a "V"

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 ();
}
}

Categories