Print pattern using for loops - c#

How to print a pattern using for loops?
Figure(3) Figure(4)
** **
** **
** **
** **
**
I tried this:
static void PrintPattern (int column)
{
for (int r = 0; r <= column + 1; r++)
{
Console.Write("**");
for (int c = 0; c < r; c++)
{
Console.WriteLine(" ");
}
Console.WriteLine();
}
}

made for fun, hope I won't receive too many -1s
int depth = 4;
var rows = Enumerable.Range(0, depth + 1)
.Select(v => new string('\t', v) + "**" );
var oneString = string.Join(Environment.NewLine, rows);
Console.WriteLine (oneString);
prints:
**
**
**
**
**
Remarks:
if you use ' ' as separator, instead of tab '\t', you'll get next result:
**
**
**
**
**

void Main()
{
const int rowCount = 10;
Console.Write("**");
for (var rowNumber = 0; rowNumber < rowCount - 1; rowNumber++)
{
Console.Write("\n ");
for (var spaceCount = 0; spaceCount < rowNumber; spaceCount++)
{
Console.Write(" ");
}
Console.Write("**");
}
}

Works just fine . . .
for figure3 : lines = 4, for figure4 : lines = 5
static void Main(string[] args)
{
int lines = 5;
for (int i = 0; i < lines; i++)
{
bool flag = false;
for (int j = 0; j < lines; j++)
{
if (j == i)
{
Console.WriteLine("**");
flag = true;
}
else
{
if (!flag)
Console.Write(" ");
}
}
}
}

I don't know C# but i'll help you in Java. You should change syntax as desired (Console.Write == System.out.print && Console.Writeline == System.out.println). So here goes the code:
static void printPattern(int column){
int spaceCount = 2;//number of spaces before **, change as needed
int k;//number of times ** is printed each row, must remain always 1
for(int i = 0; i < column; i++){
System.out.println();//starts each row with a new line
for(int j = 1; j < spaceCount; j++){
System.out.print(" ");//prints j spaces in each row
}
spaceCount++;//increment spacecount each row, so j can also go + 1
for(k = 1; k <= 1; k++){
System.out.print("**");//each row prints ** k times
}
k--;//k must remain 1
}
}
For Figure(3) call printPattern(4); for Figure(4) printPattern(5);

Related

For loop Hash character pattern

Hi i am new to programming and i currently have this code:
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 4; i++)//'rows'
{
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
}
}
}
}
This produces this output:
########
######
####
##
the number of hashes is correct as i am going from 8, 6, 4, 2 but i need to add an extra space every time i go onto a new line. How do i make it so the output is as follows?
########
######
####
##
Thanks,
Umer
From your code you could modify it to do the following in the inner for loop:
for (int j = 0; j < i - 1; j++) {
Console.Write(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++) {
Console.Write("#");
}
Console.WriteLine("\n" );
As a note you should probably use StringBuilder to do this as I believe it is quite inefficient to constantly call Console.WriteLine.
The code could be modified further:
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < i - 1; j++) {
sb.append(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++) {
sb.append("#");
}
sb.append("\n" );
}
Console.WriteLine(sb.toString());
Introduce variables, start your rows at 0 and repeat the string for each row number.
This can also be applied to the string printing the hashes:
static void Main(string[] args)
{
int rows = 4;
int columns = 9;
for (int i = 0; i < rows; i++)
{
// Print a string with `i` spaces.
Console.Write(new String(' ', i));
int hashes = columns - ((i + 1) * 2) + 1;
Console.Write(new String('#', hashes));
Console.WriteLine();
}
}
Basically, just add space in front of your hash characters.
######## Row 1 (i=1), 0 Space
###### Row 2 (i=2), 1 Space
#### Row 3 (i=3), 2 Spaces
## Row 4 (i=4), 3 Spaces
In this case, you need "i-1" spaces for each rows. (Actually, it's (8 - charater count) / 2) and character count was 9 - (i*2) + 1, so ( 8 - 9 + i * 2 - 1 ) / 2 = (i * 2 - 2) / 2 = i - 1 )
So just make loop to add spaces before print hash chracters.
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 4; i++)//'rows'
{
for (int j = 0; j < i -1; j++) {
Console.Write(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
}
}
}
}
You could do something like this:
for (int i = 1; i <= 4; i++)//'rows'
{
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
for (int y = i; y > 0; y--)
{
Console.Write(" ");
}
}

Making a star pyramid in C#

