C# Keeping sentinel value out of my array [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This code works when I enter 10 values. If I enter less my sentinel value is added. I'd like that to stop, as well as being able to manipulate my array length so I don't get however many 0's left when entering less than 10.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace IntegerStatistics
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[10];
int arrayCount, high, low, sum;
double avg;
arrayCount = FillArray(numbers);
Statistics(numbers, arrayCount, out high, out low, out sum, out avg);
for (int x = 0; x < numbers.Length; ++x)
Write("{0, 4}", numbers[x]);
WriteLine();
WriteLine("The array has {0} values", arrayCount);
WriteLine("The highest value is {0}", high);
WriteLine("The lowest value is {0}", low);
WriteLine("The sum of the array is {0}", sum);
WriteLine("The average is {0}", avg);
}
private static int FillArray(int[] numbers)
{
const int QUIT = 999;
string enterNum;
int stop;
int count = 0;
int addNum = 0;
stop = numbers.Length - 1;
while((addNum != QUIT) && (count <= stop))
{
Write("Enter a number or 999 to exit: ");
enterNum = ReadLine();
while (!int.TryParse(enterNum, out numbers[count]))
{
WriteLine("Error");
Write("Enter a number or 999 to exit: ");
enterNum = ReadLine();
}
numbers[count] = Convert.ToInt32(enterNum);
addNum = numbers[count];
++count;
}
return count;
}
private static int Statistics(int[] numbers, int arrayCount, out int high, out int low, out int sum, out double avg)
{
high = numbers.Max();
low = numbers.Min();
sum = numbers.Sum();
avg = numbers.Average();
return arrayCount;
}
}
}

First, let's fix your code, because it is very simple: rather than using numbers.Length in the Main, use arrayCount. This is something that you already have, and it will stop Main from showing zeros at the end.
I'd like [...] to manipulate my array length
Although .NET provides a way to resize an array, this is not something you should be doing in general, because your code quickly becomes hard to read.
A better solution to this problem would be to return a properly sized array from FillArray. However, the best solution is to switch to using List<T>, which are allowed to grow and shrink as needed.

I have modified your original program to use a List<int> (good practice) instead of an array of integers which is dynamically re-sized (no so good practice, in general).
class Program
{
static void Main(string[] args)
{
// Use a collection instead of an array, as length is as of yet unknown:
List<int> numbers;
int high, low, sum;
double avg;
numbers = FillArray();
Statistics(numbers, out high, out low, out sum, out avg);
foreach (var number in numbers)
{
Console.Write("{0, 4}", number);
}
Console.WriteLine();
Console.WriteLine("The array has {0} values", numbers.Count);
Console.WriteLine("The highest value is {0}", high);
Console.WriteLine("The lowest value is {0}", low);
Console.WriteLine("The sum of the array is {0}", sum);
Console.WriteLine("The average is {0}", avg);
Console.ReadKey();
}
private static List<int> FillArray(int maximum = 10)
{
const int QUIT = 999;
int count = 0;
int addNum = 0;
var list = new List<int>();
while (count <= maximum)
{
Console.Write("Enter a number or 999 to exit: ");
if (!int.TryParse(Console.ReadLine(), out addNum))
{
Console.WriteLine("Error");
continue;
}
if (addNum == QUIT)
{
break;
}
list.Add(addNum);
count++;
}
return list;
}
private static void Statistics(List<int> numbers, out int high, out int low, out int sum, out double avg)
{
high = numbers.Max();
low = numbers.Min();
sum = numbers.Sum();
avg = numbers.Average();
}
}
I also noticed you were including your "escape" value of 999 with your collection of numbers. I corrected this so that 999 is not included with the calculated average (I am guessing that was your intention).

Similar to #Dave. Allows for a value of 999. There's no exception handling, tho...
class Program
{
private static string _STOP = "STOP";
private static int _MAX_SIZE = 10;
static void Main(string[] args)
{
List<int>numbers = FillList();
foreach(int number in numbers)
Console.Write("{0, 4}", number);
Console.WriteLine();
Console.WriteLine("The list has {0} values", numbers.Count);
Console.WriteLine("The highest value is {0}", numbers.Max());
Console.WriteLine("The lowest value is {0}", numbers.Min());
Console.WriteLine("The sum of the array is {0}", numbers.Sum());
Console.WriteLine("The average is {0}", numbers.Average());
Console.ReadKey();
}
private static List<int> FillList()
{
List<int> numbers = new List<int>();
int value;
int count = 0;
do
{
Console.Write("Enter a number or {0} to exit: ", _STOP);
string line = Console.ReadLine();
if (line == _STOP)
break;
if (int.TryParse(line, out value))
{
numbers.Add(value);
count++;
}
else
{
Console.WriteLine("Error reading number.");
}
} while (count < _MAX_SIZE);
return numbers;
}
}

