while loop in c# - c#

I have this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _121119_zionAVGfilter_Nave
{
class Program
{
static void Main(string[] args)
{
int cnt = 0, zion, sum = 0;
double avg;
Console.Write("Enter first zion \n");
zion = int.Parse(Console.ReadLine());
while (zion != -1)
{
while (zion < -1 || zion > 100)
{
Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n");
zion = int.Parse(Console.ReadLine());
}
cnt++;
sum = sum + zion;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
}
if (cnt == 0)
{
Console.WriteLine("something doesn't make sence");
}
else
{
avg = (double)sum / cnt;
Console.Write("the AVG is {0}", avg);
}
Console.ReadLine(); }
}
}
The problem here is that if in the beginning I enter a negative or bigger than hundred number, I will get this message: "zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n".
If I then meenter -1, this what that shows up instead of the AVG: "Enter next zion, if you want to exit
tap -1 \n."
How can I solve this problem so when the number is negative or bigger than hundred and than tap -1 I will see the AVG an not another message?

You can just add a flag variable and it's done.
namespace _121119_zionAVGfilter
{
class Program
{
static void Main(string[] args)
{
int cnt = 0, zion, sum = 0;
double avg;
int flag = 0;
Console.Write("Enter first zion \n");
zion = int.Parse(Console.ReadLine());
while (zion != -1)
{
while (zion < -1 || zion > 100)
{
Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n");
zion = int.Parse(Console.ReadLine());
if(zion== -1)
flag = 1;
}
cnt++;
sum = sum + zion;
if (flag == 1)
break;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
if (cnt != 0) { }
}
if (cnt == 0)
{
Console.WriteLine("something doesn't make sence");
}
else
{
avg = (double)sum / cnt;
Console.Write("the AVG is {0}", avg);
}
Console.ReadLine();
}
}
}

Just enclose this code that you don't want to be executed in if statement like this
if(zion != -1)
{
cnt++;
sum = sum + zion;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
if (cnt != 0){}
}

Related

Why does my 'averageScore' come out as 0?

why does my code not calculate an average score when entering "-1" into the console? It comes up at 0. It's a part of a loop exercise, so I'm sure there are faster ways to code this. I want to fix it within my current C# comprehension.
Here's the task
using System;
namespace Challenge_Loops1
{
internal class Program
{
static void Main(string[] args)
{
string individualScore = "0";
int scoreCount = 0;
int totalScore = 0;
int individualScoreIntoInt = 0;
while (individualScore != "-1")
{
Console.WriteLine($"Last number was {individualScoreIntoInt}");
Console.WriteLine("Please enter the next score");
Console.WriteLine($"Current amount of entries: {scoreCount}");
Console.WriteLine("Enter '-1' when you're ready to calculaate the average");
individualScore = Console.ReadLine();
if (individualScore.Equals("-1"))
{
Console.WriteLine("--------------------------------------------");
double averageScore = (double)totalScore / (double)scoreCount;
Console.WriteLine($"The average total score is {averageScore}");
if(int.TryParse(individualScore, out individualScoreIntoInt) && individualScoreIntoInt > 0 && individualScoreIntoInt < 21)
{
totalScore += individualScoreIntoInt;
//longer way: totalScore = individualScoreIntoInt + totalScore;
}
else if(individualScoreIntoInt < 0 || individualScoreIntoInt < 20)
{
Console.WriteLine("Enter a score > 0 and < 21");
continue;
}
else
{
Console.WriteLine("Please only enter numbers");
}
}
scoreCount++; // adding the individualscore entered to the count. writing it here so that it's only
//added to the count if it meets the requirements
}
}
}
}
Order of operations was incorrect:
1st validate if it's -1 or not,
2nd parse value and if it's possible perform below operations, if not drop error.
This was logic issue, rather than code itself.
You had added iteration despite exceptions, you didn't include possibility of 21 etc.
namespace Challenge_Loops1
{
internal class Program
{
static void Main(string[] args)
{
string individualScore = "0";
int scoreCount = 0;
int totalScore = 0;
int individualScoreIntoInt = 0;
while (individualScore != "-1")
{
Console.WriteLine($"Last number was {individualScoreIntoInt}");
Console.WriteLine("Please enter the next score");
Console.WriteLine($"Current amount of entries: {scoreCount}");
Console.WriteLine("Enter '-1' when you're ready to calculaate the average");
individualScore = Console.ReadLine();
if (individualScore.Equals("-1"))
{
Console.WriteLine("--------------------------------------------");
double averageScore = (double)totalScore / (double)scoreCount;
Console.WriteLine($"The average total score is {averageScore}");
}
else if (int.TryParse(individualScore, out individualScoreIntoInt))
{
if(individualScoreIntoInt > 0 && individualScoreIntoInt <= 21)
{
totalScore += individualScoreIntoInt;
scoreCount++;
}
//as mentioned in comment else here would also work, it's unnecessary to add any other validation.
else if (individualScoreIntoInt < 0 || individualScoreIntoInt > 21)
{
Console.WriteLine("Enter a score > 0 and < 21");
}
}
else
{
Console.WriteLine("Please only enter numbers");
}
}
}
}
}

