Whats wrong with my recursive factorial example code in C# [closed] - c#

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 2 years ago.
Improve this question
So I'm currently learning C# and I'm on Recursive Factorials, I followed instructions to create an example of the base case and the recursive case. But the program doesn't seem to be identifying my integer.
using System;
namespace Recursive_factorial
{
class Program
{
static void Main()
{
Factorial(5);
}
public static int Factorial(int n)
{
if (n == 0)
{
return 1; //base case
}
else
{
return n * Factorial(n - 1); //recursive case
}
}
}
}

maybe the problem is that you never show the result, try with
using System;
namespace Recursive_factorial
{
class Program
{
static void Main()
{
Console.WriteLine(Factorial(5));
}
public static int Factorial(int n)
{
if (n == 0)
return 1;
else
return n * Factorial(n - 1);
}
}
}
Also you can add
Console.ReadKey();
Below the Console.WriteLine, to pause the execution before it closes

Related

C# ureachable code detected with if and do while [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 0;
do
{
if (false)
{
Console.WriteLine("hold UP");
}
++x;
Console.WriteLine(x);
} while (false);
}
}
}
That's the compiler warning you that some part of your code will never be executed. In your case it refers to this part.
if (false)
{
Console.WriteLine("hold UP");
}
A similar thing would happen in cases like this:
void Test()
{
return;
// more code here.
}
//or
void Test2()
{
while(true) //loop forever.
{ }
// more code here.
}
Console.WriteLine("hold UP"); is unreachable because if (false) will never be true, thus the code in the following block can never be executed.
Andy is correct. For the code to run inside an If statement the conditions must be true. What you have there is a static condition of False, thus it will not enter into the If statement.

