printing matrix square shape c# - 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

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 the row of a matrix(multi-dimensional array) in a new line

I have a multi-dimensional array in C#, I have assigned the indices of the matrices by capturing input from a user, I am trying to implement a conditional structure that will let me print the rows of my matrix each on a separate line, for example if my array is A and A has a dimension of 3 by 3 then the code prints the first three elements on the first line, the next three elements on the next line and so on and so forth. I am trying to achieve this because it will be easier to understand the structure as a normal matrix and also build an entire matrix class with miscallenous operations.
Code
class Matrix{
static int[,] matrixA;
static void Main(string[] args){
Console.WriteLine("Enter the order of the matrix");
int n = Int32.Parse(Console.ReadLine());
matrixA = new int[n, n];
//assigning the matrix with values from the user
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
matrixA[i, j] = Int32.Parse(Console.ReadLine());
}
}
//the code below tries to implement a line break after each row for the matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if( (n-1-i) == 0)
{
Console.Write("\n");
}
else
{
Console.Write(matrixA[i, j].ToString() + " ");
}
}
}
}
}
How do I modify my code so that if the array has 9 elements and its a square matrix then each row with three elements are printed on a single line.
I would use something like this for the output:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrixA[i, j].ToString() + " ");
}
Console.Write("\n");
}
When the inner loop is done, that means one row has been completely printed. So that's the only time the newline is needed. (n passes of the outer loop ==> n newlines printed).

Multidimensional array initialization c#

I have a problem initializing the following array
char[,] omar = new char[4, 4];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
omar[i, j] = (char)(Console.Read());
}
}
when I try entering input like this
....
####
####
##..
It only take the first 3 lines not all the fourth , so any help please ?
You're using Console.Read() to read an individual character entered, but when you hit enter, Read() will return either:
A single linefeed character (\n, or decimal 10) if you're on a *nix-like platform;
A carriage-return character (\r, or decimal 13) if you're on Windows. The Read() call directly subsequent to this will then return a linefeed character.
A small modification to get the code you've got to work the way you expect:
char[,] omar = new char[4, 4];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
omar[i, j] = (char)(Console.Read());
}
Console.Read();
if (Environment.NewLine.Length > 1)
Console.Read();
}

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

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