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 )
{
}
}
}
}
}
CodePudding user response:
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);
}
CodePudding user response:
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("");
}
CodePudding user response:
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();
}
temp
means temporary variable, just have no idea how to call it ;)