Related

Making a word into a sentinel value in C#

I am currently working on a program that is a loop with a sentinel value that asks the user to enter a number or enter -99 to end the program and it runs perfectly. If I were to change that -99 to just the word "Quit" is there a certain parameter that I would have to put? For example, if I want to use a letter, I know that I could use:
char (undefined parameter) = 'A'
But how would I do this with a word? When I simply try to change the value of -99 to Quit, I receive an error as expected.
using System;
class Program {
public static void Main (string[] args) {
int sum = 0;
int counter = 0;
int max = Int32.MinValue;
int min = Int32.MaxValue;
bool keepGoing = true;
while(keepGoing) {
Console.WriteLine("Please enter a number or enter -99 to stop the program:");
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
sum += number;
if (number >= max) {
max = number;
}
if (number <= min) {
min = number;
}
}
}
double average = (double) sum / counter;
Console.WriteLine($"{counter} numbers were entered.");
Console.WriteLine("The average is:" + average);
Console.WriteLine("The sum is:" + sum);
Console.WriteLine("The maximum value is:" + max);
Console.WriteLine("The minimum value is:" + min);
}
}
It's difficult to store "Quit" in an int, so the root of your problem is that you have no separation between pulling the string from the console and converting it to an int:
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
If you did have a separation, it becomes possible:
string input = Console.ReadLine();
if (input == "Quit"){
keepGoing = false;
} else {
int number = Convert.ToInt32(input);
counter++;

Modulus operator with random numbers

What I want to do is have random numbers be generated and take those random numbers and put them through a modulus operator. And I want it to ask the user for the answer they think it is and then they will be told if it is right or wrong. This is what I have.
Random rand = new Random();
int minA;
int maxA;
int minB;
int maxB;
int usersAnswer;
Console.WriteLine("what is the minimum value: ");
Int32.TryParse(Console.WriteLine(), out minA);
Console.WriteLine("what is the minimum value: ");
Int32.TryParse(Console.WriteLine(), out maxA);
Console.WriteLine("what is the minimum value: ");
Int32.TryParse(Console.WriteLine(), out minB);
Console.WriteLine("what is the minimum value: ");
Int32.TryParse(Console.WriteLine(), out maxB);
Console.WriteLine("What is the result of {0} % {1}? ", rand.Next(minA, maxA), rand.Next(minB, maxB));
Int32.TryParse(Console.ReadLine(), out usersAnswer);
answer = //directly implementing the random numbers generated with modulous operator)
if(userAnswer == answer)
{
Console.WriteLine("{0} is correct", answer);
}
else
{
Console.WriteLine("Good try, but no: {the random number} % {the other random number} = {0}", not sure, not sure, answer)
}
So what I want to know is how I can directly implement the random numbers already generated from "Console.WriteLine("What is the result of {0} % {1}? ", rand.Next(minA, maxA), rand.Next(minB, maxB));" into a modulus operator equation and get the answer.
I hope this all made sense
You should store your 2 random numbers as new variables in your class:
int RandomOne;
int RandomTwo;
assign them further down
RandomOne = rand.Next(minA, maxA);
RandomTwo = rand.Next(minA, maxA);
and then refer to them in your messaging. Something like:
Console.WriteLine($"What is the result of {RandomOne} % {RandomTwo}?");
Your code have some promblem:
Remember to fix your instructions text
Somthimes, you use writeline(),but readline() actually
You should handle that something might be going wrong, check comment out
Try it
static void Main(string[] args)
{
Random rand = new Random();
int minA, maxA;
int minB, maxB;
int userAnswer;
Console.WriteLine("what is the minimum A: ");
if (!Int32.TryParse(Console.ReadLine(), out minA)) { return; } //If something going wrong, you should handle it.
Console.WriteLine("what is the maximum A: ");
if (!Int32.TryParse(Console.ReadLine(), out maxA)) { return; }
Console.WriteLine("what is the minimum B: ");
if (!Int32.TryParse(Console.ReadLine(), out minB)) { return; }
Console.WriteLine("what is the maximum B: ");
if (!Int32.TryParse(Console.ReadLine(), out maxB)) { return; }
if (minA > maxA) { exchange(ref minA, ref maxA); } //User might have typo,and this is one way to fix it.
if (minB > maxB) { exchange(ref minB, ref maxB); }
int rndA = rand.Next(minA, maxA),
rndB = rand.Next(minB, maxB); //You should restore the random result, or lost it
int result;
try
{
result = calcMod(rndA, rndB); //Directly implementing the random numbers generated with modulous operator
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return;
}
Console.WriteLine($"What is the result of {rndA} % {rndB}? ");
Int32.TryParse(Console.ReadLine(), out userAnswer);
if (userAnswer == result)
{
Console.WriteLine("{0} is correct", result);
}
else
{
Console.WriteLine($"Good try, but no: {rndA} % {rndB} = {result}");
}
Console.Write("\nPress Any key to leave.");
Console.ReadKey();
}
//Calculate mod result
static int calcMod(int i1, int i2)
{
try
{
return i1 % i2;
}
catch (Exception e)
{
throw e;
}
}
//Swap number
static void exchange(ref int i1, ref int i2)
{
int tmp;
tmp = i1;
i1 = i2;
i2 = tmp;
}

How find average of numbers(by input) and also count numbers

I mean how to count and sum input numbers until receive "end".
thanks !
And also how to find out input is number or letter in c#?
class Program
{
static void Main(string[] args)
{
int n = 0;
int sum = 0;
string inp;
do
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num= Convert.ToInt16(inp);
sum = sum + num;
n++;
} while (too == "end");
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
}
}
I would suggest you use a normal while loop and also add validation to check to integer input.
For the while loop you want to loop until the input is not equal to "end":
while(inp != "end")
For the validation, you can use int.TryParse method:
int num = 0;
if (int.TryParse(inp, out num)) { }
Here is a modified example of your code:
int n = 0;
int sum = 0;
string inp = null;
while(inp != "end")
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num = 0;
if (int.TryParse(inp, out num))
{
sum = sum + num;
n++;
}
}
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
// A list to hold all of the numbers entered
List<int> numbers = new List<int>();
// Will hold the inputted string
string input;
// This needs to be outside the loop so it's written once
Console.Write("Numbers: " + Environment.NewLine);
// Keep going until we say otherwise
while (true)
{
// Get the input
input = Console.ReadLine();
// Will hold the outcome of parsing the input
int number = -1;
// Check to see if input was a valid number
bool success = int.TryParse(input, out number);
// If it was a valid number then remember it
// If ANY invalid or textual input is detected then stop
if (success)
numbers.Add(number);
else
break;
}
// Write the count and average
Console.WriteLine("Count:" + numbers.Count);
Console.WriteLine("Average:" + numbers.Average());
Console.ReadLine();
Input:
Numbers:
1
2
3
4
5
Output:
Count: 5
Average: 3
The only thing here a little different to what you specified is ANY invalid or textual entry causes it to finish, not just typing the word "end", although that obviously works too.