So I'm trying to do a pyramid in C# but I can't get it to print properly.
I'm doing this for my school's C# class, can't really figure out how to get the spaces in the pyramid properly. I feel like I'm really doing something wrong here.
Instead of a triangle I'm getting something like this:
*
**
***
****
*****
******
*******
********
Here is my code:
using System;
namespace Pyramidi
{
class Ohjelma
{
static void Main()
{
int korkeusMax = 0;
int valit = 0;
do
{
Console.Write("Anna korkeus: ");
korkeusMax = Convert.ToInt32(Console.ReadLine());
if (korkeusMax > 0) {
break;
}
else {
continue;
}
}
while(true);
for (int korkeus = 1; korkeus <= korkeusMax; korkeus++)
{
valit = (korkeusMax - korkeus) / 2;
for (int i = 0; i < valit; i++)
{
Console.Write(" ");
}
for (int leveys = 1; leveys <= korkeus; leveys++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Try this:
for (int korkeus = 0; korkeus < korkeusMax; korkeus++)
{
for (int i = 0; i < (korkeusMax - korkeus - 1); i++)
{
Console.Write(" ");
}
for (int i = 0; i < (korkeus * 2 + 1); i++)
{
Console.Write("*");
}
Console.WriteLine();
}
Alternatively, instead of loops, you can use new String('*', num). Try this:
for (int korkeus = 0; korkeus < korkeusMax; korkeus++)
{
Console.Write(new String(' ', korkeusMax - korkeus - 1));
Console.Write(new String('*', korkeus * 2 + 1));
Console.WriteLine();
}
You are doing the first half right, but what you want to do for the second half is another for loop that does the opposite.
So you probably want to copy your for loop and change the header from
for (int korkeus = 1; korkeus <= korkeusMax; korkeus++)
to
for (int korkeus = kokeusMax; korkeus > 1; korkeus--)
or something along those lines

To solve upside-down rendering?

I have written this segment of C# to help me understand how nested for loops can be used to render 2 dimensional data.
Here is what the output looks like.
████
███
██
█
I would like to make it so that the 4 blocks up top are rendered at the bottom, basically in the reverse order so that the steps ascend. However the console window only renders downward, so the conventional thinking won't be right. The following is my code.
static void Main(string[] args)
{
int i = 0;
int j = 0;
for (i = 0; i < 4; i++)
{
Console.Write('\n');
for (j = i; j < 4; j++)
{
Console.Write("█");
}
}
Console.ReadKey();
}
This is what I'd like the output to look like.
█
██
███
████
You need to reverse your loop condition from inremant to decremant..
for (i = 0; i < 4; i++)
{
Console.Write('\n');
for (j = i; j >= 0; j--)
{
Console.Write("█");
}
}
Output will be;
Here is a DEMO.
UPDATE: Since you change your mind, you need to add space every column (column number isi) 4 - 1 times.
public static void Main(string[] args)
{
int i = 0;
int j = 0;
for ( i = 0; i < 4; i++ )
{
for ( j = 0; j < 4; j++ )
{
if ( j < 3 - i )
Console.Write(" ");
else
Console.Write("█");
}
Console.Write('\n');
}
Console.ReadKey();
}
Here is a DEMO.
class Program
{
const int Dimension = 4;
static void Main(string[] args)
{
char[] blocks = new char[Dimension];
for (int j = 0; j < Dimension; j++)
blocks[j] = ' ';
for (int i = 0; i < Dimension; i++)
{
blocks[Dimension - i - 1] = '█';
for (int j = 0; j < Dimension; j++)
Console.Write(blocks[j]);
Console.WriteLine();
}
Console.ReadKey();
}
}
Should be:
for (j = 3 - i; j < 4; j++)
{
Console.Write("█");
}
The easiest way would be: just reverse your inner loop condition and decrement the counter instead of incrementing it:
for (i = 0; i < 4; i++)
{
Console.Write('\n');
for (j = i; j >= 0; j--)
{
Console.Write("█");
}
}
Console.ReadKey();
returning:
█
██
███
████
And for right-to-left version:
for (i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
if(j < 3 - i)
Console.Write(" ");
else
Console.Write("█");
}
Console.Write('\n');
}
Console.ReadKey();
with a result:
█
██
███
████

C# Multiplication Table

So I'm attempting to print a multiplication table in C# however I can't quite figure out how to get what I need.
So far my program outputs the following:
1 2 3
2 4 6
3 6 9
However, I need it to output this:
0 1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
I've tried a lot of different ways to get the second output however I can't quite figure it out. I'm not necessarily asking for an answer but if someone could point me in the right direction it would be much appreciated.
This is the code I have as of now:
static void Main(string[] args)
{
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.Write(i * j + "\t");
}
Console.Write("\n");
}
Console.ReadLine();
}
for (int i = 0; i <= 3; i++)
{
Console.Write(i + "\t");
for (int j = 1; j <= 3; j++)
{
if (i>0) Console.Write(i * j + "\t");
else Console.Write(j + "\t");
}
Console.Write("\n");
}
int tbl= int.Parse(Console.ReadLine());
int j = int.Parse(Console.ReadLine());
for (int i=1; i<=10; i++)
{
for (int j=1;j<=10; j++)
{
Console.WriteLine("{0}*{1}={2}", i, j, (i * j));`enter code here`
}
}
Console.ReadLine();
You should skip both 0's.
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
Console.Write((i == 0? j : (j == 0? i : i*j)) + "\t");
}
Console.Write("\n");
}
You could try one of this three solutions.
Solution 1 (without if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
Console.Write("{0}\t", i);
for (int j = 1; j <= 3; j++)
{
Console.Write("{0}\t", i * j);
}
Console.WriteLine();
}
Console.ReadLine();
}
Solution 2 (With if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
if (i == 0)
{
Console.Write("{0}\t", i);
}
else
{
Console.Write("{0}\t", i * j);
}
}
Console.WriteLine();
}
Console.ReadLine();
}
Solution 3 (With short-hand if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.Write("{0}\t", (i == 0) ? i : i * j);
}
Console.WriteLine();
}
Console.ReadLine();
}
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
if (i == 0)
{
Console.Write(j);
}
else
{
if(j == 0)
{
Console.Write(i);
}
else
{
Console.Write(i * j);
}
}
}
Console.Write("\n");
}
Console.WriteLine("Enter A Number");
int j = Convert.ToInt32(Console.ReadLine());
for (int i = 0 ; i <= 10; i++) {
Console.WriteLine("{1} X {0} = {2}",i,j,i*j);
Console.ReadLine();
}
public class Program
{
//int num;
public static void Main(string[] args)
{
int num,num1;
Console.WriteLine("enter a any number num");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter any second number num1");
num1 = Convert.ToInt32(Console.ReadLine());
for(int i = num;i <= num1; i++)
{
for (int j = 1; j <= 10; j++)
{
Console.Write(i *j+ "\t");
}
}
Console.Write("\n");
}
}
using System;
/*
* Write a console-based application that displays a multiplication table of the product of
* every integer from 1 through 10 multiplied by every integer from 1 through 10. Save the
* file as DisplayMultiplicationTable.cs.
*/
namespace MultiplicationTable
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\t\t\t\t\t\t\t\t\tMultiplication Table");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------");
const int END = 11;
for(int x = 1; x < END; x++)
{
for(int y = 1; y < END; y++)
{
int value = x * y;
Console.Write("{0} * {1} = {2}\t", y, x, value);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Output
Output of Code
I am attempting to complete the above code in a GUI. So far I have come up with the following code; but the output is not like the above output.
My Code for the GUI is as follows:
using System;
using System.Windows.Forms;
namespace DisplayMultiplicationTableGUI
{
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
}
private void ShowTableButton_Click(object sender, EventArgs e)
{
int a;
int b;
const int STOP = 11;
for(a = 1; a < STOP; a++)
{
for(b = 1; b < STOP; b++)
{
int value = a * b;
multiplicationTableLabel.Text += String.Format("{0} * {1} = {2} ", b, a, value);
}
multiplicationTableLabel.Text += "\n";
}
}
}
}

