Declaring a variable in a loop and using it outside? - c#

I'm very new to c# and am trying to run this bit of code. I'm trying to make it so the question "How many miles were you able to travel in week {number}?" is repeated 4 times and this: int totalaverage = Convert.ToInt32(Console.ReadLine()); is repeated 4 times and each time added up. Then I need to use it outside the loop to make the finalaverage. Is there any way to do this?
using System;
namespace HelloWorld
{
class Program
{
static void Main()
{
Console.WriteLine("Whats your name?");
string input = Console.ReadLine();
Console.WriteLine($"Hi {input}");
Console.WriteLine("What were you hoping to hit for your average?");
int average = Convert.ToInt32(Console.ReadLine());
int number = 1;
while (number < 5)
{
Console.WriteLine($"How many miles were you able to travel in week {number}?");
int totalaverage = Convert.ToInt32(Console.ReadLine());
number = number + 1;
}
int finalaverage = totalaverage / 4;
Console.WriteLine($"{input} you have averaged {finalaverage} miles per week");
if (finalaverage >= average)
{
Console.WriteLine("Congratulations you have met your target");
}
else
{
Console.WriteLine("Sorry you have not met your target");
}
}
}
}

You need to declare your variable outside of your loop, in order to use it outside of your loop, something like this:
int number = 1;
int totalaverage = 0;
while (number < 5)
{
Console.WriteLine($"How many miles were you able to travel in week {number}?");
totalaverage = Convert.ToInt32(Console.ReadLine());
number = number + 1;
}
int finalaverage = totalaverage / 4;
Console.WriteLine($"{input} you have averaged {finalaverage} miles per week");
if (finalaverage >= average)
{
Console.WriteLine("Congratulations you have met your target");
}
else
{
Console.WriteLine("Sorry you have not met your target");
}

Related

Trouble with C# console code. Trying to get a while loop to average 3 test scores. Final product is only using the first number entered in while loop