Calculating The Factorial of a Number

When I enter the number 6 to calculate its factorial, it returns 30 (which is wrong).
Why is my program producing incorrect output?
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
int counter, number, fact;
Console.WriteLine("Please enter the number you wish to factorize");
number = int.Parse(Console.ReadLine());
fact = number;
for (counter = number - 1; counter >= 1; counter--)
{
fact = fact * counter;
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, fact);
Console.ReadLine();
}
}
}
}
You look new to programming, or least C#, so just for fun, this will blow your mind:
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the number you wish to factorize");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorial(number));
Console.ReadKey(true);
}
static int Factorial(int n)
{
if (n >= 2) return n * Factorial(n - 1);
return 1;
}
}
}
No loops anywhere, and the function calls itself.
You can also do it like this:
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the number you wish to factorize");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorial(number));
Console.ReadKey(true);
}
static int Factorial(int n)
{
return Enumerable.Range(1, n).Aggregate((i, r) => r * i);
}
}
}
Which is all kinds of messed up :) ...but it does get the significant work down to a single line of code.
Then there's my personal favorite, the infinite enumerable:
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the number you wish to factorize");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorials().Skip(number-1).First());
Console.ReadKey(true);
}
static IEnumerable<int> Factorials()
{
int n = 1, f = 1;
while (true) yield return f = f * n++;
}
}
}
The program is paused waiting for some input. You need to move the second Console.ReadLine() out of the loop. And likely the Console.WriteLine() unless you want to see each iteration completing.
You need to move two lines out from the for loop. The modified code look like this.
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
int counter, number, fact;
Console.WriteLine("Please enter the number you wish to factorize");
number = int.Parse(Console.ReadLine());
fact = number;
for (counter = number - 1; counter >= 1; counter--)
{
fact = fact * counter;
}
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, fact);
Console.ReadLine();
}
}
}
There are lots of ways to calculate Factorial. You can also do it by creating a recursive function. Google can help you a lot on these basic things.
Thanks!
int n = 4, fact = n;
for (int i = n; i > 1; i--)
{
fact *= (i - 1);
}
Console.WriteLine(fact);
Console.ReadLine();
why are You printing the message inside the loop.put it outside the loop
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, fact);
using System;
namespace factorial
{
class Program
{
static void Main(string[] args)
{
int fact = 1;
Console.Write("Enter a number to find factorial:");
int n = int.Parse(Console.ReadLine());
for (int i = n; i > 0; i--)
{
fact = fact * i;
}
Console.Write("Factorial of" + n +"is :"+fact);
Console.ReadLine();
}
}
}
import java.util.Scanner;
public class Chapter5ProblemTwelve
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
int number;
int factor = 1;
int counter;
System.out.print("Enter a positive integer to display the factorial number: ");
number = keyboard.nextInt();
//If the number entered is less then zero. The program will tell the user to enter a positive number
if (number <= 0)
{
System.out.println("Please enter a postive number and rerun the program again.");
}
else
{
// Math work preformed if user enters a postive number. Example if user enters 4.
// 1*1 = 1, 1*2 = 2,1*3 = 3, 1*4 = 4, The program will multiple all the answers together 1*2*3*4 = 24
for (counter = 1; counter <= number; counter++)
{
factor = factor * counter;
}
//display
System.out.println("The factorial number of " + number + " is: " + factor);
}
}
}
using System;
namespace septtwenty
{
class Program
{
static void Main(string[] args)
{
int i, number, fact;
System.Console.WriteLine("Enter the Number");
number = int.Parse(Console.ReadLine());
fact = number;
for (i = number -1; i>=1; i--)
{
fact = fact * i;
}
System.Console.WriteLine("\nFactorial of Given Number is: "+fact);
Console.ReadLine();
}
}
}