create asterisk tree with C#

Hello everyone
I try to solve asterisk tree problem
and found my code is not work correctly and can be improved.
This is output that expected
input : 5
*
* * *
* * * * *
* * *
*
input : 4
* * * *
* *
* * * *
and this is my code
static void Main(string[] args)
{
Console.Write("input:");
char input = Console.ReadKey().KeyChar;
if (char.IsDigit(input))
{
int couter = (int)char.GetNumericValue(input);
Console.WriteLine();
if (couter % 2 != 0)
{
for (int i = 1; i <= couter; i++)
{
for (int j = 3; j > i; j--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(" *");
}
Console.WriteLine();
}
for (int i = couter - 1; i >= 3; i--)
{
for (int j = 1; j <= i; j++)
{
if (j <= couter - i)
{
Console.Write(" ");
}
else
{
Console.Write("* ");
}
}
Console.WriteLine();
}
}
else
{
for (int i = couter; i > 3; i--)
{
for (int j = 1; j <= i; j++)
{
if (couter - i >= j)
{
Console.Write(" ");
}
else
{
Console.Write("* ");
}
}
Console.WriteLine();
}
for (int i = couter - 1; i <= couter; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
}
}
}
Please could you help me to solve this problem.
Lately, I think I'm poor at algorithms and a little complex problem. Is anybody know useful link or how I can improve this skill, please let me know.
Thanks,
Check this page for input 5 (diamond) : http://www.dreamincode.net/forums/topic/126715-diamond-asterisk/
I've translated it to C# - now it displays diamonds with size that you set in variable 'rows':
int rows = 5;
StringBuilder sb = new StringBuilder();
// top part
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= rows - i; j++)
sb.Append(' ');
for (int k = 1; k <= 2 * i - 1; k++)
sb.Append('*');
sb.AppendLine();
}
//bottom part
for (int n = rows - 1; n > 0; n--)
{
for (int l = 1; l <= rows - n; l++)
sb.Append(' ');
for (int m = 1; m <= 2 * n - 1; m++)
sb.Append('*');
sb.AppendLine();
}
Console.Write(sb.ToString());
I was initially reluctant to post it because it definitely smells like homework...
Anyway, here's a piece of working code:
static void Main(string[] args)
{
Console.Write("input:");
char input = Console.ReadKey().KeyChar;
if (char.IsDigit(input))
{
int couter = (int)char.GetNumericValue(input);
Console.WriteLine();
if (couter % 2 != 0)
PrintDiamond(couter);
else
PrintHourGlass(couter);
}
Console.ReadLine();
}
private static void PrintDiamond(int couter)
{
bool moreAsterisks = true;
for (int row = 0; row < couter; row++)
{
int nAsterisks = moreAsterisks ? (2 * row) + 1 : 2 * (couter - row - 1) + 1;
int nSpaces = (couter - nAsterisks) / 2;
if (row == (couter - 1) / 2)
moreAsterisks = false;
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
for (int i = 0; i < nAsterisks; i++)
Console.Write("*");
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
Console.WriteLine();
}
}
private static void PrintHourGlass(int couter)
{
bool moreAsterisks = false;
for (int row = 0; row < couter - 1; row++)
{
int nAsterisks = moreAsterisks ? couter - 2 * (couter - row - 2) : couter - (2 * row);
int nSpaces = (couter - nAsterisks) / 2;
if (row == (couter - 2) / 2)
moreAsterisks = true;
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
for (int i = 0; i < nAsterisks; i++)
Console.Write("*");
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
Console.WriteLine();
}
}
P.S.:
it works with any number, not just 4-5...
Here's a minified LINQ solution for your problem:
class Program
{
static void Main(string[] args)
{
Console.Write("input: ");
string line = Console.ReadLine();
int n;
if (!int.TryParse(line, out n))
{
Console.WriteLine("Enter a valid integer number.");
return;
}
for (int i = 0; i < n; i++)
{
int l = Math.Abs(n - i * 2 - 1) + 1;
if (n % 2 != 0) l = n - l + 1;
Console.Write(Enumerable.Repeat(" ", n - l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
Console.WriteLine(Enumerable.Repeat("* ", l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
}
}
}
It's pretty simple; inside the loop, first line calculates length of the i-th diamond row if input is even, second one corrects the calculation for odd input. The remaining two lines print i-th row using some LINQ tricks. If you don't like showing off with LINQ, you can replace thoose lines with regular for loops (which is probably going to be faster). Then the code would look like:
class Program
{
static void Main(string[] args)
{
Console.Write("input: ");
string line = Console.ReadLine();
int n;
if (!int.TryParse(line, out n))
{
Console.WriteLine("Enter a valid integer number.");
return;
}
for (int i = 0; i < n; i++)
{
int l = Math.Abs(n - i * 2 - 1) + 1;
if (n % 2 != 0) l = n - l + 1;
//Console.Write(Enumerable.Repeat(" ", n - l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
//Console.WriteLine(Enumerable.Repeat("* ", l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
for (int c = 0; c < n - l; c++) Console.Write(" ");
for (int c = 0; c < l; c++) Console.Write("* ");
Console.WriteLine();
}
}
}

Categories

Resources