Show incremented value of i in a console [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to display an incremented value of an i in a loop of a console. That is, instead of showing "The object 0 has fallen", I want to display "The object 1 has fallen". How do I achieve this?
for(int i = 0; i<6; i++)
{
Debug.Log("The object: " +(i+1)+ " has fallen");
}
Your original sample works perfectly it already '
using System;
public class Program
{
public static void Main()
{
for(int i = 0; i<6; i++)
{
Debug.Log("The object: " +(i+1)+ " has fallen");
}
}
}
public static class Debug
{
public static void Log(string s) => Console.WriteLine(s);
}
https://dotnetfiddle.net/Q1shlY
prints:
The object: 1 has fallen
The object: 2 has fallen
The object: 3 has fallen
The object: 4 has fallen
The object: 5 has fallen
The object: 6 has fallen
You could of course also just start the loop at 1 instead of 0, also notice the change for the condition in the for loop from < to <=:
using System;
public class Program
{
public static void Main()
{
for(int i = 1; i<=6; i++)
{
Debug.Log("The object: " +i+ " has fallen");
}
}
}
public static class Debug
{
public static void Log(string s) => Console.WriteLine(s);
}
https://dotnetfiddle.net/rb76IS
prints:
The object: 1 has fallen
The object: 2 has fallen
The object: 3 has fallen
The object: 4 has fallen
The object: 5 has fallen
The object: 6 has fallen
A for-loop has 3 parts:
for(<initial state, runs once at beginning>; <condition, runs while true>; <iterator, runs after each iteration>
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for
So this does exactly what you're asking.

Clean code: How to refactor code to make it better removing the switch statement [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have the following code on my game:
public class EnemyCount : MonoBehaviour
{
public EnemyType et;
void Start()
{
int value=0;
switch(et){
case EnemyType.Warrior:
value = increasePlayerPrefs(Constantes.WARRIORS_KILLED);
achievementChecker(value, Constantes.WARRIOR_KILLER_ACHIEVEMENT, 20);
break;
case EnemyType.Mage:
value = increasePlayerPrefs(Constantes.MAGES_KILLED);
achievementChecker(value, Constantes.MAGE_KILLER_ACHIEVEMENT, 20);
break;
case EnemyType.BigKnight:
value = increasePlayerPrefs(Constantes.BIG_KNIGHTS_KILLED);
achievementChecker(value, Constantes.BIG_KNIGHT_KILLER_ACHIEVEMENT, 10);
break;
case EnemyType.Ranger:
value = increasePlayerPrefs(Constantes.RANGERS_KILLED);
achievementChecker(value, Constantes.RANGER_KILLER_ACHIEVEMENT, 20);
break;
case EnemyType.StrongWarrior:
value = increasePlayerPrefs(Constantes.STRONG_WARRIORS_KILLED);
achievementChecker(value, Constantes.STRONG_WARRIOR_KILLER_ACHIEVEMENT, 20);
break;
case EnemyType.Sorcerer:
value = increasePlayerPrefs(Constantes.SORCERERS_KILLED);
achievementChecker(value, Constantes.SORCERER_KILLER_ACHIEVEMENT, 1);
break;
default:
Debug.Log("Inimigo não identificado");
break;
}
}
public int increasePlayerPrefs(string StringConstant){
int val = PlayerPrefs.GetInt(StringConstant);
val = val + 1;
PlayerPrefs.SetInt(StringConstant,val);
PlayerPrefs.Save();
Debug.Log(StringConstant+" value: "+val);
return val;
}
public void achievementChecker(int enemiesKilled, string achievementConstant, int enemiesKilledToEnableAchievement){
if( enemiesKilled >= enemiesKilledToEnableAchievement ){
if(SteamManager.Initialized){
SteamUserStats.SetAchievement (achievementConstant);
SteamUserStats.StoreStats ();
Debug.Log("achievement complete: "+achievementConstant);
}
}
}
}
This code works, but I am learning Clean Code from "Uncle Bob" and he says that switches and if-else statements are evil because they break.
How can I change this code to make it better, using a "Clean code" approach?
I guess Polymorphism is the answer, but I don't know how to do that.
I don't believe switches and/or if/else's are inherently evil. They have their place in properly structured code.
But, how you are using in your example is probably not the best way to tackle what you want to accomplish. Imagine adding a new character class. You'd have to find everywhere you did a switch case or if/else and make sure to account for that.
You need to look in to polymorphism, a common OOP pattern.
For example:
public abstract class BasePlayerClass
{
protected abstract EnemyType EnemyType {get;}
public int IncreaseKilledPlayerPrefs()
{
// note: this code should be protected with thread synchronization
var val = PlayerPrefs.GetInt(EnemyType.ToString());
val = val + 1;
PlayerPrefs.SetInt(EnemyType.ToString(),val);
PlayerPrefs.Save();
Debug.Log(EnemyType.ToString()+" value: "+val);
return val;
}
}
public sealed class Mage : BasePlayerClass
{
protected override EnemyType EnemyType => EnemyType.Mage;
}
public sealed class Warrior : BasePlayerClass
{
protected override EnemyType EnemyType => EnemyType.Warrior;
}
So now when a Mage gets killed, you'd call theMage.IncreaseKilledPlayerPrefs()
You don't need to iterate through all the object types, because you already know the object type and the object can update everything itself. Then when you add a new player-class, you just create the new class, add the new enum and you are done.
Now, I'm not saying this is how you should do this, by any means. I am showing you how polymorphism can help you think more abstractly about the objects in your game and avoid iterating through types.

How do you end a method from code in another method? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
How do I end a method with logic in another method? It seems return only works in the method it is in.
private void BeAmazing (int number) {
HandleNumber(number);
Debug.Log("number is 3 or less");
}
private void HandleNumber(int number) {
if (number > 3) {
return;
}
}
Your inner function should return a result indicating whether it was successful in doing whatever it is supposed to do, like this:
private void BeAmazing (int number) {
if (!HandleNumber(number)) {
Debug.Log("number is 3 or less");
}
}
private bool HandleNumber(int number) {
if (number > 3) {
return true;
}
return false;
}
I have to guess a bit, as your description was insufficient. But I guess that FunctionA calls FunctionB - propably in some form of loop - and that in certain cases things that happen in FunctionB should also cancel the loop in FunctionA, thus ending FunctionA.
The primary way for this is throwing Exceptions. Exceptions will just plow through all brackets, until they find catch block. And the last one is in the Framework itself. There are two articles on excetpion handling, that a link often.
However one rule the mention is to not throw exceptions in situations that are not exceptional. And this case might not be exceptional. Well, for those cases there are out parameters:
void FunctionA(){
bool continueLoop = true;
while(continueLoop){
FunctionB(out continueLoop);
}
}
void FunctionB(out bool continueLoop){
//Set the bool, for out parameters this will change it back in FunctionA
continueLoop = false;
}
Of course there is also the way more common case of Recursion, where FunctionA and FunctionB are either the same, or B keeps calling itself. This is often better then using a loop like this.
Robert McKee has got the question covered, but here are two little examples how
HandleNumber could communicate with BeAmazing using an exception.
Please note that an if is the simplest solution here. The examples below are just to show another possibility.
Example 1
Task: Print the message if number is 3 or less without modifying BeAmazing.
private void BeAmazing (int number)
{
HandleNumber(number);
Debug.WriteLine("number is 3 or less");
}
private void HandleNumber(int number) {
if (number > 3) {
throw new Exception("Number is > 3");
}
}
public static void Main()
{
var p = new Program();
try
{
p.BeAmazing(5);
}
catch (Exception ex )
{
Console.WriteLine(ex.Message);
}
p.BeAmazing(3);
Number is > 3
number is 3 or less
Example 2
Task: Make BeAmazing print different messages if number is >3 or not without modifying the signature of HandleNumber.
private void BeAmazing (int number)
{
try
{
HandleNumber(number);
Console.WriteLine($"This number is amazing");
}
catch( Exception ex )
{
Console.WriteLine(ex.Message);
}
}
private void HandleNumber(int number) {
if (number > 3) {
return;
}
throw new Exception("Number is 3 or less");
}
public static void Main()
{
var p = new Program();
p.BeAmazing(5);
p.BeAmazing(3);
}
This number is amazing
Number is 3 or less

I cannot solve this simple exercise in Deitel Visual C# 2010 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've been studying Deitel's Visual C# 2010. I'm stuck at an exercise in the chapter about arrays. It's been bugging me for days now, and I've written the code several times now and each times something goes wrong.
The exercise is asking to develop a new reservation system for a small airline company. The capacity of an airplane is 10 seats. So you ask the customer to input 1 for First Class and 2 for Economy. Seats from 1 to 5 are for first class. Seats from 6 to 10 are for economy.
I must use a one-dimensional array of type bool to represent the seating char of the plane. Initialize all elements of the array to false to represent vacant seats (Luckily bool initializes to false anyway, because I do not know how to initialize an array). As each seat is assigned, set the corresponding element in the plane to true.
The app should never assign a seat that's already been seated. When the economy class is full, the app should ask the customer if he wants to fly in first class (and vice versa). If the customer responds with yes, assign him in the economy class (if there's an empty seat there). If there is no empty seats in economy or the customer refuses to fly in first class, then just display to him that "The next flight is after three hours!).
I'm self-studying the book. This is not an assignment or homework. I really do not wish to post the code I've written because I want a completely fresh way to solve the problem, but I'm pretty sure that I will be asked about the code, so here it is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Craps_Game
{
class AirlineReservation
{
private static bool[] seats = new bool[10];
private static void FirstClass(ref bool[] seats)
{
for(int i = 0; i < 5; i++)
{
if (seats[i] == false)
{
seats[i] = true;
Console.WriteLine("Your seat number is " + i);
break;
}
else
{
Console.WriteLine("First Class is full. Would you like to fly Economy?");
if (Console.ReadLine().ToLower() == "y")
Economy(ref seats);
else
Console.WriteLine("The next flight is in three hours!. Good bye");
}
}
}
private static void Economy(ref bool[] seats)
{
for (int i = 5; i < 10; i++)
if (seats[i] == false)
seats[i] = true;
else
{
Console.WriteLine("Economy class is full. Would you like to fly First Class");
if (Console.ReadLine().ToLower() == "y")
FirstClass(ref seats);
else
Console.WriteLine("The next flight is in three hours!. Good Bye");
}
}
public static void Reservation()
{
do
{
Console.WriteLine("Enter 1 to fly First Class");
Console.WriteLine("Enter 2 to fly Economy Class");
if (Convert.ToInt32(Console.ReadLine()) == 1)
FirstClass(ref seats);
else
Economy(ref seats);
} while (true);
}
}
}
Bear in mind that I would prefer a completely different way of solving the problem, instead of fixing this one :)
I don't want to solve the entire problem in code since you are learning, but I will show you the major things I saw in your code that is a bug.
Your Economy method was not exiting the loop if it found that a
seat was available. It needed to break.
Your else when you did not find a seat was not checking if all of the seats were taken. Checking if i == 9 will make it so it will only go to FirstClass if there are no more seats, not before.
private static void Economy(ref bool[] seats)
{
for (int i = 5; i < 10; i++)
{ // <---- Added the brackets
if (seats[i] == false)
{
seats[i] = true;
break; // <----- You forgot to break when you reserved a seat.
}
else if (i == 9) // <---- You weren't checking if all seats are taken.
{
Console.WriteLine("Economy class is full. Would you like to fly First Class");
if (Console.ReadLine().ToLower() == "y")
FirstClass(ref seats);
else
Console.WriteLine("The next flight is in three hours!. Good Bye");
}
}
}
I like the way you approach programming and your task and this site!
Therefore I would hate to write out the code for you - all the fun is getting it done by yourself. But since you are stuck let me give you a few hints:
Starting at the bottom, the first thing that comes to mind is that you are always offering both classes even when one or both are full. Here is a function header that could help to break things down even further than you already have done:
public int getFirstVacantSeatIn(int classType)
// returns 1-5 for classType=1, 6-10 for classType=2, -1 if classType is full
You can use this function to make the prompt dynamic like this:
Console.WriteLine( ( getFirstVacantSeatIn(1) >= 0 ?
"Enter 1 to fly First Class") : "First Class is full");
And you can reuse it when you try to assign the new seats..:
Another point is that you offer switching between classes when one is full without checking if the other one actually isn't full, too. I suspect that is the problem you are facing?
So you should check before offering to up- or downgrade.. The above function will help here as well. If you can re-use something, chances are that it was right to create that thing..
The secret is ever so often to break your problem down further and further until it goes away, always using/creating useful names for the sub-problems..
"I must use a one-dimensional array of type bool to represent the seating char of the plane"
"I want a completely fresh way to solve the problem"
"Bear in mind that I would prefer a completely different way of solving the problem, instead of fixing this one"
So be it! Others have given you really good advice already, but here's "fresh" way to do it.
using System;
namespace FunnyConsoleApplication
{
public class Program
{
static void Main(string[] args)
{
Airplane plane = new Airplane();
bool reserve = true;
while (reserve)
{
Console.Clear();
Console.WriteLine("Enter [1] to fly First Class ({0} vacant)", plane.VacantFirstClassSeats());
Console.WriteLine("Enter [2] to fly Economy Class ({0} vacant)", plane.VacantEconomySeats());
string input = Console.ReadLine();
switch (input)
{
case "1":
if (plane.HasFirstClassSeats)
{
plane.ReserveFirstClassSeat();
}
else if (plane.HasEconomySeats)
{
if (IsOk("No vacancy, enter [y] to fly Economy instead?"))
plane.ReserveEconomySeat();
else
reserve = false;
}
else
{
reserve = false;
}
break;
case "2":
if (plane.HasEconomySeats)
{
plane.ReserveEconomySeat();
}
else if (plane.HasFirstClassSeats)
{
if (IsOk("No vacancy, enter [y] to fly First Class instead?"))
plane.ReserveFirstClassSeat();
else
reserve = false;
}
else
{
reserve = false;
}
break;
}
Console.WriteLine();
}
Console.WriteLine("No can do, good bye!");
Console.ReadLine();
}
private static bool IsOk(string question)
{
Console.WriteLine(question);
return string.Compare(Console.ReadLine(), "y", StringComparison.OrdinalIgnoreCase) == 0;
}
}
public class Airplane
{
private readonly bool[] _seats = new bool[10];
public bool HasFirstClassSeats
{
get { return HasSeats(0); }
}
public bool HasEconomySeats
{
get { return HasSeats(5); }
}
public int VacantFirstClassSeats()
{
return GetVacant(0);
}
public int VacantEconomySeats()
{
return GetVacant(5);
}
public void ReserveFirstClassSeat()
{
Reserve(0);
}
public void ReserveEconomySeat()
{
Reserve(5);
}
private bool HasSeats(int index)
{
for (int i = index; i < index + 5; i++)
{
if (!_seats[i])
return true;
}
return false;
}
private int GetVacant(int index)
{
int count = 0;
for (int i = index; i < index + 5; i++)
{
if (!_seats[i])
count++;
}
return count;
}
private void Reserve(int index)
{
for (int i = index; i < index + 5; i++)
{
if (!_seats[i])
{
_seats[i] = true;
break;
}
}
}
}
}
Which gives you

Categories

Resources