Sum integers using a loop c#

I am new to programming and I think I have confused myself I'm trying to make a loop that asks users for integers when the user inputs a integer greater than 100 then the console displays the amount of integers the user has input and the sum of these integers. I know it's basic but I can't figure where I went wrong.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum1, strNum2;
int num1, num2;
int i = 0;
int sum =0 ;
Console.WriteLine("Please enter a integer between 1 and 100"); // asks for user input
strNum1 = Console.ReadLine();
num1 = int.Parse(strNum1);
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum2 = Console.ReadLine();
num2 = int.Parse(strNum2); //input is stored as num2
sum = num2; //store num2 in sum
i++;
if (num2 >= 100) // if num2 int is greater than 100
{
sum = (num1 +num2 +sum); // do calculation
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
while (i < 100);
}
}
}
any help would be appreciated thanks everyone!
You're on the right track... a couple of things:
Do... While is used when you always want to run through the block at least once, so your first 'get' from the user can be inside the block. You can code whatever you want to happen after the condition fails right after the block, instead of checking the same condition inside it.
Make sure if you're simply using Parse that you wrap it in a try...catch, because your user could type in anything (not just numbers). Personally I usually use TryParse instead.
Finally, make sure you're comparing to the correct variable. Checking that i < 100 will keep looping until 100 numbers have been entered; you want to compare the user's input instead.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string prompt = "Please enter {0} integer between 1 and 100";
string strNum;
int num = 0;
int i = 0;
int sum =0 ;
do //ask once and repeat while 'while' condition is true
{
string pluralPrompt = i > 0 ? "another" : "an";
prompt = string.Format(prompt,pluralPrompt);
Console.WriteLine(prompt); // asks for user input
strNum = Console.ReadLine();
if (!Int32.TryParse(strNum, out num)) //input is stored as num
{
// warn the user, throw an exception, etc.
}
sum += num; //add num to sum
i++;
}
while (num < 100);
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
}
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum;
int num;
int i = 0;
int sum = 0;
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum = Console.ReadLine();
if (int.TryParse(strNum, out num)) //input is stored as num2
{
if (num < 101)
{
i++;
sum += num;
continue;
}
else
{
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
break;
}
}
}
while (i < 100);
}
}

Categories

Resources