Positive Or Negative - If Statements - c#

Alright so in the book im reading its telling me to write a program that asks the user for two multiplication numbers and then it will print out whether the result should be positive or negative.
The rule is that i cannot take two numbers and multiply them, and then check if the result is greater than or less than zero. Instead if the two numbers have the same sign (both positive or both negative) the result is positive. If they have different signs, the result is negative.
I did it like this ( also i added int anresult = first * second; <- do i need that?) because if i remove it it still works, but the book wants it in multiplication. so im not sure if that piece of code is doing anything at all
Console.WriteLine("Enter First Nuumber: ");
string firstAsString = Console.ReadLine();
int first = Convert.ToInt32(firstAsString);
Console.WriteLine("Enter Second Nuumber: ");
string secondAsString = Console.ReadLine();
int second = Convert.ToInt32(secondAsString);
int anresult = first * second;
if (first >= 0 && second > 0 || first < 0 && second < 0)
Console.WriteLine("Your number will be Positive");
else
Console.WriteLine("Your number will be negative");
Console.ReadLine();
But the book did it like this
Console.WriteLine("Enter First Nuumber: ");
string firstAsString = Console.ReadLine();
int first = Convert.ToInt32(firstAsString);
Console.WriteLine("Enter Second Nuumber: ");
string secondAsString = Console.ReadLine();
int second = Convert.ToInt32(secondAsString);
bool firsNumberPositive;
bool secondNumberPositive;
if (first > 0) {
firsNumberPositive = true;
}
else
{
firsNumberPositive = false;
}
if (second > 0)
{
secondNumberPositive = true;
}
else
{
secondNumberPositive = false;
}
if (firsNumberPositive && secondNumberPositive || !firsNumberPositive && !secondNumberPositive)
Console.WriteLine("Answer Is Positive");
else
if (!firsNumberPositive && secondNumberPositive || firsNumberPositive && !secondNumberPositive)
Console.WriteLine("Answer Is Negative");
Console.ReadLine();
isnt my way the same as the books way? because the book shows
if (first > 0) {
firsNumberPositive = true;
}
which is using the numbers just like i am to display positive and negative
heres mine, same thing?..
if (first >= 0 && second > 0 || first < 0 && second < 0)
Console.WriteLine("Your number will be Positive");
else
Console.WriteLine("Your number will be negative");

The solution presented in the book doesn't consider the condition where the input is 0, so it will behave differently than the code you wrote.

Your solution does not output the same result as the one in the book. Just try it with both first and second 0. Your code will say the result is negative while the book's solution will say it is positive.
In my opinion, 0 is neither a positive nor negative number and should be treated separately. So here's my solution:
if (first == 0 || second == 0) {
Console.WriteLine("The result is 0");
} else if ((first > 0) != (second > 0)) { // here, it might look a little weird but I'm just checking whether the signs are the same.
Console.WriteLine("The result is negative");
} else {
Console.WriteLine("The result is positive");
}

Related

If-statment, that loop / rerun it self till one of the conditions is true is that possible? i

Im totaly new to programming and trying to find a basic solution, im making a very simple game and im giving the person 2 options to do something, and if they choose neither 1 or 2 i want the tell them to choose again. But cant find a way to do it.
int antalspelare = 0;
int.TryParse(Console.ReadLine(), out antalspelare);
if(antalspelare == 1)
{
string spelareEtt = Console.ReadLine();
}
else if(antalspelare == 2)
{
string spelareEtt = Console.ReadLine();
string spelareTva = Console.ReadLine();
}
Keep on learning! You'll need loops to accomplish that. In particular here while loop will be useful that will keep running until the condition is false.
int antalspelare = 0
while(antalspelare < 1 || antalspelare > 2)
{
Console.WriteLine("Enter option (1 or 2):");
int.TryParse(Console.ReadLine(), out antalspelare);
if(antalspelare == 1)
{
string spelareEtt = Console.ReadLine();
}
else if(antalspelare == 2)
{
string spelareEtt = Console.ReadLine();
string spelareTva = Console.ReadLine();
}
}
At first antalspelare is 0, and so antalspelare < 1 || antalspelare > 2 is true, we start first iteration of the loop. It prints the message, asks to read number. If the number is 1 or 2, does the action, and on the next iteration antalspelare < 1 || antalspelare > 2 is false, the loop will terminate. However if it was something not 1 or 2, then the loop will continue to ask for new number
Further, you can dedicate the loop only for reading antalspelare, and only after the loop continue all the logic, like so:
int antalspelare = 0
while(antalspelare < 1 || antalspelare > 2)
{
Console.WriteLine("Enter option (1 or 2):");
int.TryParse(Console.ReadLine(), out antalspelare);
}
string spelareEtt, spelareTva;
if(antalspelare == 1)
{
spelareEtt = Console.ReadLine();
}
else if(antalspelare == 2)
{
spelareEtt = Console.ReadLine();
spelareTva = Console.ReadLine();
}
// You can use spelareEtt and spelareTva here and further

