I am new to c# and coding in general. To try and improve my skills I am trying to create a basic game where two players roll a dice and keep record of their score. The player wins by reaching 20. Each player takes turns rolling a dice adding their first roll to their second and so on until one of them reaches 20. A player can roll the dice again if they roll a six.
The current code I have is:
do
{
Console.Write("Enter the name of Player 1: ");
Player[0] = Console.ReadLine();
Console.Write("Enter the name of Player 2: ");
Player[1] = Console.ReadLine();
Random DiceRandom = new Random();
DiceThrow[0] = DiceRandom.Next(1, 7);
int i = 0;
while (i <= 1)
{
DiceThrow[0 + i] = DiceRandom.Next(1, 7);
Console.ReadLine();
Console.Write(Player[0 + i] + " rolled a " + DiceThrow[0 + i]);
if (DiceThrow[0 + i] != 6) i++;
}
Console.ReadLine();
PlayerTotal[0] = DiceThrow[0];
PlayerTotal[1] = DiceThrow[1];
Console.ReadLine();
Console.Write(Player[0] + " currently has " + PlayerTotal[0]);
Console.ReadLine();
Console.Write(Player[1] + " currently has " + PlayerTotal[1]);
Console.ReadLine();
}
while (PlayerTotal[0] == 20);
while (PlayerTotal[1] == 20);
What I am specifically struggling with is adding the players first roll to there second roll. And if a player rolls a six that it adds the 6 to what they get in the re-roll.
Any help at all will be greatly appreciated.
There are a number of concerns with your code here:
you are asking the player name inside the loop
You are initializing the Random generator inside the loop (this can cause same results on different loops because the random generator can use the same seed)
You are resetting totals using = instead of +=
The stop condition is totals == 20 instead of total < 20
you are using two while statement instead of an AND (&&) condition
This is just a brief overview..
This can be a solution:
Console.Write("Enter the name of Player 1: ");
Player[0] = Console.ReadLine();
Console.Write("Enter the name of Player 2: ");
Player[1] = Console.ReadLine();
Random DiceRandom = new Random();
do
{
int i = 0;
while (i <= 1)
{
int thisThrow = DiceRandom.Next(1, 6);
DiceThrow[0 + i] += thisThrow;
Console.ReadLine();
Console.Write(Player[0 + i] + " rolled a " + thisThrow);
if (thisThrow != 6) i++;
}
Console.ReadLine();
PlayerTotal[0] += DiceThrow[0];
PlayerTotal[1] += DiceThrow[1];
Console.ReadLine();
Console.Write(Player[0] + " currently has " + PlayerTotal[0]);
Console.ReadLine();
Console.Write(Player[1] + " currently has " + PlayerTotal[1]);
Console.ReadLine();
}
while (PlayerTotal[0] < 20 && PlayerTotal[1] < 20);
Your problem is that you're reseting the previous scores with these lines:
PlayerTotal[0] = DiceThrow[0];
PlayerTotal[1] = DiceThrow[1];
You should change it to use += like this:
PlayerTotal[0] += DiceThrow[0];
PlayerTotal[1] += DiceThrow[1];
Which is like saying: PlayerTotal[0] = PlayerTotal[0] + DiceThrow[0];
Other then that, there are a few more problems in your code.
For instance, you have one Do at the beginning of the code but 2 whiles...
You probably want to create one While with an AND statement. Also, the Do statement needs to be after you get the user's names...
For instance:
// Get User names
do
{
// All your Dice throwing logic
}
while (PlayerTotal[0] != 20 && PlayerTotal[1] != 20);
int i = 0;
while (i <= 1)
{
int thisThrow = DiceRandom.Next(1, 6);
DiceThrow[0 + i] += thisThrow;
Console.ReadLine();
Console.Write(Player[0 + i] + " rolled a " + thisThrow);
if (thisThrow != 6) i++;
}
Console.ReadLine();
PlayerTotal[0] += DiceThrow[0];
PlayerTotal[1] += DiceThrow[1];
Console.ReadLine();
Console.Write(Player[0] + " currently has " + PlayerTotal[0]);
Console.ReadLine();
Console.Write(Player[1] + " currently has " + PlayerTotal[1]);
Console.ReadLine();
Related
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();
}
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.
I am trying to add a Goto or like function in my code. This game is based on the hammurabi game. I am trying to remove the sections in my code where it says "Please reset" and follows back to the question.
Also once the game is completed I am looking it to loop back and add a value to the year but also keep values from the orginal game.
using System;
namespace Game2
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int land = 1000, people = 100, landprice = rnd.Next(17, 26);
int foodin = 0, landin = 0, landout = 0, seeds = 0;
int foodcost = 20, food = 2800, totalfoodcost = 0;
int year = 0;
Console.WriteLine("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA");
Console.WriteLine("SUCCESSFULLY FOR A 1 YEAR TERM OF OFFICE.");
Console.WriteLine();
Console.WriteLine("HAMURABI: I BEG TO REPORT TO YOU,");
Console.WriteLine();
Console.WriteLine("Year " + year + 1 +" In Charge");
Console.WriteLine("The city population is now " + people);
Console.WriteLine("The city owns " + land + " acres");
Console.WriteLine("You now have " + food + " bushels in store.");
Console.WriteLine("Land is trading at " + landprice + " bushels per acre.");
Console.WriteLine();
Console.Write("How Many Acres Would You Like To Buy? ");
landin = int.Parse(Console.ReadLine());
Console.WriteLine();
food = food - landprice * landin;
land = landin + land;
if (landin * landprice <= food)
{
Console.WriteLine("You Bought " + landin + " Acres");
Console.WriteLine("You Own " + land + " Acres");
Console.WriteLine("You Have " + food + " Bushell Left");
Console.WriteLine();
}
else if (landin * landprice > food)
{
Console.WriteLine("You Dont Have Enought Bushell ");
return;
}
Console.Write("How Many Acres Would You Like To Sell? ");
landout = int.Parse(Console.ReadLine());
Console.WriteLine();
land = land - landout;
food = landprice * landout + food;
if (landout <= land)
{
Console.WriteLine("You Sold " + landout + " Acres");
Console.WriteLine("You Own " + land + " Acres");
Console.WriteLine("You Now Have " + food + " Bushells");
Console.WriteLine();
}
else if (landout > land)
{
Console.WriteLine("You Dont Own Enough Acres - Please Reset");
return;
}
Console.Write("How Many Bushell Would You Like To Feed Your People? ");
foodin = int.Parse(Console.ReadLine());
Console.WriteLine();
totalfoodcost = people * foodcost;
if (foodin == totalfoodcost && foodin < food)
{
Console.WriteLine("Your People Have Eaten");
food = food - totalfoodcost;
Console.WriteLine("You Have " + food + " Bushell Left");
Console.WriteLine();
}
else if (foodin > food)
{
Console.WriteLine("You Dont Have Enought Bushell - Please Restart! ");
return;
}
else if (foodin < totalfoodcost)
{
Console.WriteLine("You Have Been Over Thrown As People Are Hungry - Please Restart! ");
return;
}
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
if (seeds <= food && seeds <= people)
{
Console.WriteLine("You Have Planted " + seeds + " Seeds");
food = food - seeds;
Console.WriteLine("You Now Have " + food + " Bushell");
Console.WriteLine();
}
else if (seeds > food)
{
Console.WriteLine("You Do Not Have Enought Bushell");
}
else if (seeds > people)
{
Console.WriteLine("You Do Not Have Enought People");
}
Console.WriteLine("End Of Year " + year);
}
}
}
First of all, you need to divide your program into functions as per its duty (Seperation of Concerns)
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int land = 1000, people = 100, landprice = rnd.Next(17, 26);
int foodin = 0, landin = 0, landout = 0, seeds = 0;
int foodcost = 20, food = 2800, totalfoodcost = 0;
int year = 0;
for (; year < <break_condition> ; year++)
StartMyGame(land, foodin, foodcost, year);
}
}
furthermore, you can also use goto statement
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int land = 1000, people = 100, landprice = rnd.Next(17, 26);
int foodin = 0, landin = 0, landout = 0, seeds = 0;
int foodcost = 20, food = 2800, totalfoodcost = 0;
int year = 0;
game_start_pos:
StartMyGame(land, foodin, foodcost, year++);
if (!<your_break_condition> )
goto game_start_pos:
}
}
This is my code I resolved it by, I used a while loop.
using System;
namespace Game2
{
class Program
{
static void Main(string[] args)
{
{
// This is the to allow random numbers to be created
Random rand = new Random(DateTime.Now.Millisecond);
Random ran1 = new Random(DateTime.Now.Millisecond);
Random ran2 = new Random(DateTime.Now.Millisecond);
Random ran3 = new Random(DateTime.Now.Millisecond);
Random ran4 = new Random(DateTime.Now.Millisecond);
//this is my integer which will hold my data
int people = 100, landPrice = 0;
int foodIn = 000, landIn = 0000, landOut = 0000, seeds = 0;
int foodCost = 20, food = 2800, totalFoodCost = 0000;
int year = 1;
int land = 1000;
int newPeople = 0;
int peopleDied = 0;
int seedCost = 0;
int rats = 0;
int peopleSell = 0;
double landFinal = 0;
peopleSell = people * 10;
//game rules and start of game
Console.WriteLine("Game Rules! ");
Console.WriteLine("The game lasts 10 years, with a year being one turn. ");
Console.WriteLine("Each year, enter how many bushels of grain to allocate to buying (or selling) acres of land, feeding your population, and planting crops for the next year ");
Console.WriteLine("Each person needs 20 bushels of grain each year to live and can till at most 10 acres of land. ");
Console.WriteLine("Each acre of land requires one bushel of grain to plant seeds. ");
Console.WriteLine("The price of each acre of land fluctuates from 17 bushels per acre to 26 bushels. ");
Console.WriteLine("If the conditions in your country ever become bad enough, the people will overthrow you and you won't finish your 10 year term. ");
Console.WriteLine("If you make it to the 11th year, your rule will be evaluated ");
Console.WriteLine();
Console.WriteLine("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA");
Console.WriteLine("SUCCESSFULLY FOR A 10 YEAR TERM OF OFFICE.");
Console.WriteLine();
Console.WriteLine("HAMURABI: I BEG TO REPORT TO YOU,");
Console.WriteLine();
// loop to add + 1 to year if year is <= 10 and people > 0
while (year <= 10 && people > 0)
{
// this will random gen a number between 17 and 26
landPrice = rand.Next(17, 26);
Console.WriteLine("Year " + year + " In Charge.");
Console.WriteLine();
Console.WriteLine("You Harvested " + seeds + " Bushels.");
Console.WriteLine(newPeople + " People Came To The City.");
Console.WriteLine(peopleDied + " Died In The City.");
Console.WriteLine("Rats Have Eaten " + rats + " Bushels.");
people = people + newPeople;
people = people - peopleDied;
Console.WriteLine("The City's Population Is Now " + people + ".");
Console.WriteLine("The City Owns " + land + " Acres.");
food = seeds + food;
food = food - rats;
Console.WriteLine("You Now Have " + food + " Bushels In Storage.");
Console.WriteLine("Land is trading at " + landPrice + " Bushels per Acre.");
Console.WriteLine();
landFinal = ((double)land / people);
//start of game
// Section for user to enter how many acres would like to buy
Console.Write("How Many Acres Would You Like To Buy? ");
landIn = int.Parse(Console.ReadLine());
Console.WriteLine();
// this will random gen a number between 1 and 10 and 0 and 5 and so on.
newPeople = ran1.Next(1, 10);
peopleDied = ran2.Next(0, 5);
rats = ran3.Next(50, 500);
// loop if landIn * landPrice > food or landIn < 0 will show error and ask user to input again
while (landIn * landPrice > food || landIn < 0)
{
Console.WriteLine("You Dont Have Enough Bushels!! ");
Console.Write("PLEASE RE ENTER: How Many Acres Would You Like To Buy? ");
landIn = int.Parse(Console.ReadLine());
Console.WriteLine();
}
// loop if landIn * landPrice < food then allows user to go on and shows summary
if (landIn * landPrice < food)
{
food = food - landPrice * landIn;
land = landIn + land;
Console.WriteLine("You Bought " + landIn + " Acres.");
Console.WriteLine("You Own " + land + " Acres.");
Console.WriteLine("You Have " + food + " Bushels Left.");
Console.WriteLine();
}
// Section for user to enter how many acres would like to sell
Console.Write("How Many Acres Would You Like To Sell? ");
landOut = int.Parse(Console.ReadLine());
// loop if land < landOut or landIn < 0 will show error and ask user to input again
Console.WriteLine();
while (land < landOut || landOut < 0)
{
Console.WriteLine("You Dont Own Enough Acres!!");
Console.Write("RE ENTER How Many Acres Would You Like To Sell? ");
landOut = int.Parse(Console.ReadLine());
Console.WriteLine();
}
//if the loop condition is met will allow user to carry on.
if (landOut < land || landOut == land)
land = land - landOut;
food = food + landPrice * landOut;
{
Console.WriteLine("You Sold " + landOut + " Acres.");
Console.WriteLine("You Own " + land + " Acres.");
Console.WriteLine("You Now Have " + food + " Bushels.");
Console.WriteLine();
}
// Section for user to enter how many bushel to feed their people.
Console.Write("How Many Bushels Would You Like To Feed Your People? ");
foodIn = int.Parse(Console.ReadLine());
Console.WriteLine();
// Section if condition not met user will have to re enter value
while (foodIn > food || foodIn < 0)
{
Console.WriteLine("You Dont Have Enough Bushels!!");
Console.Write("RE ENTER How Many Bushels Would You Like To Feed Your People? ");
foodIn = int.Parse(Console.ReadLine());
Console.WriteLine();
}
totalFoodCost = people * foodCost;
// if condition met user can carry on
if (foodIn >= totalFoodCost && foodIn <= food)
{
Console.WriteLine("Your People Have Eaten.");
Console.WriteLine();
food = food - foodIn;
Console.WriteLine("You Have " + food + " Bushels Left.");
Console.WriteLine();
}
// Section if condition not met user will have to re enter values
else if (foodIn < totalFoodCost)
{
Console.WriteLine("You Have Been Over Thrown As People Are Hungry - Please Restart! ");
return;
}
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
seedCost = (people * 10);
while (seeds > seedCost || seeds < 0)
{
Console.WriteLine("You Dont Have Enough People! ");
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
}
if (seeds < seedCost && seeds < food)
{
Console.WriteLine("You Have Planted " + seeds + " Seeds.");
food = food - seeds;
Console.WriteLine("You Now Have " + food + " Bushels.");
Console.WriteLine();
}
while (land == 1 || seeds > land || seeds < 0)
{
Console.WriteLine("You Dont Have Enough Land!!");
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
}
while (seeds > food || seeds < 0)
{
Console.WriteLine("You Dont Have Enough Bushels!!");
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
}
food = food - seeds;
seeds = seeds * rand.Next(2, 8);
//end of year summary will loop untill year 11.
Console.WriteLine("End Of Year " + year + ".");
year = year + 1;
Console.WriteLine();
Console.WriteLine("You Ended With " + food + " Bushels.");
Console.WriteLine("You Ended With " + land + " Acres.");
Console.WriteLine();
landFinal = ((double)land / people);
// end of year final summary
if (year == 11)
{
Console.WriteLine("Congratulations On Reaching The End Of Your Term!");
Console.WriteLine();
Console.WriteLine("You Ended With " + food + " Bushels.");
Console.WriteLine("You Ended With " + land + " Acres.");
Console.WriteLine("You Ended With " + people + " People.");
Console.WriteLine("Each Person Ended With " + landFinal + " Per Acre.");
Console.WriteLine();
landFinal = ((double)land / people);
}
//failed year summary
if (year == 11 && landFinal < 10)
{
Console.WriteLine("You Have Been Marked As A Failure For Your Service!!");
return;
}
//sucessful game summary
if (year == 11 && landFinal >= 10)
{
Console.WriteLine("You Are A Great King!!");
return;
}
}
}
}
}
}
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);
I'm trying to get a factorial to be displayed as for example (factorial of 5 is 5*4*3*2*1)
I'm using a method for the factorial, but it doesn't accept the line Console.Write(i + " x "); in my code.
Any help would be great.
here is my code.
//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have entered an invalid option");
Console.WriteLine("Please enter a number");
number_str = Console.ReadLine();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
}
Console.Write(i + " x ");
Console.Clear();
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
factorial = 1;
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
Thank you!
The problem is that your for loop isn't using braces, so the scope is just one line.
Try adding braces appropriately:
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i.ToString() + " x ");
}
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
Without the braces, the i variable only exists on the next statement (factorial = factorial * i;), and no longer exists in scope by the time you call Console.Write.
You will likely also want to remove the call to Console.Clear immediately following this Write, or you will not see it.
here's a solution to consider
public static void Main()
{
Console.WriteLine("Please enter number");
int input;
while (!int.TryParse(Console.ReadLine(), out input) || input <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
}
Console.Write("Factorial of " + input + " is : ");
int output = 1;
for (int i = input; i > 0; i--)
{
Console.Write((i == input) ? i.ToString() : "*" + i);
output *= i;
}
Console.Write(" = " +output);
Console.ReadLine();
}
int.TryParse() will be beneficial for you, so the program doesn't crash if the user inputs a non-integer
also, you may want something besides an integer. Factorials get very large very fast - anything over 16 will return a wrong result.