C# - I need to add code! Guess the number

I have written a guess the number game between 1-100.
This is my code..
class Program
{
static void Main(string[] args)
{
while (true)
{
int randno = Newnum(1, 101);
int count = 1;
while (true)
{
Console.Write("Guess a number between 1 and 100, or press 0 to quit: ");
int input = Convert.ToInt32(Console.ReadLine());
if (input == 0)
return;
else if (input < randno)
{
Console.WriteLine("Unlucky, that number is too low - have another go!");
++count;
continue;
}
else if (input > randno)
{
Console.WriteLine("Unlucky, that number is too high - have another go!");
++count;
continue;
}
else
{
Console.WriteLine("Well done - you guessed it! The number was {0}.", randno);
Console.WriteLine("It took you {0} {1}.\n", count, count == 1 ? "attempt" : "attempts to guess it right");
break;
}
}
}
}
static int Newnum(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
}
How can I edit it so that if a user gets close to the number, say within 5 numbers, they are greeted with a message saying they're close?
You can use Math.Abs:
int diff = Math.Abs(input - randno);
if(diff <= 5)
{
// say him that he's close
}

C#, integer entered not between two numbers [closed]

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 6 years ago.
Improve this question
I have to make it to when an integer entered that is not between 0 and 10 then it will display a message, whatever the number entered is not between 0 and 10. Also when -99 is entered it will exit the program. I have tried the while statement and nothing seems to be working.
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = ReadLine();
if (int.TryParse(inValue, < 1 && > 10) == false)
WriteLine("Integer entered, {0}, is not between 0 and 10.");
if (int.TryParse(inValue, out score[i])
== false)
WriteLine("\n\tInvalid data - re-enter homework score: ");
}
You can't put the "greater than 10, less than 1" condition inside the TryParse() method, it does not support that. So check the condition separately. Also no need to check if (something == false) because that's identical to if (!something). I changed your ReadLine/Write/WriteLine's to have Console. prepended so it works on my system. You will need a while loop for the "please re-enter homework score" to work as you intend, but the code here does fix your original problem..
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Console.Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = Console.ReadLine();
if (int.TryParse(inValue, out score[i]))
{
if (score[i] == 99)
{ Environment.Exit(0); }
bool between0and10 = score[i] <= 10 && score[i] >= 0;
if (!between0and10)
{ Console.WriteLine("Integer entered, {0}, is not between 0 and 10."); }
}
else
{ Console.WriteLine("\n\tInvalid data - re - enter homework score: "); }
}
Try this:
int total = 0;
double avg;
string inValue;
int[] score = new int[8];
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = ReadLine();
if (!int.TryParse(inValue, out score[i]))
{
WriteLine("\n\tInvalid data, StackOverflow did your homework! - re-enter homework score: ");
}
else if (score[i] < 1 || score[i] > 10)
{
WriteLine("Integer entered, {0}, is not between 0 and 10.");
}
}
int[] score = new int[8];
string sVal;
int val;
int i = 0;
while (i < score.Length)
{
Console.WriteLine("Please enter homework score [0 to 10] (-99 to exit):");
sVal = Console.ReadLine();
if (int.TryParse(sVal, out val))
{
//if quit
if (val == -99)
break;
//if valid range
if (val >= 0 && val <= 10)
{
score[i] = val;
i++;
}
else //invalid input range
Console.WriteLine("Invalid data - re-enter homework score:");
}
else //not a number
Console.WriteLine("Invalid data - re-enter homework score:");
}
int total = 0;
double avg;
int parsedScore;
//this bool will tell us if the data entered is valid
bool isValid;
int[] score = new int[8];
string inValue;
// prompt user for initial values
for (int i = 0; i < score.Length; i++)
{
Console.Write("Please enter homework score [0 to 10] (-99 to exit): \n", i + 0);
inValue = Console.ReadLine();
//here we check that the data entered is valid and set our bool to the result
isValid = int.TryParse(inValue, out parsedScore);
if (isValid && parsedScore == -99) //check first if it is -99 and then exit if need be.
{
System.Environment.Exit(0);
}
//if it is not valid we are going to prompt them to re-enter their number
if(!isValid || (parsedScore < 0 && parsedScore > 10))
{
Console.WriteLine("Integer not entered or {0}, is not between 0 and 10.", inValue);
i--; //we decrement i in order to let them re-enter at this index
}
else
{
//valid number, do logic here.
}

Highest Common Factor C#

I have the current coding and I feel as if it is close to what I need but I can't seem to get it to work for what I want. I am trying to get it to output the highest common factor of the two numbers entered.
i = myInt;
{
if (myInt % i == 0 && myInt2 % i == 0)
{
Console.Write("Your GCF is...");
Console.Write("{0} ", i);
Console.ReadLine();
}
else
i--;
goto;
}
As others said in comments, you should really avoid goto statements because they are bad practice, especially when you are learning your college course of programming (that usually should conform to structural programming). Instead use while loop (or any other) with two conditions as you can see in the example. Also, I think that you should start your search from the smaller number (the first entered does not need to be smaller one) which is a little improvement in terms of performance. This is the code:
static void Main(string[] args)
{
string myInput;
int myInt;
string myInput2;
int myInt2;
int i;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
Console.Write("Please enter another number: ");
myInput2 = Console.ReadLine();
myInt2 = Int32.Parse(myInput2);
i = myInt > myInt2 ? myInt2 : myInt;
bool found = false;
while(!found && i>0)
{
if (myInt % i == 0 && myInt2 % i == 0)
{
Console.Write("Your GCF is...");
Console.Write("{0} ", i);
Console.ReadLine();
found = true;
}
else
i--;
}
}
EDIT: I included the other possible solution thanks to #Servy
bool found = false;
for( i = Math.Min(myInt, myInt2); !found && i>0; i--)
{
if (myInt % i == 0 && myInt2 % i == 0)
{
Console.Write("Your GCF is...");
Console.Write("{0} ", i);
Console.ReadLine();
found = true;
}
}
{
label:
if (myInt % i == 0 && myInt2 % i == 0)
{
Console.Write("Your GCF is...");
Console.Write("{0} ", i);
Console.ReadLine();
}
else
i--;
goto label;
}
will do. However, this is a very bad idea. Rather learn how to use while.

Output a sequence of ten numbers to console

The user must provide the starting point and indicate whether the sequence should be ascending or descending. Thus far it starts counting and never stops. How do I make it stop after increment it by 10. Would I use an if statement to let the user choose to make it ascending or descending?
class Program
{
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); val++)
Console.WriteLine(val);
Console.ReadLine();
}
}
It never stops because you increase val, and i will always be less than val + 10 (you never increase i). You should increase i instead, and use i inside the loop.
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
Console.ReadLine();
}
For the ascending vs. descending part, you also need to take a second input from the user and if he choose descending, make a loop that checks if i >= (val - 10), and that goes i-- each iteration instead.
using System;
using System.Linq;
class Sample {
static void Main(){
const char down = '-';
Console.Write("Please enter a number! n[{0}]:", down);
string input = Console.ReadLine();
char ch = input.Last();
int diff = (ch == down) ? -1 : 1;
int val = Int32.Parse(input.TrimEnd(down));
for(var i = 1; i <= 10; i++, val += diff)
Console.WriteLine(val);
}
}
DEMO
Please enter a number! n[-]:10-
10
9
8
7
6
5
4
3
2
1
Please enter a number! n[-]:5
5
6
7
8
9
10
11
12
13
14
Change to:
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
Console.ReadLine();
}
static void Main(string[] args)
{
int val, isDecrement;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please enter 1 to go Descending order!");
isDecrement = Int32.Parse(Console.ReadLine());
if(isDecrement ==1)
{
for (int i = val; i >= (val - 10); i--)
Console.WriteLine(i);
}
else
{
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
}
Console.ReadLine();
}

Categories

Resources