C# While Infinite Loop - c#

I'm still learning the fundamentals of C# and I'm currently busy with some code which has got me stuck in an infinite loop.
do
{
Console.Write("Please enter the Exam mark for student " + (index + 1) + ": ");
Exam[index] = double.Parse(Console.ReadLine());
Console.Write("Please enter the DP for student " + (index + 1) + ": ");
DP[index] = double.Parse(Console.ReadLine());
Final[index] = (DP[index] + Exam[index]) / 2;
index++;
} while (DP[index] != 999);
The code doesn't break when I type 999.

You increase the index with 1 just before the while condition is checked. I guess the value is 0 on that index...
A solution can be to remember the previous value in a variable, or subtract one from the index:
} while (DP[index - 1] != 999);
Another problem might be the use of a double, since it is imprecise, it doesn't always match to 999 if you entered that value. If you can, use int or decimal.

Related

Sum up all numbers between two numbers

I am a beginner in C# programming and trying to code a method that ask the user to give a start and an end integer number, then sum up all numbers from the start to the end and in case the given start number is greater than the end number, swap the values so that the start number becomes the end number and the end number gets the value of the start number.
This what I have done so far but I'm not getting the right answer when running the app:
private void SumNumbers()
{
int startNumber, endNumber;
Console.WriteLine("\nplease enter a start number: ");
startNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nplease enter an end number: ");
endNumber = Convert.ToInt32(Console.ReadLine());
int result = 0;
for (int i=0; i<=startNumber; i=i+1)
{
result = result + i;
Console.WriteLine(i);
}
Console.ReadLine();
Console.WriteLine("The sum of Numbers between " + startNumber + " and " + endNumber + " is: " + result.ToString());
Console.ReadLine();
}
I'm getting this result: The sum of Numbers between 12 and 23 is: 78 when the result actually need to 210.
for (int i=0;i<=startNumber;i=i+1)
You are iterating from 0 to startNumber, when really you want to iterate like startNumber to endNumber.
Try
for (int i = startNumber; i <= endNumber; i = i+1)
Below is the working example.
I also added some logic to handle the checking of the input (whether it is correct or no) so the application doesn't break. This way the user experience is much better.
Here is the live working example: code
private void SumNumbers()
{
int startNumber, endNumber;
Console.WriteLine("\nplease enter a start number: ");
do
{
var input1 = Console.ReadLine();
if (Regex.IsMatch(input1, #"^\d+$"))
{
startNumber = Convert.ToInt32(input1); break;
}
else
{
Console.WriteLine("Input provided is invalid. Please enter a correct number: ");
}
} while (true);
Console.WriteLine("\nplease enter an end number: ");
do
{
var input2 = Console.ReadLine();
if (Regex.IsMatch(input2, #"^\d+$"))
{
endNumber = Convert.ToInt32(input2); break;
}
else
{
Console.WriteLine("Input provided is invalid. Please enter a correct number: ");
}
} while (true);
int min = Math.Min(startNumber, endNumber);
int max = Math.Max(startNumber, endNumber);
int result = 0;
for (int i = min; i <= max; i++)
{
result = result + i;
Console.WriteLine(i);
}
Console.WriteLine("The sum of Numbers between " + min + " and " + max + " is: " + result.ToString());
Console.ReadLine();
}

Fix user input not continuing until the entered user input loops to match its index in the array

The problem I have is that when I enter an element from the array, the user input resets to the start of the loop, for example when i user input the third element from the array, the user input question two more times to continue to the next user input question, how can I fix this? everybody know what I can adjust here.
worked loop image with 1st element entered
looping error
while (true)
{
String[] bgtype = { "cheeseburger","tlc", "bbq" };
int[] bgtypeprice = { 15, 25, 10 };
int max = bgtype.Length;
String[] product = new string[max];
String[] type = new string[max];
int[] qty = new int[max];
int[] disc = new int[max];
Console.WriteLine("");
for (int i = 0; i < max; i++)
{
Console.Write("What PRODUCT would you like to buy ?: "); ;
product[i] = Console.ReadLine();
if (product[i].Equals("burger", StringComparison.CurrentCultureIgnoreCase))
{
{
Console.Write("What TYPE of product would you like to buy?: ");
type[i] = Console.ReadLine();
if (bgtype[i].Contains(type[i]))
{
Console.Write("Enter your discount % (5% for adults & 7% for minors): ");
disc[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("How many will you buy? ");
qty[i] = Convert.ToInt32(Console.ReadLine());
float total = bgtypeprice[i]; total *= qty[i];
Console.WriteLine("Total cost of " + type[i] + " " + product[i] + " is: " + qty[i] + " pieces x P" + bgtypeprice[i] + "= P" + total);
float totaldisc = 0; totaldisc = (total * disc[i]) / 100;
Console.WriteLine("Total amount of discount: P " + totaldisc);
float totalamt = 0; totalamt = total - totaldisc;
Console.WriteLine("Total cost of order: P " + totalamt);
Console.WriteLine("-------------------ORDER CONFIRMATION-------------------");
}}}}}
if (bgtype[i].Contains(type[i])) should be changed to if (bgtype.Contains(type[i]))
Array.Contains, verifies if an item is contained within an Array, not an Array value. By asking if bgtype[i] contains type[i], you are asking if cheesburger contains tlc, which it doesn't, hence why it starts from the beginning. By verifying if bgtype contains type[i], you are asking if ["cheesburger", "tlc", "bbq"] contains tlc, which it does. I hope this was clear enough.

Number Guessing Game in c#

I'm working on Visual Studio about binary search in c#. My project about the computer find the user's guess number. So, I use tihs code in the main;
int min = 0; // minimum number in the array
int max = 100; // maximum number in the array
int middle = 50; // middle number in the array
int counter = 1;
string name, input;
int guess_number;
Console.WriteLine("Hello, this is a game that finding the number of in your mind. If you want to play so let me know you! ");
name = Console.ReadLine();
Console.WriteLine("Awesome welcome to the game " + name + " guess a number between " + min + " and " + max + " Please! ");
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
input = Console.ReadLine();
guess_number = Convert.ToInt32(input);
Console.WriteLine(" You select " + guess_number + " so, ");
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
Console.WriteLine(counter + " times I tried for finding your number ");
} while (guess_number != 0);
Console.ReadKey();
However, output always repeat after the user write anything, why the reason about that, is there anyway to get the number?
from your description, I think you need to let user input new value to guess_number variable in the loop end otherwise the loop will not end from the condition guess_number != 0.
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
Console.WriteLine(counter + " times I tried for finding your number ");
input = Console.ReadLine(); // let user key in new value.
guess_number = Convert.ToInt32(input);
} while (guess_number != 0);
the last readKey should be inside the while.
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
input = Console.ReadLine();
guess_number = Convert.ToInt32(input);
Console.WriteLine(counter + " times I tried for finding your number ");
} while (guess_number != 0);

C# Lottery Compare Results

I'm new to C# we have an activity to create a lottery game.
1 matching number won $10
2 matching number won $100
3 matching number not in order $1,000
3 matching number in order won $10,000
I'm having issues with my code even there are 2 matching or 3 matching number it always display $10. Any help would be appreciated.
Below are the source code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LotteryGame
{
class Program
{
static void Main(string[] args)
{
// Matching numbers awards
int rNumMatchOne = 10;
int rNumMatchTwo = 100;
int rNumMatchThree = 1000;
int rNumMatchFour = 10000;
// Generate random numbers
Random randomNum = new Random();
// Integers Declaration
int rNum1;
int rNum2;
int rNum3;
int rNumIput;
int guessNum;
// Arrays Declartion
int[] guessNumMatch = new int[3];
int[] guessNumSort = new int[3];
int[] guessInput = new int[3];
// Restrict inputs between 1 and 4 only
rNum1 = randomNum.Next(1, 5);
rNum2 = randomNum.Next(1, 5);
rNum3 = randomNum.Next(1, 5);
Console.Write("C# Lottery Game\n\n");
Array.Sort(guessNumSort); // sort random numbers
// Guess number input loop
for (rNumIput = 0; rNumIput < 3; rNumIput++)
{
Console.Write("Guess Number " + (rNumIput + 1) + ": ");
guessNum = Convert.ToInt32(Console.ReadLine());
// Invalid input between 1 and 4 program will loop back and enter correct number
while (guessNum < 1 || guessNum > 4)
{
Console.WriteLine("\n");
Console.WriteLine("Invalid Number. Please enter number between 1 and 4. \n");
Console.Write("Guess Number " + (rNumIput + 1) + ": ");
guessNum = Convert.ToInt32(Console.ReadLine());
}
guessNumMatch[rNumIput] = guessNum;
guessNumSort[rNumIput] = guessNum;
}
Array.Sort(guessNumSort);
// Display random numbers and entered numbers
Console.WriteLine();
Console.WriteLine("Generated random numbers are : " + rNum1 + " | " + rNum2 + " | " + rNum3);
Console.WriteLine("Numbers you entered are : " + guessNumMatch[0] + " | " + guessNumMatch[1] + " | " + guessNumMatch[2]);
// Matching 1 number
if (guessNumMatch[0] == rNum1 || guessNumMatch[1] == rNum2 || guessNumMatch[2] == rNum3)
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchOne);
}
// Matching 2 numbers
else if ((guessNumMatch[0] == rNum1 && guessNumMatch[1] == rNum2) || (guessNumMatch[1] == rNum2 && guessNumMatch[2] == rNum3))
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchTwo);
}
// Matching 3 numbers not in order
else if (guessNumSort[0] == guessInput[0] && guessNumSort[1] == guessInput[1] && guessNumSort[2] == guessInput[2])
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchThree);
}
// Matching 3 numbers exact order
else if (guessNumMatch[0] == rNum1 && guessNumMatch[1] == rNum2 && guessNumMatch[2] == rNum3)
{
Console.WriteLine("\n");
Console.WriteLine("CONGRATULATIONS! YOU WON: $" + rNumMatchFour);
}
else // No matching numbers
{
Console.WriteLine("\n");
Console.WriteLine("SORRY, NO MATCHING NUMBERS FOUND! ");
}
Console.WriteLine("\n");
Console.WriteLine("PRESS ANY KEY TO EXIT PROGRAM ");
Console.ReadKey();
}
}
}
Invert the order of your if statements. Check first if 3 numbers are matched in order, then 3 then 2 then 1 and last no match.
Otherwise the first if statement hits true even when there is more than 1 match.
Your first if statement will evaluate to true if at least one of the numbers is correct. For example, if the user guess the 2nd and 3rd number correctly, guessNumMatch[1] == rNum2 will evaluate to true. if(false || true || true) evaluates to true so the statement gets executed. The other if statements will be skipped.
One solution (as Attersson beat me to) is to invert your if statements - check if all 3 are true, then if 2 are true, etc.