Struggling with understanding the while loop. I'm just starting to learn programming. While testing the code, it appears as if only the second number entered gets processed into the final answer.
static void Main(string[] args)
{
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = Double.Parse(input);
double sum = 0.0;
int counter = 1;
int total = 3;
while (counter < total)
{
sum = sum + value;
counter = counter + 1;
Console.WriteLine("Enter another test score");
input = Console.ReadLine();
value = Double.Parse(input);
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
}
You need your while loop to run three times so start the counter from 0 instead of 1.
Within the loop you can ask for the test scores and add them to the sum and then increment the counter.
double sum = 0.0;
int counter = 0;
int total = 3;
while (counter < total)
{
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = double.Parse(input);
sum += value;
counter++;
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
Or like this if you need the question to be different, you can ask the question outside of the loop and save the result to the sum variable. Since we have already asked the question once we can make the counter start at 1 instead of 0.
double sum = 0.0;
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = double.Parse(input);
sum = sum + value;
int counter = 1;
int total = 3;
while (counter < total)
{
Console.WriteLine("Enter another test score");
input = Console.ReadLine();
value = double.Parse(input);
sum += value;
counter++;
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
You use Wrong number
total is 3, but you need repeat 3 times calculate
counter 1 calculate clear
counter 2 calculate clear
but counter 3 is while false.
you need to fix counter <=total or counter started 0

Program to guess number gets incredibly slow

So, I decided to have some fun and make a program that will come up with a number and you have to guess it with it telling you if you're too high/too low. However, I decided it would be more fun if the computer could come up with the random numbers itself.
I use a simple method here which basically has the program check if a value is in an array, and if it is, come up with another random number. And when a number is too high, start from the size of how large the number can be and go down to that number (that way if it's too high of a number, it never guesses that high or higher again).
So, this works great for small numbers. I think when doing a number like 1,000 or something, it guessed it within 15 tries. However, when I did a 10,000,000 (I know, it's a bit extreme, but I wanted to see C#'s power since I'm fairly new to the language).
The program got about 10 guesses in and it started slowing down incredibly. I had put in a 250ms sleep timer to make it look more like it was guessing (since it is instant for things like 1,000 or 10,000), but when taking it out, it still slowed down. I think this is probably because if it guesses a number like 3 million, it has to add 7 million values to an array (I'm using a List so that it has an "infinite" value).
So what exactly can I do at this point? I want it to be able guess big numbers, but it doesn't really seem possible at this point. How could I do this?
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Program {
class Program {
static void Main(string[] args) {
Random random = new Random();
int selectedNumber = random.Next(1, 101);
int maxNumber;
int guessNumber = 0;
int inputNumber = 0;
// Intro
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("Welcome to the High Low - Computer version program!");
System.Threading.Thread.Sleep(4000);
Console.WriteLine("\n--------------------------------------------------------");
Console.ForegroundColor = ConsoleColor.DarkYellow;
// This way the computer guesses rather than you
char who = 'C';
Console.Write("\nHow high do you want the computer's number to be max > ");
maxNumber = Convert.ToInt32(Console.ReadLine());
List<int> guessedNumbers = new List<int>();
selectedNumber = random.Next(1, maxNumber);
do {
// System.Threading.Thread.Sleep(250);
Console.ForegroundColor = ConsoleColor.DarkYellow;
if (who == 'M') {
Console.Write("\nPlease enter your guess > ");
guessNumber = Convert.ToInt32(Console.ReadLine());
}
else {
while (true) {
guessNumber = random.Next(1, maxNumber);
if (!(guessedNumbers.Contains(guessNumber))) {
guessedNumbers.Add(guessNumber);
inputNumber++;
break;
}
}
Console.WriteLine("Please enter your guess > {0}", guessNumber);
}
Console.ForegroundColor = ConsoleColor.DarkGreen;
if (guessNumber < selectedNumber) {
Console.WriteLine("\nYou're guessing too low!\n");
for (int i = 0; i < guessNumber; i++) {
guessedNumbers.Add(i);
inputNumber++;
}
}
else if (guessNumber > selectedNumber) {
Console.WriteLine("\nYou're guessing too high!\n");
for (int i = maxNumber; i > guessNumber; i--) {
guessedNumbers.Add(i);
inputNumber++;
}
}
} while (guessNumber != selectedNumber);
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("\nCongratulations! You correctly guessed that {0} is the computer's number!", selectedNumber);
Console.ReadKey();
}
}
}
Edit: I think I'll try a way to make it so that it only adds the numbers that are higher or lower if they aren't already in there, to keep from having duplicate numbers.
The way you're trying to find the number using the computer's power isn't really efficient, why don't you just change the ranges of the possible guessing numbers based on if the previously guessed number is higher or lower than the correct number like so:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Highest number:");
int maxNumber = Convert.ToInt32(Console.ReadLine());
Random rand = new Random();
int correctNumber = rand.Next(0, maxNumber);
Console.WriteLine("Trying to guess number now..");
int guessedNumber = 0;
int lowBound = 0;
int highBound = maxNumber;
int guesses = 0;
while(guessedNumber != correctNumber)
{
guessedNumber = rand.Next(lowBound, highBound);
if(guessedNumber > correctNumber)
{
highBound /= 2;
lowBound /= 2;
}
else if(guessedNumber < correctNumber)
{
lowBound *= 2;
highBound *= 2;
}
++guesses;
}
Console.WriteLine($"Took me {guesses} guesses.");
Console.ReadKey();
}
}
This takes less than a second for 10,000,000 entries on my machine.
for (int i = 0; i < guessNumber; i++)
{
guessedNumbers.Add(i);
inputNumber++;
}
Everytime you enter these types of loops, you add 'guessnumber' items to the list, possibly millions.
Consider re-reading your code and understanding what it does.
Also, you should consider encapsulating your code to avoid making a behemoth of your main()
Another way is to use a Binary Search approach to guess the number and avoid the additional overhead caused by writing and searching for guess values.
This should run in O(log n).
int minGuess = 0;
int maxGuess = 1000000;
Random random = new Random();
int selectedNumber = random.Next(minGuess, maxGuess);
Console.WriteLine($"Selected number: {selectedNumber}");
int guess;
int count = 0;
do
{
count++;
guess = (minGuess + maxGuess) / 2;
Console.WriteLine($"Guess: {guess}");
if (selectedNumber < guess)
maxGuess = guess - 1;
else
minGuess = guess + 1;
} while (guess != selectedNumber);
Console.WriteLine($"Guessed it in {count} tries");
Console.ReadLine();

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);
}
}

Using "if" statement to remove min/max user input data

I'm new to C#, well, coding in general.
I have done fairly well by myself to date, in this introduction course I am taking, but I ran into a road bump.
I am trying to figure out how to code a if statement that will run inside a loop to analyze 5 different ints as they are entered and to put the max int and min int seperatly so that I can ue the remaining three ints to make a calculation.
To be exact, validate user input and remove the min/max user input to average the remaining three.
PS, I tried an array but for some reason it wasn't working well. I don't have the code as I'm at work right now though. I was told in a lecture that an if statement should be used but arrays are possible too.
Thank you for your time and any possible answers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city, value;
double rating, avg = 0;
double[] array1 = new double[5];
double max = 0;
double min = double.MaxValue;
double score, totalScore = 0;
//get basic information
do
{
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
value = Console.ReadLine();
score = Convert.ToDouble(value);
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
array1[s] = Convert.ToDouble(score); //----this line keeps throwing an exception
}
Console.ReadLine();
//calculate totalScore by dropping min/max scores and averaging them times dive rating
foreach (int i in array1)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
totalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", totalScore);
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
}
}
}
or you can go list route and
List<int> apples = new List<int>();
apples.Add(31);
apples.Add(34);
apples.Add(100);
apples.Add(57);
apples.Add(1);
int min = apples.Min();
int max = apples.Max();
apples.Remove(min);
apples.Remove(max);
decimal average = (decimal)(apples.Sum()) / apples.Count;
Not sure about your question... You want to know, the max and min about 5 values, and the avarage about the three others...
int[] n = { 4, 7, 29, 3, 87 };
int max = 0;
int min = int.MaxValue;
double avg = 0;
foreach (int i in n)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
avg = avg / n.Count - 2;
try this code:
int[] a = new int[5];
int minpos;
int maxpos;
int min = Int32.MaxValue;
int max = a[0];
int temp = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" Enter number " + (i + 1));
Int32.TryParse(Console.ReadLine(), out temp);
a[i] = temp;
//Decision Making Logic
if (min > temp)
{
min = temp;
minpos = i;
}
if (max < temp)
{
max = temp;
maxpos = i;
}
}
//At the end of this loop you will see that minpos contains the index of minimum element
//and maxpos contains index of maximum element,values in remaining indeces contain elements that are neither max or min in that //collection
Thanks guys, it appears I needed a good night of sleep. Thanks a ton for all these helpful answers as I'm sure I will be delving into those methods soon and it will be good to be able to get a head start on them. Here is my code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city;
double rating, avg = 0;
double max = 0;
double min = 10;
double score, value = 0, totalScore = 0, finalScore = 0;
//get basic information
do
{
Console.WriteLine("\n");
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
score = Convert.ToDouble(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
if (score > max)
max = score;
if (score < min)
min = score;
totalScore = score + totalScore;
}
Console.ReadLine();
\\Calculate values
value = totalScore - max - min;
avg = value / 3;
finalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", finalScore);
Console.WriteLine("\n");
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
Console.WriteLine("\n");
}
}
}

Categories

Resources