How do I output monthly rainfall as "*" using arrays C#? - c#

I have created a program which allows a user to enter the rainfall over the course of a year. The program is then meant to output a chart as well as summarized data such as average, maximum, minimum and total rainfall.
While all of my outputs based upon data works, the actual chart which is meant to display the numbers inputted with asterisks isn't working.
I can't quite understand where I have gone wrong. I have linked an example output of the "*" table as well as my actual code below. Any help would be much appreciated. I am a beginner to C# by the way.
Example output
int[] monthrainfall = new int[12];
int i;
double average;
int total = 0;
int max = 0;
int min = Int32.MaxValue;
string bar = "";
//title
Console.Write("\n\nRainfall Data:\n");
Console.Write("**************\n");
//asks user to input names
Console.Write("Enter Rainfall for the year:\n");
for (i = 0; i < 12; i++)
{
Console.Write("Enter rainfall for month {0}: ", i + 1);
monthrainfall[i] = Convert.ToInt32(Console.ReadLine());
}
//outputs rainfall results
Console.WriteLine("\nRainfall Chart");
Console.WriteLine("**************");
//outputs results for each month
for (i = 0; i < 12; i++)
{
Console.Write("Month {0}: ", i + 1);
bar = bar + "*";
Console.WriteLine("{0} ", bar[i]);
}
Console.WriteLine("\nSummary data");
Console.WriteLine("**************");
//calculates the maximum rainfall
for (int index2 = 0; index2 < 12; index2++) //inline variable declaration
{
if (monthrainfall[index2] > max) max = monthrainfall[index2];
}
Console.WriteLine("The maximum rainfall was: " + max);
//calculates the minimum rainfall
for (int index3 = 0; index3 < 12; index3++) //inline variable declaration
{
if (monthrainfall[index3] < min) min = monthrainfall[index3];
}
Console.WriteLine("The minimum rainfall was: " + min);
//calculates average rainfall
for (int index = 0; index < 12; index++)
{
total = total + monthrainfall[index];
}
average = (total) / 12;
Console.WriteLine("The average rainfall was: " + average);
Console.WriteLine("The total rainfall was: " + total);
Console.ReadKey();

for (i = 0; i < 12; i++)
{ //loop every month
Console.Write("Month {0}: ", i + 1);
bar = "";
for(int stars = 0; stars < monthrainfall[i]; stars++)
{
bar = bar + "*";
}
Console.WriteLine("{0} ", bar[i]);
}
but as #Flydog57 said, use the string constructor instead of the additional for-loop

All of the explanation is going to take place in this part of code
//outputs results for each month
for (i = 0; i < 12; i++)
{
Console.Write("Month {0}: ", i + 1);
bar = bar + "*";
Console.WriteLine("{0} ", bar[i]);
}
Part 1:
on bar = bar + "*"; you are adding only one * for each iteration of the loop. However, what you want is to add the number based on what have been entered in monthrainfall.
As #Flydog57 suggested, the modification would be
bar = new string('*', monthrainfall[i]);
Part 2:
on Console.WriteLine("{0} ", bar[i]); you are only printing one * as you have selected the element bar[i] of the string bar.
The modification would be Console.WriteLine("{0} ", bar);

Related

i want to write a console app that get int value from user and put them in a array

i want to write a console app that get int value from user and put them in a array and show sum of the numbers and min and max of them and then print them in the console in order
i write until this point of project but have some bugs...
Console.WriteLine("\n Please Enter the Number of your Numbers: \n");
int k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" Please Enter Your Numbers:");
int[] myArray = new int[k];
int sum = 0;
//INPUT
for (int i = 0; i < k; i++)
{
myArray[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" Number [" + (i+1) + "]: " + myArray[i] + " and Next:");
}
//DELETE DUPLICATE ELEMENTS
int[] newArray = myArray.Distinct().ToArray();
//SORT
Array.Sort(newArray);
Console.WriteLine("\n Your Sorted Numbers Without Duplicated ones: ");
foreach (int i in newArray)
{
Console.Write(" | " + i);
}
Console.Write(" |");
i think you are trying to make a program like this:
int i,n;
int[] a = new int[100];
Console.WriteLine("element numbers :");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("please entre your numbers : ", n);
for (i = 0; i < n; i++)
{Console.WriteLine($"element i");
a[i] = Convert.ToInt32(Console.ReadLine());}
int sum = 0;
for (i = 0; i < n; i++)
{sum += a[i];}
Console.WriteLine("sum is : {0}", sum);
int max = a[0];
int min = a[0];
for (i = 1; i < n; i++)
{if (a[i] > max)
{max = a[i];}
if (a[i] < min)
{min = a[i];}}
Console.WriteLine("max is : " + max);
Console.WriteLine("min is : " + min);
Console.WriteLine("element numbers are: ");
for (i = 0; i < n; i++)
{Console.WriteLine(a[i]);}

Need help creating console app that outputs percent response for a rating on a survey 1-5 (whole number)

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.

C# Displaying every other number from a user in a console app