Adding points to a score

Im building a console c# flash card game and I want to keep a score going to show at the end of how many where correct. I am thinking on what is the best course of action to do this I was thinking a for loop but it didn't work for me like I thought that it might and then again I am still new to programming so I am sure maybe I am just doing something wrong.
So, I have a double called answer.
and since I only need a single in I used another int that is called correctAnswer.
I was thinking I could use that to add to the for loop but it didn't go as planned
so, I am just asking for what might be the best course of action to add points to a score. I also see another problem I will have by using answer as it will add a point even if they get it wrong but I can fix that once I get this sorted.
double answer = 0;
int correctAnswer = Convert.ToInt32(answer);
for (correctAnswer = 0; correctAnswer <= answer; correctAnswer++) ;
///Setting up the switch statement
///switch (variable)
/// case 1:
/// code;
/// break;
///
switch (opSign)
{
case 1:
Console.WriteLine("What is the answer to " + num1 + (" Times " + num2 + " ?"));
answer = Convert.ToInt32(Console.ReadLine());
if (answer == num1 * num2)
{
speechAnswers();
Console.WriteLine("You entered " + answer + " as the answer to " + num1 + " times " + num2 + "." + " You are correct good job! ");
}
else if (answer != num1 * num2)
Console.WriteLine("You are incorrect please try again");
break;
This your the code after adding a small bit of code. Every time he answers correctly, Answer is incremented by 1. If you want to reset your score, You will need to make a function for that that happens when maybe, score decreases three times in a streak. This is your game.
double answer = 0;
int correctAnswer = Convert.ToInt32(answer);
for (correctAnswer = 0; correctAnswer <= answer; correctAnswer++) ;
///Setting up the switch statement
///switch (variable)
/// case 1:
/// code;
/// break;
///
switch (opSign)
{
case 1:
Console.WriteLine("What is the answer to " + num1 + (" Times " + num2 + " ?"));
answer = Convert.ToInt32(Console.ReadLine());
if (answer == num1 * num2)
{
speechAnswers();
Console.WriteLine("You entered " + answer + " as the answer to " + num1 + " times " + num2 + "." + " You are correct good job! ");
score += 1; // every time the answer is correct, score is incremented by 1.
}
else if (answer != num1 * num2)
Console.WriteLine("You are incorrect please try again");
// what happens on loss
break;
every time you write a code happens when the answer is correct, Add this
score += 1;

Categories

Resources