I am very new to C# and I am trying to create a console application to create a vertical and horizontal histogram, made of stars. So I am asking the user for 8 numbers between 1-10 and printing their results onto the screen as a histogram.
I need help with displaying the histogram vertically, I've done the horizontal one and can't figure out how to make it vertical. Here's what I've got so far:
Would appreciate any help greatly. Thank you in advance.
I'd like it to look something like this:
*
* *
* * *
* * * *
* * * * *(Height of row depends on numbers user enters.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class Program
{
static void Main(string[] args)
{
clsMainMenu MainMenu = new clsMainMenu();
ConsoleKeyInfo ConsoleKeyPressed;
do
{
MainMenu.DisplayMenu();
ConsoleKeyPressed = Console.ReadKey(false);
Console.WriteLine();
switch (ConsoleKeyPressed.KeyChar.ToString())
{
case "1":
clsHistogram Histogram = new clsHistogram();
Histogram.CreateHorizontalHistogram();
break;
case "2":
clsHistogram HistogramV = new clsHistogram();
HistogramV.CreateVerticalHistogram();
break;
}
} while (ConsoleKeyPressed.Key != ConsoleKey.Escape);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsMainMenu
{
public void DisplayMenu()
{
Console.WriteLine("1. Create a Horizontal Histogram.");
Console.WriteLine("2. Create a Vertical Histogram.");
Console.WriteLine("Press Esc to exit the Program.");
Console.WriteLine("..................................");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsHistogram
{
string strNumberChosen = "";
public void CreateHorizontalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" *");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Horizontal Array.
}
public void CreateVerticalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" * \n");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Vertical Array.
}
}
}
Here is a little test program that might get you started on creating the Vertical Histogram. Notice I combined the last solution I provided for the Horizontal Histogram and made the code more universally applicable:
private static readonly char star = '*';
private static readonly uint minValue = 1;
private static readonly int maxValue = 10;
static void Main(string[] args)
{
var list = GetHistorgramData();
CreateHorizontalHistogram(list);
CreateVerticalHistogram(list);
}
private static void CreateHorizontalHistogram(List<int> list)
{
Console.WriteLine("Your Horizontal Histogram looks like this: ");
//foreach(var value in list)
//{
// Console.WriteLine(string.Empty.PadRight(value, star));
//}
//Console.WriteLine("Or like this with LINQ");
list.ForEach(n => Console.WriteLine(string.Empty.PadRight(n, star)));
}
private static void CreateVerticalHistogram(List<int> list)
{
Console.WriteLine("Your Vertical Histogram looks like this: ");
for(int i = 0; i < maxValue + 1; i++)
{
var displayLine = string.Empty;
foreach(int x in list)
{
displayLine += ((x + i) - maxValue) > 0 ? star.ToString() : " ";
}
Console.WriteLine(displayLine);
}
}
private static List<int> GetHistorgramData()
{
var limits = "a number between " + minValue + " and " + maxValue + ": ";
Console.WriteLine("Please enter " + limits);
var list = new List<int>();
do
{
var message = string.Empty;
bool isNumber = false;
bool isRightSize = false;
int output;
do
{
var input = Console.ReadLine();
isNumber = int.TryParse(input, out output);
if(isNumber)
{
isRightSize = minValue <= output && output <= maxValue;
message = isRightSize ? "That will do: " : "Try again - value is not " + limits + output;
}
else
{
message = "Try again - " + input + " is not a Number";
}
Console.WriteLine(message);
}while(!isNumber || !isRightSize);
list.Add(output);
Console.WriteLine("Entered number at position" + list.Count + " : " + output);
}while(list.Count < 8);
return list;
}
Vertical Results:
*
**
**
****
****
******
*******
********
********
for input:
Please enter a number between 1 and 10:
2
Entered number at position1 : 2
4
Entered number at position2 : 4
6
Entered number at position3 : 6
8
Entered number at position4 : 8
9
Entered number at position5 : 9
6
Entered number at position6 : 6
4
Entered number at position7 : 4
3
Entered number at position8 : 3
NOTE:
I suggest you use the method GetHistorgramData() for both Vertical and Horizontal.
You can decide whether you wish to use LINQ for the Horizontal Histogram or the foreach loop version.
I think I could have made LINQ version for the Vertical Histogram, but I felt that might look confusing.
You might want to restyle the Histogram a bit, but keep in mind the width of a space " " is different than that of the star "*".
Please let me know if you have any questions.
int currentValue = 1;
bool allDone = false;
Console.WriteLine("Your Histogram looks like this: ");
while (!(allDone))
{
int x = 0;
for (int intcounter = 0; intcounter < 8; intcounter++)
{
if (intHistogramArray[intcounter] >= currentValue)
{
Console.Write(" * ");
}
else
{
Console.Write(" ");
x = x + 1;
}
}
if (x>=8) { allDone = true; }
currentValue = currentValue + 1;
Console.WriteLine();
}
output:
Your Histogram looks like this:
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
If you want to have them bottom-aligned, you have to make some slight modigfications, this is just to give you an idea on how to start.
Related
Working on an assignment where i need to accomplish the following: On a survey a question asks the surveyed person to rate something from 1-5 (whole number). The end user of your program iinputs the answers for that question on an unknown number of surveys. Write a program that allows this and outputs the percent response for each value (1, 2, 3, 4, and 5).
I did a previous Console app with a loop to collect an average and I am unsure how to collect a percent response on 5 different possible inputs.
Below is my previous code.
namespace WhileLoopsMean
public class MeanProgram
static void Main(string[] args)
{
long test, sum, loop, count;
double avg;
Console.Write("How many tests? ");
count = long.Parse(Console.ReadLine());
sum = 0;
loop = 1;
while (loop <= count)
{
Console.Write("enter score " + loop + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
loop = loop + 1;
}
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.WriteLine("\n\nenter a score of -100 to end\n");
count = 1;
sum = 0;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
while (test != -100)
{
count = count + 1;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
if (test != -100)
{
sum = sum + test;
}
else { }
}
count = count - 1;
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.ReadKey();
class Program {
static void Main(string[] args) {
string input = "";
List<List<int>> answers = new List<List<int>>();
int questionsCount = ReadInt32("The number of questions: ");
for (int i = 0; i < questionsCount; i++) {
answers.Add(new List<int>());
}
while (input == "" || input == "y") {
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
a.Add(ReadInt32($"Question [{i}]: "));
}
input = Read("Continue (y/n)? ").ToLower();
}
WriteLine("End of input!");
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
Write($"Average for question[{i}]: {a.Average()}\n");
}
ReadKey();
}
static string Read (string a) {
Write(a);
return ReadLine();
}
static int ReadInt32 (string a = "") {
Write(a);
return ToInt32(ReadLine());
}
}
Try this out. You can customize the questions. And note that to use Write() and WriteLine(), you should add
using static System.Console;
at the top, in the references of the project.
I have created a piece of code to create an array of 100 elements which will randomize based on the numbers from a set array. However whenever I enter "y" I am looking the array to delete the last element and add a new random element to the start and move everything in between one to the right to allow for this. However at the moment it is completely changing the array every time I enter "y". Can anyone help with this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
int[] values = { 1, 2, 3, 4, 5, 6 };
int Min = values[0];
int Max = values[5] + 1;
int w = 0 ;
int[] rndValues = new int[100];
Random rndNum = new Random();
Console.WriteLine("Random001 " + w);
for (int i = 0; i < rndValues.Length; i++)
{
rndValues[i] = rndNum.Next(Min, Max);
}
Console.WriteLine("Random " + w);
foreach(var item in rndValues)
{
Console.Write(item.ToString() + " ");
}
if (w==0)
{
Console.WriteLine(Environment.NewLine);
prob(rndValues, Min, Max,w);
Console.WriteLine(Environment.NewLine);
w++;
}
if (w>0)
{
while(true)
{
Console.WriteLine("To change elements in the array press y");
// read input
var s = Console.ReadLine();
if(s == "y")
{
//rndValues[99] = 0;
for(int i = 0; i == rndValues.Length; i++)
{
if (i != rndValues.Length)
{
rndValues[rndValues.Length-i] = rndValues[(rndValues.Length-i)-1];
}
else if (i == rndValues.Length)
{
rndValues[0] = rndNum.Next(Min, Max);
}
}
}
else
{
break;
}
prob(rndValues, Min, Max,w);
}
}
}
public static void prob(int[] rndValues, int Min, int Max, int w )
{
double[] count = new double[rndValues.Length];
//Loop through min to max and count the occurances
for (int i = Min; i <Max; i++)
{
for (int j = 0; j < rndValues.Length; j++)
{
if (rndValues[j] == i)
{
count[i] = count[i] + 1;
}
}
}
//For displaying output only
foreach(var item in rndValues)
{
Console.Write(item.ToString() + " ");
}
Console.WriteLine("W " + w);
for (int i = Min; i < Max; i++)
{
count[i] = (count[i] / rndValues.Length) * 100;
Console.WriteLine("Probability of the number " + i + " is " + count[i]);
}
}
}
}
Thanks.
I am working on a project here where I need to have a rolling average of a 2D array of numbers. The rolling average should average across a rolling "window" size of 8. I have a simple example here to demonstrate, but the idea is that with each new 2D array (a new data scan), that array will be copied into the rolling buffer that I have set up as a 3D array where the 3rd dimension is of size of the rolling window. With the current code I have below, I'm not getting the output I expect. To check if its working, I am just printing out the same position in each 2D scan across all scans of the rolling buffer, but I am not getting what I expect and I'm struggling to find issue in the code. Am I even going about this correctly? Thanks for any help. output attached below.
I would expect an output that looks like:
0 (nextline)
1 | 0 (nextline)
2 | 1 | 0 (nextline)
3 | 2 | 1 | 0 (nextline)
and so on ...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlockCopySample
{
class Program
{
static void Main(string[] args)
{
RollingAverager RA = new RollingAverager();
for (int i = 0; i < 25; i++)
{
RA.addValue(i);
RA.PrintBuffer();
System.Threading.Thread.Sleep(1000);
}
}
}
class RollingAverager
{
const int INT_SIZE = 4;
const int DOUBLE_SIZE = 8;
const int BUFFER_LENGTH = 8;
const int SCAN_ROW_SIZE = 3;
const int SCAN_COLUMN_SIZE = 4;
//int scan_value_block_size = SCAN_ROW_SIZE * SCAN_COLUMN_SIZE * DOUBLE_SIZE;
int scan_value_block_size=0;
double[,] array_CurrentScan = null;
double[,,] array_FullBuffer = null;
double total = 0;
int numLoaded = 0;
public double Average { get; set; }
public RollingAverager()
{
array_CurrentScan = new double[SCAN_ROW_SIZE, SCAN_COLUMN_SIZE];
array_FullBuffer = new double[SCAN_ROW_SIZE, SCAN_COLUMN_SIZE, BUFFER_LENGTH];
scan_value_block_size = Buffer.ByteLength(array_CurrentScan);
}
//public void addValue(int newVal)
public void addValue(int index)
{
//Console.Write("here" + index.ToString() + "\n");
for (int j = 0; j < SCAN_ROW_SIZE; j++)
{
for (int k = 0; k < SCAN_COLUMN_SIZE; k++)
{
array_CurrentScan[j, k] = (double) index + j + k;
}
}
//Console.Write("here 1\n");
if (numLoaded == 0)
{
numLoaded++;
Console.Write("here 2\n");
}
else if(numLoaded > 0 && numLoaded < BUFFER_LENGTH)
{
//shift all buffer scans by 1 index to allow for new data to be copied into 0 index
Buffer.BlockCopy(array_FullBuffer, 0 * scan_value_block_size, array_FullBuffer, 1 * scan_value_block_size, numLoaded * scan_value_block_size);
Console.Write("here 3\n");
numLoaded++;
}
else
{
//shift all buffer scans by 1 index to allow for new data to be copied into 0 index
Buffer.BlockCopy(array_FullBuffer, 0 * scan_value_block_size, array_FullBuffer, 1 * scan_value_block_size, (BUFFER_LENGTH - 1) * scan_value_block_size);
Console.Write("here 4\n");
}
//Copy new data into buffer at index 0
Buffer.BlockCopy(array_CurrentScan, 0 * scan_value_block_size, array_FullBuffer, 0 * scan_value_block_size, scan_value_block_size);
//Average = total / numLoaded;
}
public void PrintBuffer()
{
//Console.Write("|");
//Console.Write(total.ToString() + "\n");
for (int i = 0; i < numLoaded; i++)
{
//total += array_FullBuffer[0,3,i];
Console.Write(array_FullBuffer[0, 0, 0].ToString() + " | ");
}
Console.Write("\n");
//Console.WriteLine(" Average = " + Average.ToString());
}
}
}
I m Trying to convert a number entered in the text box post.But I can not find the right reasons, does not work.Are you also please have a look.Thank you in advance!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NumberToText
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void NumberControl()
{
if ((txtNumber.Text.Length>7))
{
MessageBox.Show("Please enter a smaller number");
}
}
public void ReadNumber()
{
try
{
int ones, tens, hundreds, thousands, tenthousands, hundredthousands,
millions;
int number = Convert.ToInt32(txtNumber.Text);
int[] array=new int[7];
for (int j = 0; j < txtNumber.Text.Length; )
{
array[j] = (number / (10 ^ (txtNumber.Text.Length -
(txtNumber.Text.Length - j)))) % 10;
j += 1;
}
if (txtSayi.Text.Length != 7)
{
for (int i = 6; i >= txtNumber.Text.Length; )
{
dizi[i] = 0;
i-=1;
}
}
ones = array[0];
tens = array[1];
hundreds = array[2];
thousands = array[3];
tenthousands = array[4];
hundredthousands = array[5];
millions = array[6];
//Converting to numbers in TURKISH Text
string[] a_ones = { "", "Bir", "İki", "Üç", "Dört", "Beş", "Altı",
"Yedi", "Sekiz", "Dokuz" };
string[] a_tens = { "", "On", "Yirmi", "Otuz", "Kırk", "Elli",
"Altmış", "Yetmiş", "Seksen", "Doksan" };
string[] a_hundreds = { "", "Yüz", "İkiyüz", "Üçyüz", "Dörtyüz",
"Beşyüz", "Altıyüz", "Yediyüz", "Sekizyüz", "Dokuzyüz" };
string[] a_thousands = { "", "Bin", "İkibin", "Üçbin", "Dörtbin",
"Beşbin", "Altıbin", "Yedibin", "Sekizbin", "Dokuzbin" };
string[] a_tenthousands = { "", "On", "Yirmi", "Otuz", "Kırk",
"Elli", "Altmış", "Yetmiş", "Seksen", "Doksan" };
string[] a_hundredthousands = { "", "Yüz", "İkiyüz", "Üçyüz",
"Dörtyüz", "Beşyüz", "Altıyüz", "Yediyüz", "Sekizyüz", "Dokuzyüz" };
string[] a_millions = { "", "Birmilyon", "İkimilyon", "Üçmilyon",
"Dörtmilyon", "Beşmilyon", "Altımilyon", "Yedimilyon", "Sekizmilyon", "Dokuzmilyon"
};
lblText.Text = a_millions[millions] + " " + a_hundredthousands
[hundredthousands] + a_tenthousands[tenthousands] + " " + a_thousands[thousands] + "
" + a_hundreds[hundreds] + " " + a_tens[tens] + " " + a_ones[ones];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnConvert_Click(object sender, EventArgs e)
{
NumberControl();
ReadNumber();
}
}
}
for (int j = 0; j < txtNumber.Text.Length; )
{
array[j] = (number / (10 ^ (txtNumber.Text.Length - (txtNumber.Text.Length - j)))) % 10;
j += 1;
}
(txtNumber.Text.Length - (txtNumber.Text.Length - j)) is j, so:
for (int j = 0; j < txtNumber.Text.Length; j += 1)
{
array[j] = (number / (10 ^ j)) % 10;
}
You're XOR'ing 10 with j?
Also, "Sekizmilyon" is not a word. You need a put a space in between.
It looks like you're trying to calculate a power of 10 with ^ when you probably mean Math.Pow. Using the reduction aib suggested, your line:
array[j] = (number / (10 ^ (txtNumber.Text.Length - (txtNumber.Text.Length - j)))) % 10;
becomes:
array[j] = (number / (int)Math.Pow(10, j)) % 10;
A couple of other suggestions:
Change NumberControl to return a bool so you can skip the call to ReadNumber if the entered number is too large. Currently it goes into ReadNumber even if the number is more than 7 digits, which results in an array out of bounds error
The block of code starting with if (txtSayi.Text.Length != 7) seems redundant.
I'm having a logic problem here. I want to add the result of the factorial values but I'm not sure how to add them. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task_8_Set_III
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " +);
}
}
static double fact(double value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}
}
}
Not sure if this is what you meant but if for factorial of N you want to have the sum of all factorials up to that value this is how you do it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task_8_Set_III
{
class Program
{
static void Main(string[] args)
{
double sum = 0;
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
sum += c;
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + sum);
}
}
static double fact(double value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}
}
}
You need to add a total variable to keep track of the sum.
double total = 0; //the total
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
total += c; // build up the value each time
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + total);
}
short of totally understanding what you want to do exactly, here's two things...
in programming, the following expression is perfectly valid:
i = i + 1 Saying "the new value of i is the old value of i plus one"
variables live within scopes, their boundaries usually being braces { }, that is you will need a variable that is outside the braces of the foreach in order to "remember" stuff of the previous iteration.
static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 7; i++)
{
int c = fact(i);
sum += c;
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + sum);
}
}
static int fact(int value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}