Develop a C# console application that displays the following pattern. Use for loops (hint: nested) to generate the patterns. All asterisks should be displayed by a single statement of the form Console.Write("*"); which displays the asterisks leading up to the number value shown in the example. Note the sequence of each number in turn. You will need to deduce how the numbers are computed (they are the result of a computation) and where that computation will be placed in the loop structures. You may not hardcode the displayed numbers into your loops.
I already have the "*" but can't figure out the numbers.
The two patterns should look similar to the following:
*2
**4
***6
****8
*****10
******12
*******14
********16
*********18
**********20
{
for (int row = 0; row < 10; row++)
{
Console.Write(" ");
for (int col = 0; col <= row; col++)
{
Console.Write("*");
Console.Write(" ");
}
Console.WriteLine(" ");
}
Console.WriteLine(" ");
for (int row = 0; row < 10; row++)
{
Console.Write(" ");
for (int col = 10; col > row; col--)
{
Console.Write("*");
Console.Write(" ");
}
Console.WriteLine(" ");
}
}
}
}
I already have the "*" but can't figure out the numbers.
You have the hardest part then: getting the numbers to print is much easier. Note that the number that you print is equal to two times the number of asterisks in front of it. Therefore, what you need to write is 2*n, where n is the limit in the loop that wrote the asterisks (i.e. the row plus one in your code).
You can combine the printing with writing the end-of-line mark: replace
Console.WriteLine(" ");
with
Console.WriteLine(2*(row+1));
to get the desired result.
I decided to make my comment to dasblinkenlight's answer into an answer on its own:
for(int row = 0; row < 10; row++) {
for(int col = 0; col <= row; col++) {
Console.Write("*");
}
Console.Write("{0}{1}", (row+1)*2, Environment.NewLine);
}
Notice, that the rownumer displayed at the end of the line is calculated as (row+1)*2, because your loop starts at index 0. The output would be faulty otherwise. This is followed by a new line.
Related
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();
}
I'm trying to create a pyramid in c# using a number input.
I know how to create a normal pyramid that counts from 1-20 but I can't seem to find what to change on my code to make it.
Instead of:
1
2 2
3 3 3
4 4 4 4
I need it to be:
4
3 3
2 2 2
1 1 1 1
Here's my current code:
using System;
public class Exercise17
{
public static void Main()
{
int i,j,spc,rows,k;
Console.Write("\n\n");
Console.Write("Display the pattern like pyramid with repeating a number in same row:\n");
Console.Write("-----------------------------------------------------------------------");
Console.Write("\n\n");
Console.Write("Input number of rows : ");
rows= Convert.ToInt32(Console.ReadLine());
spc=rows+4-1;
for(i=1;i<=rows;i++)
{
for(j=spc;j>=1;j--)
{
Console.Write(" ");
}
for(k=1;k<=i;k++)
Console.Write("{0} ",i);
Console.Write("\n");
spc--;
}
}
}
First, you need to reverse the for loop. So that it starts with rows, loops while greater than zero, and decrements and each iteration
for (i = rows; i > 0; i--)
This is the main part. But you also need to take care of the spaces. So to do this we now need to keep track of how many iterations we have already performed. So we need a new variable initiated before the loop.
int iteration = 1;
for (i = rows; i > 0; i--)
.....
Then we need to use this, in the loop to output the number. And then increment it afterwards.
for (k = 1; k <= iteration; k++)
Console.Write("{0} ", i);
iteration++;
So the whole loop now looks like;
int iteration = 1;
for (i = rows; i > 0; i--)
{
for (j = spc; j >= 1; j--)
{
Console.Write(" ");
}
for (k = 1; k <= iteration; k++)
Console.Write("{0} ", i);
Console.Write("\n");
spc--;
iteration++;
}
Now the challenge is, can you try to optimise this further?
Instead of the following:
Console.Write("{0} ",i);
You can write:
Console.Write("{0} ", (rows - i) + 1);
I want to create a List with words and later compare them. First I need is to add strings to List for wordsnumber times. If user inputs wordsnumber = 5, how can I write that ?
while (wordsnumber < 1 || wordsnumber > 20)
{
Console.WriteLine("*Leader Instructor: You must follow my instructions !");
Console.Write("Your number: ");
wordsnumber = Convert.ToInt32(Console.ReadLine());
}
if(wordsnumber >= 1 || wordsnumber < 20)
{
Console.WriteLine("*Leader Instructor: Awesome.");
}
List<string> words = new List<string>();
You can use a normal for loop to ask the user to enter wordsNumber amount of words. Normally the structure of the for loop would look something like:
List<string> words = new List<string>();
for (int i = 0; i < wordsnumber; i++)
{
Console.Write($"Enter word #{i + 1}: ");
words.Add(Console.ReadLine());
}
A couple other things: you should use int.TryParse to try to get the number so the program doesn't crash if they enter some non-numeric text, and you don't need the if condition since the while loop is already enforcing a valid range of numbers. Just for fun, I also showed how to color the leader instructor text in red, so it stands out more:
int wordsnumber;
Console.WriteLine("Enter the number of words (1 - 20): ");
while (!int.TryParse(Console.ReadLine(), out wordsnumber) ||
wordsnumber < 0 || wordsnumber > 20)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("*Leader Instructor: You must follow my instructions !");
Console.ResetColor();
Console.Write("Enter the number of words (1 - 20): ");
}
You can simply add a word into a list with words.Add(wordsnumber);. After adding a word into a list you can iterate through the list with a for loop and then ad if statement for comparing your words like:
for (int i = 0; i < words.length; i++){
for (int j = 0; j < words.length; j++) {
//so you don't compare the word with itself
if (i != j) {
if (words[i] == words[j]) {
...words are the same do something
}
}
}
}
And also as #Rufus said try using int.TryParse instead of Convert.ToInt32
So im using a for loop to loop through all rows in an excel spreadsheet and i can display the current row number very easily by just using the "i" definition, however it prints on multiple lines since each iteraton displays with a Console.WriteLine() command.
What i would like is for it to only show it once, and have it display an updated iteration on one single line. Here is my current code:
void DeleteCells(string filePath)
{
int currRowNumber = 0;
// create excel-instance:
Application excel = new Application();
// open the concrete file:
Workbook excelWorkbook = excel.Workbooks.Open(#filePath);
// select worksheet. NOT zero-based!!:
_Worksheet excelWorkbookWorksheet = excelWorkbook.ActiveSheet;
if(isclosing)
{
closeProgram(excel, excelWorkbook);
}
int numRows = excelWorkbookWorksheet.UsedRange.Rows.Count;
Console.WriteLine("Number of rows: " + numRows);
Console.Write("Checking Row #: " + currRowNumber);
int numRowsDeleted = 0;
int nullCounter = 0;
//for (int j = 1; j <=)
for (int i = 1; i < numRows + 4; i++)
{
//We want to skip every row that is null and continue looping until we have more than 3 rows in a row that are null, then break
if (i > 1)
{
i -= 1;
}
//Create Worksheet Range
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)excelWorkbookWorksheet.Cells[i, 2];
string cellValue = Convert.ToString(range.Value);
if (nullCounter == 5)
{
Console.WriteLine("Null row detected...breaking");
Console.WriteLine("Number of rows deleted: " + numRowsDeleted);
break;
}
if (cellValue != null)
{
if (cellValue.Contains("MESSAGE NOT CONFIGURED"))
{
//Console.WriteLine("Deleting Row: " + Convert.ToString(cellValue));
((Range)excelWorkbookWorksheet.Rows[i]).Delete(XlDeleteShiftDirection.xlShiftUp);
numRowsDeleted++;
//Console.WriteLine("Number of rows deleted: " + numRowsDeleted);
nullCounter = 0;
i--;
currRowNumber++;
}
else
{
currRowNumber++;
nullCounter = 0;
}
}
else
{
nullCounter++;
//Console.WriteLine("NullCounter: " + nullCounter);
}
i++;
}
Console.WriteLine("Fixes Finished! Please check your excel file for correctness");
closeProgram(excel, excelWorkbook);
}
Sample output:
Row Number: 1
Row Number: 2
Row Number: 3
Row Number: 4
Row Number: 5
etc..
I want it to display only one line and continuously update the row number. How would i go about doing this? Any help is appreciated. Thanks.
UPDATE:
So i have the following loop:
for (int i = 1; i < numRows + 2; i++) //numRows was +4, now +2
{
Console.Clear();
Console.WriteLine("Number of rows: " + numRows);
Console.Write("Checking Row #: " + currRowNumber);
//We want to skip every row that is null and continue looping until we have more than 3 rows in a row that are null, then break
if (i > 1)
{
i -= 1;
}
//Create Worksheet Range
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)excelWorkbookWorksheet.Cells[i, 2];
string cellValue = Convert.ToString(range.Value);
if (nullCounter == 3) //was 5
{
Console.WriteLine("\nNull row detected...breaking");
Console.WriteLine("Number of rows deleted: " + numRowsDeleted);
break;
}
if (cellValue != null)
{
if (cellValue.Contains(searchText))
{
//Console.WriteLine("Deleting Row: " + Convert.ToString(cellValue));
((Range)excelWorkbookWorksheet.Rows[i]).Delete(XlDeleteShiftDirection.xlShiftUp);
numRowsDeleted++;
//Console.WriteLine("Number of rows deleted: " + numRowsDeleted);
nullCounter = 0;
i--;
currRowNumber++;
rowsPerSecond = i;
}
else
{
currRowNumber++;
nullCounter = 0;
}
}
else
{
nullCounter++;
//Console.WriteLine("NullCounter: " + nullCounter);
}
i++;
}
I want to calculate how many rows im looping through per second, then calculate from that number how long it will take to complete the entire loop, based on how many rows there are.
Again, any help is appreciated, thanks!
On each loop circle use the Clear() method before print output:
Console.Clear();
You could do this:
const int ConsoleWidth = 80;
for(int i = 0; i < 10; i++)
{
// pull cursor to the start of the line, delete it with spaces
// then pull it back again
for(int j = 0; j < ConsoleWidth; j++) Console.Write("\b");
for(int j = 0; j < ConsoleWidth; j++) Console.Write(" ");
for(int j = 0; j < ConsoleWidth; j++) Console.Write("\b");
Console.Write("Row Number: {0}", i);
}
If you do
Console.Write("Row Number: {0}", i);
It will keep appending in front of previous text.
If you do
Console.Clear();
Any message that you intend to write before this text will dissapear.
If you know the exact position of the text, you can try to modify the text in console at that position as:
// First time write
Console.WriteLine("Row Number: {0}", i);
// x,y coordinates in the method for later iterations
Console.SetCursorPosition(11, 0);
Console.Write(i);
If the amount of text in the row will never decrease (e.g. because the number only ever gets bigger) you can do this by using Console.Write() and prefixing the text with \r:
for (int i = 0; i < 100000; ++i)
Console.Write($"\rRow Number: {i}");
Console.WriteLine();
If the text decreases in length because the number gets smaller, you can use a formatting string to output the number left-justified with extra spaces which will overwrite the extra digits:
for (int i = 100000; i >= 0; --i)
Console.Write($"\rRow Number: {i, -6}");
Console.WriteLine();
Doing it this way has the advantage that you keep any previous text in the console and only update the single line. This also makes it a lot quicker compared to clearing the entire display every iteration.
try to use Console.SetCursorPosition before Console.Write
You can do as the previous answers suggested, here is another way.
int line = Console.CursorTop;
int len = new String("Row Number: ").length;
Console.WriteLine("Row Number: ");
for(your loop)
{
Console.WriteLine(i);
//Print whatever else you want!
Console.SetCursorPosition(len,line);
}
Advantage of this approach is that the position is remembered and you can come back to the same position after displaying any other information to the user, This is useful when updating a single character in a screen full of text!
To answer the next question, use
Stopwatch s = new Stopwatch();
long millis =0,avg;
for(int i=0;i<loopLength;i++)
{
s.Start();
//Do work
s.Stop();
millis += s.ElapsedMilliseconds;
avg = millis/(i+1);
Console.WriteLine("Time remaining :" + (TimeSpan.FromMilliseconds(avg*(loopLength - (i+1))).Seconds);
}
Is it possible to write a loop that will write to the console with overlapping text?
Desired output:
Notice how the lines overlap. I was using '|' vertically and '-' horizontally.
The vertical line is the 4th column and the horizontal line is the 3rd row.
I know this is way off:
for (int i = 1; i <= 4; i++)
{
Console.Write(" | ");
for (int x = 1; x <= 6; x++)
{
Console.Write(" - ");
}
}
Try Extended ASCII Codes. These might help you draw pretty pseudographics:
╒╥╦╫