cannot figure out while random number generator game is not working c#

I am programming a game that generates a random number and then has the user try to guess the number when the user inputs a number the program will respond with either too high or too low depending on the number generated.The problem I am having is that the loop will just keep executing and the program will not take another user input if the number is incorrect.I have tried using different types of loops like a do while and for loop but keep getting the same problem I feel as though I am missing something simple or making a simple mistake thanks
string usernumber;
Random rnd = new Random();
int value = rnd.Next(1,50); //generates a random number upto 50
int guess = 0;
Console.WriteLine("please enter a number"); //asks for and takes user input
usernumber = Console.ReadLine();//stores user input
guess = Convert.ToInt32(usernumber);
while (guess != value) //this stands for not equals to
{
//guess = Convert.ToInt32(usernumber);
if (value > guess)
{
Console.WriteLine("too high");
}
else if (value < guess)
{
Console.WriteLine("too low");
}
else if (value == guess)
{
Console.WriteLine("bang on the answer was" + value);
}
else
{
Console.WriteLine("errrrrrrrrr");
}
}
Thread.Sleep(2000); //delays the program closing for a bit
You can use this corrected and refactored to have more explicit variables names.
We add 1 to 50 because the Random.Next last parameter is the upper bound excluded.
We use a do...while loop to have a concise algorithm.
We use int.TryParse to get the int from the user. This method returns false and sets the value to 0 in case of conversion error instead of an exception.
We use Console.ReadKey instead of Thread.Sleep, that is more UX friendly.
var random = new Random();
int numberTarget = random.Next(1, 50 + 1);
int numberUser;
do
{
Console.Write("Please enter a number between 1 and 50: ");
if ( int.TryParse(Console.ReadLine(), out numberUser) )
{
if ( numberUser > numberTarget )
{
Console.WriteLine("Too high, retry.");
}
else
if ( numberUser < numberTarget )
{
Console.WriteLine("Too low, retry.");
}
else
{
Console.WriteLine($"Bang on the answer was {numberTarget}.");
}
}
else
{
Console.WriteLine("You didn't enter a valid number, retry.");
}
}
while ( numberUser != numberTarget );
Console.WriteLine("Press a key to exit.");
Console.ReadKey();
In your while loop, you forgot to make another ReadLine.
while (guess != value) //this stands for not equals to
{
if (value > guess)
{
Console.WriteLine("too high");
guess = Convert.ToInt32(Console.ReadLine());
}
else if (value < guess)
{
Console.WriteLine("too low");
guess = Convert.ToInt32(Console.ReadLine());
}
else if (value == guess)
{
Console.WriteLine("bang on the answer was" + value);
}
else
{
Console.WriteLine("errrrrrrrrr");
}
}

Ending a loop by sentinel and parsing an input string as an integer