I need to write a console app that asks the user how many number (double) to enter. After accepting that many numbers, display every other number entered. There always seems to be an error when I try to use a double. I also get this error "System.IndexOutOfRangeException was unhandled
HResult=-2146233080
Message=Index was outside the bounds of the array."
after the the for loop has gone through the last loop for this line
myArrai1[i] = int.Parse(Console.ReadLine());
in the first for loop
this all the code I have been able to try to brainstorm with.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
int i = 0;
for (i = 1; i <= number; i++)
{
Console.WriteLine("Enter Number " + i.ToString() + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < number; i++)
{
Console.WriteLine("Every other number entered: ");
Console.WriteLine(myArrai1[i += 2]);
}
Console.ReadLine();
}
}
}
Not too far off, main changes to fix fix this was loop#1 was set to 0 index to prevent out of range and loop#2 was simplified by intervaling at 2 of ++.
The rest of the changes were aesthetic; I changed the input Console.WriteLine to just Console.Write to keep the input on the same line, and moved the Every Other Line statement to precede the output display loop instead of being written on every iteration.
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
for (int i = 0; i < number; i++) {
Console.Write("Enter Number " + (i + 1) + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Every other number entered: ");
for (int j = 0; j < number; j = j + 2) {
Console.WriteLine(myArrai1[j]);
}

Extra zero in final out put where does it come from?

I wrote this code to order any set of numbers from biggest to smallest, but for whatever reason, the output always has a zero at the end. My question is, where did it come from? (new to coding)
Console.WriteLine("Please enter set of numbers");
int input = Convert.ToInt16(Console.ReadLine());
int counter= 1;
int temp1;
int temp2;
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
for (int x = 0; x <= input; x++)
{
for (int i = 1; i <=input; i++)
{
if (array[i - 1] <= array[i])
{
temp1 = array[i - 1];
temp2 = array[i];
array[i - 1] = temp2;
array[i] = temp1;
}
}
}
Console.WriteLine();
for (int i = 0; i<=input; i++)
{
Console.Write(array[i] + " ");
}
Console.ReadLine();
You're inconsistent between whether you're trying to handle input + 1 or input elements. For example:
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
You're creating an array with input + 1 elements, but only populating input of them.
In general, it's much more common to use exclusive upper boundaries for loops. For example:
int[] array = new int[input];
for (int i = 0; i < input; i++)
{
// No need for the counter variable at all
Console.WriteLine("Please enter entry number " + (i + 1));
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
}

Trying to find the average amount of attempt it takes for Tom to roll a six on: 10 repetitions

It takes the total number of rolls and divides them by 10. For example, if it took 56 rolls so my average is 5.6.
Random numGen = new Random ();
int numOfAttempt = 0;
int Attempt = 0;
int avrBefore = 0;
int avrAfter = 0;
for (int i = 1; i <= 10; i++)
do {
Attempt = numGen.Next (1, 7);
Console.WriteLine (Attempt);
numOfAttempt++;
avrBefore = numOfAttempt;
avrAfter = avrBefore / 10;
} while (Attempt != 6);
Console.WriteLine ("He tried " + numOfAttempt + " times to roll a six.");
Console.WriteLine ("The average number of times it took to get a six was " + avrAfter);
Console.ReadKey ();
maybe you need to reset the vars inside the for loop, before the while:
for (int i = 1; i <= 10; i++){
int numOfAttempt = 0;
int Attempt = 0;
int avrBefore = 0;
int avrAfter = 0;
do {//your code
You are diving by ten at the wrong time.
You are dividing by ten even when you haven't done ten iterations.
This code below instead shows the correct average at each iteration.
void Main()
{
Random numGen = new Random ();
int totalAttempts = 0;
for (int i = 1; i <= 10; i++)
{
int attempts = 0;
int attempt = 0;
do {
attempt = numGen.Next (1, 7);
attempts++;
} while (attempt != 6);
totalAttempts+=attempts;
Console.WriteLine ("He tried " + attempts + " times to roll a six.");
Console.WriteLine ("The average number of times it took to get a six was " + (double)totalAttempts / i);
}
}
So you want to know how many times it took to get a six. This is quite simple. You just have to save how many times you rolled the dices and how many times you got a six.
Random numGen = new Random ();
int attempt = 0;
int numOfAttempt = 0;
int numberOfSixes = 0;
int i;
for (i = 0; i < 10; i++) {
do {
attempt = numGen.Next (1, 7);
Console.WriteLine (Attempt);
numOfAttempt++;
} while (Attempt != 6);
numberOfSixes++;
}
Console.WriteLine ("He tried " + numOfAttempt + " times to roll a six.");
Console.WriteLine ("The average number of times it took to get a six was " + (numberOfAttempt/numberOfSixes));
Console.ReadKey ();
I hope you understand my approach.
I would appreciate it if you could elaborate your thought process behind avrBefore,avrAfter and divide by 10. I didn't get that.
You can shorten down the code a lot and get it correct:
Random numGen = new Random();
int numOfAttempt = 0;
for (int i = 0; i < 10; i++)
{
int attempt = 0;
while (attempt != 6)
{
attempt = numGen.Next(1, 7);
Console.WriteLine (attempt );
numOfAttempt++;
}
}
Console.WriteLine("He tried " + numOfAttempt + " times to roll a six.");
Console.WriteLine("The average number of times it took to get a six was " + numOfAttempt / 10.0);
Console.ReadKey();

Categories