I am trying to continuously ask user for a number between 300-850. When the user enters a valid number, add it to the total and ask again. If the number is invalid, display an error. Before program ends, display the average of total number by amount of times of input. End program if user enters a sentinel value. I don't know how to check if user enters a sentinel value.
using System;
class CreditScores
{
static void Main()
{
var iterations = 0;
double total = 0;
int sum = 0;
double average = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentinel value reached.
while (iterations < 1000)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
int input = int.Parse(Console.ReadLine());
//not sure how to check if input is a number or not
if(input == integer)
{
if( input < 850 && input > 300 )
{
total +=input;
}
}
else
{
break;
}
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
average = total / count;
Console.WriteLine("The average is {0}", average);
}
}
Modification/fix of Your Method
Also, I would read all the way to the end for the more robust method you could use.
First thing I would change:
while (iterations < 1000)
{
...
}
To this (which we are not done yet, read to the end):
while (input != "calculate") // or some other string
{
...
}
Then, before the while starts, make input a string.
string input = "";
while (input != "calculate") // or some other string
{
...
}
Now, we declared an input variable that is already an int later on. Let's fix that.
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Now, we need to put it together and do some cleaning.
int total = 0;
int numbersEntered = 0;
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
numbersEntered++;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
}
Console.WriteLine("Total is {0}", total);
double average = (double)total / numbersEntered;
Console.WriteLine("The average is {0}", average);
(I know, long answer. But it should help you step through the problem in the future. Also, I wrote this all by memory, I can't guarantee it will compile.)
Update: just tested it, works as expected.
A more Robust Method
Lastly, and this is really the coolest method in my opinion, use a List<int> and some extension methods.
List<int> values = new List<int>();
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
values.Add(value);
else
{
// Was outside our range
}
else
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Console.WriteLine("Total is {0}", values.Sum());
Console.WriteLine("The average is {0}", values.Average());
Advantages to this method? It saves a list of the values entered, allowing you to do more with them that you cannot do with the method you currently have. It also uses the int.Sum() and int.Average() extension methods rather than your own math.
What is this int.TryParse(string, out int) sorcery?
The int.TryParse(string, out int) method (as defined by MSDN) will take an input string, and return a boolean value that indicates if it would make a valid int structure or not.
In the case that the string is a valid int, then the int parameter is filled with the integer representation of the string.
I.e.:
string myString = "100";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return true and print: myString was a valid int: 100.
Example 2:
string myString = "blah";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return false, and print myString was not a valid int.. The value variable would also be 0.
Warning:
When using int.TryParse(string input, out int value), do not rely on the value parameter as 0 to indicate failure. If the input is "0", then the value will also be 0, and the method will return true.
You want to set the condition of your while loop to something that a user can trigger as false (the sentinel).
Then put a for loop inside that if you want to do a set number of iterations, for loops are better for situations where you know how many iterations you're doing.
BUT if you want to stick to while loops only, here's a quick code snippet you could use:
while (input != 0 && iterations < 1000) //or some sentinel value you choose
{
//Your logic here, now the loop will quit if if the user enters 0
//OR you run out of iterations
}
using System;
class CreditScores
{
static void Main()
{
double total = 0;
int sum = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentihel value reached.
for (iterations = 0; iterations < 1000; iterations++)
{
Console.WriteLine("Enter value between 300 to 850.");
int input;
// Check number is integer
if (int.TryParse(Console.ReadLine(), out input)
{
if(input > 300 && input < 850)
{
total +=input;
}
}
else
{
break;
}
count++;
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
double average = total/count;
Console.WriteLine("The average is {0}", average);
Console.ReadLine(); // Either this or run with Ctrl-F5
}
}
The behaviour would be to add the totals until the user entered something that couldn't be parsed, and then exit.
Does this work?
string sentinalValue = "done";
string input = "";
while (iterations < 1000 && input != sentinalValue)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if( value < 850 && value > 300 )
{
total +=input;
}
}
else
{
Console.WriteLine("That is not a number!");
}
}

How could I convert this goto into a do while loop?

class Program
{
static void Main(string[] args)
{
string choice = string.Empty;
do
{
start:
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if (number < 1000)
{
switch (conversion)
{
case true:
while (number <= output)
{
Console.Write(number + " ");
number += 2;
}
break;
case false:
Console.WriteLine("ERROR: INVALID INPUT!");
goto start;
}
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
return;
}
do // Here is the beginning of the do code
{
Console.WriteLine("\n Do you want to continue - Yes or No");
choice = Console.ReadLine();
if (choice.ToUpper() != "YES" && choice.ToUpper() != "NO")
{
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
} while (choice.ToUpper() != "YES" && choice.ToUpper() != "NO");
} while (choice.ToUpper() == "YES");
}
}
I'm using several do while loops in this statement however I'm trumped on how I would put in a loop "ERROR INVALID INPUT:" result when a user puts in anything other than the limits of the assigned integers (i.e. putting decimals or fractions) or if they put a string. I simply used goto because I'm having trouble finding out where to put the do while loop statement. If someone could simply show me how I might replace that one goto with a do while loop then I would be very greatful. (Note if you show me ways I could optimize my code better since I'm still new I probably won't understand it but your welcome to give it your best shot!)
Short answer:
The keyword continue means to go back to the beginning of the loop. Note that this will recheck the loop condition and break if it is false. Also, most people find do-while loops less readable (and they are really rarely necessary), so try using while loops instead.
There is also the keyword break which will simply exit the loop. (not just for switch-case!)
A more readable version would look something like this:
string userAnswer = "yes";
// while is usually more readable than do-while
while (userAnswer == "yes")
{
Console.WriteLine("Please input a number for it to be counted!");
int number;
// Ask for new input until the user inputs a valid number
while (!int.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("Invalid number, try again");
}
if (number < 1000)
{
// Print from 0 to number, jumping in 2's
for (int i = 0; i <= number; i += 2)
Console.WriteLine(i + " ");
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
continue; // Jump back to the start of this loop
}
Console.WriteLine("Continue? (Yes / No)");
userAnswer = Console.ReadLine().ToLower();
// Ask for new input until the user inputs "Yes" or "No"
while (userAnswer != "yes" && userAnswer != "no")
{
Console.WriteLine("Invalid input. Continue? (Yes / No)");
userAnswer = Console.ReadLine().ToLower();
}
}
Hey I'll post some code that may help and offer some advice. Basically declare a bool named 'loopCompleted' which will continue the do while loop until you set it to true. The downside is that it will not instantly exit the loop like return/goto/etc but this is not a problem in most cases.
You may want to use if/else instead of switch(conversion), its sort of interesting to see it done that way but its a bit over the top :)
If Int.TryParse() doesnt already return false for fractional values (e.g. [15.08] returns [true] with [15] ). Then you can store Console.ReadLine() before using TryParse, then use stringName.Contains() to check for the '.' Basically, if the conversion succeeds you also check if it contained the decimal point.
Another way to check is to do float.TryParse() then check if it is a fractional value.
bool fraction = false;
if( number % 1.0f > 0)
fraction == true;
% is called modulus, it returns the remainder of A / B
If a number has a remainder when divided by 1 it must be a fractional value.
//start:
bool loopCompleted = false;
do
{
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if (conversion && number < 1000)
{
while (number <= output)
{
Console.Write(number + " ");
number += 2;
}
loopCompleted = true;
}
else
{
if(conversion == false)
{
Console.WriteLine("ERROR: INVALID INPUT!");
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
}
}
} while(!loopCompleted)

outputing array values specific

i am working on a very specific problem. this program prompts the user for a number between 1-10000000 and then another number 1-10000. the first number is how many random numbers and the second is what the max those numbers can be is. im trying to print the result on user prompt and print if user wants to print results and the result are number of primes. first problem is i cannot get the program to respond to the user pushing 1 or 0 to print results. second is i cannot get the number of primes that were created to print as a resut
namespace PRIMECON
{
class PRIMECON
{
static void Main(string[] args)
{
//creates stopwatch
Stopwatch watch = new Stopwatch();
//creates randoms
Random rnd = new Random();
//starts the stopwatch
watch.Start();
//gets number from 1 to 10 million
Console.WriteLine("\nPlease enter a number between 1 and 10,000,000");
bool checkn;
int number; //input
checkn = int.TryParse(Console.ReadLine(), out number);
//gets number from 1 to 10 thousand
Console.WriteLine("\nPlease enter a number between 1 and 10,000");
bool checkr;
int range; //range of values from 0 to r
checkr = int.TryParse(Console.ReadLine(), out range);
if (checkn == true && checkr == true && number > 0 && number <= 10000000 && range > 0 && range <= 10000)
{
//array
int arraySize = 0;
//int[] array = new int[range];
for (int i = 0; i < number; i++)
{
int randomNumber = rnd.Next(1, range);
bool primeNumber = PRIMELIB.PRIMELIB.IsItPrime(randomNumber); //calls library method
if (primeNumber == true)
arraySize++; //adds to the array for each prime number
//array[i] = randomNumber;
//prints numbers
Console.WriteLine(i.ToString() + " " + randomNumber.ToString() + " " + primeNumber.ToString()); // prints index, number, true/false
}
//int[] array = new int[arraysize];
watch.Stop();
Console.WriteLine("\nElapsed Time = " + watch.Elapsed.ToString());
int exit = 1;
do
{
Console.WriteLine("would you like to print results? 0-no 1-yes");
Console.ReadLine();
int rangeHigh;
int rangeLow;
bool high = int.TryParse(Console.ReadLine(), out rangeHigh);
bool low = int.TryParse(Console.ReadLine(), out rangeLow);
if (high == true && low == true)
{
for (int i = rangeLow; i < rangeHigh; i++)
{
//Console.WriteLine( i + ". " + array[i]);
}
}
}
while (exit != 0);
}
else if (checkn == false || number > 10000000 || number < 0)
Console.WriteLine("First number was not valid");
else if (checkr == false || range > 10000000 || range < 0)
Console.WriteLine("Range was not valid");
else
Console.WriteLine("entry not valid");
Console.ReadKey();
}
}
}
At the moment I can post an answer about your "cannot get the program to respond to the user pushing 1 or 0 to print results" issue. Since your are reading the console line within the do/while loop you can use the int.Parse function then put the inner part of the while loop in an if statement so it will only execute if the user picked yes. The loop will now become this:
int exit = 1;
do
{
Console.WriteLine("would you like to print results? 0-no 1-yes");
exit = int.Parse(Console.ReadLine());
if (1 == exit)
{
int rangeHigh;
int rangeLow;
bool high = int.TryParse(Console.ReadLine(), out rangeHigh);
bool low = int.TryParse(Console.ReadLine(), out rangeLow);
if (high == true && low == true)
{
for (int i = rangeLow; i < rangeHigh; i++)
{
//Console.WriteLine( i + ". " + array[i]);
}
}
}
}
while (exit != 0);
For your library issue with not being able to get the number of primes that were created my only suggestion is to check your references to see if you include it, and if you added the using for it at the top of your code. I have not used custom libraries in c#, but searching around in google on how to use libraries in c# will be your best bet.

Categories