My code finds prime numbers in a given range. I want to make a menu in the end of it that will ask if i want to save output numbers to a file and then save it. I would really appreciate any help.
using System;
public class Exercise34
{
public static void Main()
{
int num,i,ctr,stno,enno;
Console.Write("\n\n");
Console.Write("Find the prime numbers within a range of numbers:\n");
Console.Write("---------------------------------------------------");
Console.Write("\n\n");
Console.Write("Input starting number of range: ");
stno = Convert.ToInt32(Console.ReadLine());
Console.Write("Input ending number of range : ");
enno = Convert.ToInt32(Console.ReadLine());
Console.Write("The prime numbers between {0} and {1} are : \n",stno,enno);
for(num = stno;num<=enno;num++)
{
ctr = 0;
for(i=2;i<=num/2;i++)
{
if(num%i==0){
ctr++;
break;
}
}
if(ctr==0 && num!= 1)
Console.Write("{0} ",num);
}
Console.Write("\n");
}
}
I suggest extracting method(s): do not cram everything into single Main, decompose the solution into easy to read and debug routines
private static bool IsPrime(int value) {
if (value <= 1)
return false;
if (value % 2 == 0)
return value == 2;
int n = (int) (Math.Sqrt(value) + 0.5);
for (int i = 3; i <= n; i += 2)
if (value % i == 0)
return false;
}
private static IEnumerable<int> Primes(int from, int to) {
if (to <= 1)
yield break;
if (from < 2)
from = 2;
for (int value = from; value <= to; ++value)
if (IsPrime(value))
yield return value;
}
And then you put it as simple as (output to Console)
public static void Main() {
...
Console.Write("The prime numbers between {0} and {1} are : \n",stno,enno);
foreach (int value in Primes(stno, enno))
Console.WriteLine(value);
}
or (output to File)
using System.IO;
using System.Linq;
...
public static void Main() {
...
Console.Write("The prime numbers between {0} and {1} are : \n",stno,enno);
File.WriteAllLines(#"c:\MyFile.txt", Primes(stno, enno)
.Select(value => value.ToString()));
}
Related
so we can give any number of parameters to a method, like this:
static int sumPrices(params int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
int total = sumPrices(100, 50, 200, 350);
Console.WriteLine(total);
Console.ReadKey();
}
but ... what if we wanted to get the "100, 50, 200, 350" from the USER?
in above example it's the coder giving the sumPrices method its arguments/parameters.
i mean, it would be one solution to just pass the method an array.
static int sumPrices(int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
//get up to 9999 inputs and sum them using a method
bool whileLoop = true;
int[] inputs = new int[9999];
int index = 0;
while (whileLoop == true)
{
Console.WriteLine("entering price #" + index + ", type 'stop' to sum prices");
string check = Console.ReadLine();
if (check == "stop") {
whileLoop = false;
break;
}
inputs[index] = int.Parse(check);
index++;
}
int[] prices = new int[index];
for (int i = 0; i < index; i++)
{
prices[i] = inputs[i];
}
Console.WriteLine("-----------------");
Console.WriteLine(sumPrices(prices));
Console.ReadKey();
}
BUT... longer code... and has limits.
our professor basically wanted the first code, however, i don't see how and where it's
supposed be used if we didn't know the user's inputs and if params arguments were coming from the coder (unless of course, coder using the same function multiple times for convenience)
i have tried to think of a solution and i'm not exactly sure how it could be done.
but it basically goes like this.
we could get inputs from the user separated by commas:
100,200,50
and the program would translate it into params arguments:
sumPrices("100,200,50");
but as you can see... it's a string. i wonder if there's a JSON.parse() thing like in js.
The code in the OP has some unnecessary code as well as some limitations such as 9999.
Let's examine the following code:
bool whileLoop = true;
while (whileLoop == true)
{
}
This could be re-written as:
while (true == true)
{
}
or
while (true)
{
}
Next, let's examine the following code:
if (check == "stop") {
whileLoop = false;
break;
}
You've set whileLoop = false; which is unnecessary because once break is executed, excution has moved to after the loop.
Since the input array has a hard-code size of 9999, you've limited yourself to 9999 values. You may consider using a List instead or resize the array.
Try the following:
using System;
using System.Collections.Generic;
using System.Linq;
namespace UserInputTest
{
internal class Program
{
static void Main(string[] args)
{
decimal price = 0;
List<decimal> _values = new List<decimal>();
if (args.Length == 0)
{
//prompts for user input
Console.WriteLine("The following program will sum the prices that are entered. To exit, type 'q'");
do
{
Console.Write("Please enter a price: ");
string userInput = Console.ReadLine();
if (userInput.ToLower() == "q")
break; //exit loop
else if (Decimal.TryParse(userInput, out price))
_values.Add(price); //if the user input can be converted to a decimal, add it to the list
else
Console.WriteLine($"Error: Invalid price ('{userInput}'). Please try again.");
} while (true);
}
else
{
//reads input from command-line arguments instead of prompting for user input
foreach (string arg in args)
{
if (Decimal.TryParse(arg, out price))
{
//if the user input can be converted to a decimal, add it to the list
_values.Add(price); //add
}
else
{
Console.WriteLine($"Error: Invalid price ('{arg}'). Exiting.");
Environment.Exit(-1);
}
}
}
Console.WriteLine($"\nThe sum is: {SumPrices(_values)}");
}
static decimal SumPrices(List<decimal> prices)
{
return prices.Sum(x => x);
}
static decimal SumPricesF(List<decimal> prices)
{
decimal sum = 0;
foreach (decimal price in prices)
sum += price;
return sum;
}
}
}
Usage 1:
UserInputTest.exe
Usage 2:
UserInputTest.exe 1 2 3 4 5
Resources:
Built-in types (C# reference)
Floating-point numeric types (C# reference)
Decimal.TryParse
Iteration statements - for, foreach, do, and while
String interpolation using $
List Class
Enumerable.Sum Method
Default values of C# types (C# reference)
Environment.Exit
The trick is input from the user always starts out as strings. You must parse those strings into integers. We can do it in very little code like this:
static int sumPrices(IEnumerable<int> prices)
{
return prices.Sum();
}
static void Main(string[] args)
{
int total = sumPrices(args.Select(int.Parse));
Console.WriteLine(total);
Console.ReadKey();
}
See it here (with adjustments for the sandbox environment):
https://dotnetfiddle.net/Pv6B6e
Note this assumes a perfect typist. There is no error checking if a provided value will not parse.
But I doubt using linq operations are expected in an early school project, so we can expand this a little bit to only use techniques that are more familiar:
static int sumPrices(int[] prices)
{
int total = 0;
foreach(int price in prices)
{
total += price;
}
return total;
}
static void Main(string[] args)
{
int[] prices = new int[args.Length];
for(int i = 0; i<args.Length; i++)
{
prices[i] = int.Parse(args[i]);
}
int total = sumPrices(prices);
Console.WriteLine(total);
Console.ReadKey();
}
If you're also not allowed to use int.Parse() (which is nuts, but sometimes homework has odd constraints) you would keep everything else the same, but replace int.Parse() with your own ParseInt() method:
static int ParseInt(string input)
{
int exponent = 0;
int result = 0;
for(int i = input.Length -1; i>=0; i--)
{
result += ((int)(input[i]-'0') * (int)Math.Pow(10, exponent));
exponent++;
}
return result;
}
Again: there's no error checking here for things like out-of-bounds or non-numeric inputs, and this particular implementation only works for positive integers.
I'm having trouble with the counter variable. Every time I leave each method, count is re-initialized to 0. I haven't completed the Stay() method the Hit() method is killing. After every Hit I need to display all of the user's cards. I do not know how to do this. There has to be a more efficient way. I think all my problems arise from the problem with the Count variable.
Thanks for any help.
Below is my main class. Below that is my Deck class.
I left out the Card, Suit and Rank class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlkJack
{
class Program
{
static void Main(string[] args)
{
string name;
int Chips = 500;
int Wage;
int count = 0;
string HS;
Card pCard1, dCard1, pCard2, dCard2;
int playerHand, dealerHand;
//int chipsWon;
Console.WriteLine("Welcome to Johnny's BlackJack!");
Console.WriteLine("You are given $500 to play with.");
Console.WriteLine("Table Limit is $250 per hand. <Enter a 0 to quit>");
name = GetName("Enter name: ");
Console.WriteLine("Hello {0}, you are ${1} ahead.", name, Chips);
Wage = getWager("What is your wager?: ", 1, 250, "?Value must be an integer.", "Max bet is 250!");
Deck d = new Deck();
startingHand(count, d, out pCard1, out dCard1, out pCard2, out dCard2, out playerHand, out dealerHand);
Console.WriteLine("Your hand: {0}, {1} <{2}> ", pCard1, pCard2, playerHand);
Console.WriteLine("<Dealer's show card is {0}>", dCard1);
count = count + 4;
HS = HitorStay("Do you want to <H>it or <S>tay?: ", count, playerHand, d);
while (HS == "H" || HS == "HIT")
{
HS = HitorStay("Do you want to <H>it or <S>tay?: ", count, playerHand, d);
Console.WriteLine("Your cards: {0} {1} <{2}>", pCard1, pCard2, playerHand);
//Console.WriteLine("{0}", count);
}
}
static string GetString(string prompt, string[] valid, string error)
{
string response;
bool OK = false;
do
{
Console.Write(prompt);
response = Console.ReadLine().ToUpper();
foreach (string s in valid) if (response == s) OK = true;
if (!OK) Console.WriteLine(error);
}
while (!OK);
return response;
}
static string GetName(string prompt)
{
string response;
Console.Write(prompt);
response = Console.ReadLine();
while (response == "0")
{
Environment.Exit(0);
}
return response;
}
static bool GetYesNo(string prompt)
{
string[] valid = { "YES", "Y", "NO", "N" };
string ans = GetString(prompt, valid, "Invalid response. Please reenter.");
return (ans == "YES" || ans == "Y");
}
static int getWager(string prompt, int low, int high, string errorInt, string errorRange)
{
int Wager;
string userInput;
bool OKInt = false, OKRange = false;
do
{
Console.Write(prompt);
userInput = Console.ReadLine();
OKInt = Int32.TryParse(userInput, out Wager);
if (OKInt)
{
OKRange = low <= Wager && Wager <= high;
if (!OKRange) Console.WriteLine(errorRange);
}
else
Console.WriteLine(errorInt);
}
while (!OKInt || !OKRange);
return Wager;
}
public static int startingHand(int count, Deck d, out Card pCard1, out Card dCard1, out Card pCard2, out Card dCard2, out int playerHand, out int dealerHand)
{
playerHand = 0; dealerHand = 0;
if (count == 0 || count >= 42) d.Shuffle();
for (int i = 0; i < 52; i++)
Console.Write("{0},", d.GetCard(i));
pCard1 = d.GetCard(count);
count++;
dCard1 = d.GetCard(count);
count++;
pCard2 = d.GetCard(count);
count++;
dCard2 = d.GetCard(count);
count++;
playerHand = pCard1.GetValue() + pCard2.GetValue();
dealerHand = dCard1.GetValue() + dCard2.GetValue();
return count;
}
static string HitorStay(string prompt, int count, int playerHand, Deck d)
{
string[] valid = { "HIT", "H", "STAY", "S" };
string HS = GetString(prompt, valid, "?Invalid Response. (H)it or (S)tay?");
if (HS == "HIT" || HS == "H")
{
Hit(count, playerHand, d);
}
//else if (HS == "STAY" || HS == "S")
//{
//Stay(count, playerHand, dealerHand, out chipStay);
//}
else Environment.Exit(0);
return HS;
}
public static int Hit(int count, int playerHand, Deck d)
{
count += 1;
playerHand += d.GetCard(count).GetValue();
return playerHand;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlkJack
{
class Deck
{
private Card[] cards = new Card[52];
public Deck()
{
for (int suitVal=0; suitVal<4; suitVal++)
{
for (int rankVal = 0; rankVal < 13; rankVal++)
{
cards[suitVal * 13 + rankVal] =
new Card((Suit)suitVal, (Rank)(rankVal));
cards[suitVal * 13 + rankVal].SetValue(rankVal);
if (rankVal > 9) cards[suitVal * 13 + rankVal].SetValue(10);
if (rankVal == 1) cards[suitVal * 13 + rankVal].SetValue(11);
if (rankVal == 0) cards[suitVal * 13 + rankVal].SetValue(10);
}
}
}
public Card GetCard(int cardNum)
{
return cards[cardNum];
}
public void Shuffle()
{
Card[] newDeck = new Card[52]; // cards randomly assigned to locs in newDeck
bool[] assigned = new bool[52]; // keep track of what locs used in newDeck
int seed = 0;
Console.Write("Enter seed: ");
seed = Convert.ToInt32(Console.ReadLine()); // yes, stupid user can break
Random rGen = new Random(seed);
for (int i=0; i<52; i++)
{
int destCard = 0; // where card is going to be put
bool foundCard = false;
while (foundCard == false)
{
destCard = rGen.Next(52);
if (assigned[destCard] == false)
foundCard = true;
}
assigned[destCard] = true;
newDeck[destCard] = cards[i];
}
newDeck.CopyTo(cards, 0); //.CopyTo(destination, start index)
}
}
}
Look at this code
public static int Hit(int count, int playerHand, Deck d)
{
count += 1;
You are passing in a copy of count and incrementing that copy. The original value you passed in is never affected. Straightforward fixes include
Pass count by reference ref int count.
Make count a static class field rather than a local variable in Main()
A much better way would be to encapsulate your logic in a class and make count a field or property of that class, so that class methods can see and change it.
I wrote this little program that catches five integer numbers that are entered consecutively at the console.
This works as expected - except for one thing:
I did not find a way to accept 0 as one of the numbers being entered.
Of course, a solution with another collection type is easy.
But the challenge here is to do it with an array of five integers.
I tried to set a boolean flag "zeroEntered", tried with a counter, tried to count j backwwards. It all does not work.
Perhaps this is not possible? Would somebody know for sure?
Here is the code:
class Program
{
static void Main(string[] args)
{
#region Catch5IntegerInArrayOfInt[5]
// I try to catch five integers in an array of int[5]
// This works as expected except I cannot catch 0 as one of the numbers
// Cannot wrap my head around this one it seems
// because all ints are initialized with 0
Console.WriteLine("Please enter five unique numbers consecutively.");
int[] fiveNumbers = new int[5]; // do it using an array just the same (as collections were not part of the lectures so far)
for (int i = 0; i < fiveNumbers.Length; i++)
{
Console.WriteLine("Please enter your {0} number:", (Countables)i);
CatchUsersNumbers(fiveNumbers, i);
}
DisplayResult(fiveNumbers);
Console.WriteLine("\n");
}
#endregion
#region HelperMethods
private static bool CheckWhetherInteger(string userInput)
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
return result;
}
private static bool CheckUniqueness(int[] fiveNumbers, int userInput)
{
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (userInput == 0)
{
for (int j = i ; j <fiveNumbers.Length; j--)
{
if (j == 0)
break;
if (fiveNumbers[j] == 0)
{
return false;
}
}
}
else if (fiveNumbers[i] == userInput)
{
return false;
}
}
return true;
}
private static void CatchUsersNumbers(int[] fiveNumbers, int i)
{
while (true)
{
userInput = Console.ReadLine().Trim();
if (CheckWhetherInteger(userInput) && CheckUniqueness(fiveNumbers, myInteger))
{
fiveNumbers[i] = myInteger;
break;
}
else
Console.Clear();
Console.WriteLine("You did not enter a unique integer number, try again...");
}
}
private static void DisplayResult(int[] fiveNumbers)
{
Console.Clear();
Array.Sort(fiveNumbers);
Console.WriteLine("These are the five interger numbers you entered \nand that were stored in the array:\n");
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (i != fiveNumbers.Length - 1)
Console.Write(fiveNumbers[i] + ", ");
else
Console.Write(fiveNumbers[i]);
}
}
#endregion
#region Class Variables
private static int myInteger = 0;
private static string userInput;
private enum Countables
{
first = 0,
second,
third,
fourth,
fifth
}
#endregion
}
Thank you.
It is possible, but your array of 5 ints will be initialized to 5 zeroes, so when scanning for uniqueness, your check fails, especially because of this piece of code:
if (fiveNumbers[j] == 0)
{
return false;
}
So instead of looping through the entire array, you should keep a counter to keep track of how many items you already have in your array. Then, when performing the check, only check upto that index, and don't include the other items in the check, because they contain 0, but you should treat them as uninitialized.
You could also solve this using other data types. For instance, you could create an array of nullable integers, so you can actually check whether an item already got a value. Or (maybe the best solution) you could use a List instead of array.
Your Only error here is that int.TryParse() takes 0 as invalid you could make another if statement to handle the exception but this looks less clean
private static bool CheckWhetherInteger(string userInput)
{
if (userInput == "0")
{
myInteger = 0;
return true
}
else
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
}
return result;
}
I just post the solution - using nullable integers - as suggested by Golez Trol. Here it is, should somebody be interested:
class Program
{
static void Main(string[] args)
{
#region Catch5IntegerInArrayOfInt[5]
// The solution to catching five integers in an array of int[5]
// is to use nullable integers.
// Keeping a counter when entering an integer to the array does not appeal to me.
// With normal integers I cannot catch 0 as one of the numbers
// because all ints are initialized with 0
Console.WriteLine("Please enter five unique numbers consecutively.");
var fiveNumbers = new int?[5]; // do it using an array just the same (as collections were not part of the lectures so far)
for (int i = 0; i < fiveNumbers.Length; i++)
{
Console.WriteLine("Please enter your {0} number:", (Countables)i);
CatchUsersNumbers(fiveNumbers, i);
}
DisplayResult(fiveNumbers);
Console.WriteLine("\n");
}
#endregion
#region HelperMethods
private static void CatchUsersNumbers(int?[] fiveNumbers, int i)
{
while (true)
{
userInput = Console.ReadLine().Trim();
if (CheckWhetherInteger(userInput) && CheckUniqueness(fiveNumbers, myInteger))
{
fiveNumbers[i] = myInteger;
break;
}
else
{
Console.Clear();
Console.WriteLine("You did not enter a unique integer number, try again...");
}
}
}
private static bool CheckWhetherInteger(string userInput)
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
return result;
}
private static bool CheckUniqueness(int?[] fiveNumbers, int userInput)
{
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (fiveNumbers[i] == userInput)
{
return false;
}
}
return true;
}
private static void DisplayResult(int?[] fiveNumbers)
{
Console.Clear();
Array.Sort(fiveNumbers);
Console.WriteLine("These are the five interger numbers you entered \nand that were stored in the array:\n");
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (i != fiveNumbers.Length - 1)
Console.Write(fiveNumbers[i] + ", ");
else
Console.Write(fiveNumbers[i]);
}
}
#endregion
#region Class Variables
private static int myInteger = 0;
private static string userInput;
private enum Countables
{
first = 0,
second,
third,
fourth,
fifth
}
#endregion
}
Thank you for your hints - I was truly stuck.
here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.
My factorial calculator isn't working quite correctly.
It works as expected from 1 to 20, as my professor wants. However, entering 0 should return a factorial of 1; it returns 0
Here is my code:
private void CalculateFactorial(long number)
{
//perform the calculations
long result = number;
for (int i = 1; i < number; i++)
{
result = result * i;
}
//display the calculated Factorial to the user
txt_Factorial.Text = result.ToString("n0");
}
Here is the method which calls the above method, the event handler for the calculate button:
private void btn_Calculate_Click(object sender, EventArgs e)
{
//get the users input
long number = long.Parse(txt_Number.Text);
// make sure the number not invalid. If it is invalid, tell the user
// otherwise, proceed to calculation.
if (number < 0 || number > 20)
txt_Factorial.Text = "Invalid Number";
else
CalculateFactorial(number);
txt_Number.Focus(); // returns the focus to the number box whether or not data was valid
Ideas?
If you step through this in a debugger the problem becomes pretty clear. And as you're just getting started with programming I highly recommend getting used to a debugger as early as you can. It's an absolutely invaluable tool for programming.
Look at your for loop:
for (int i = 1; i < number; i++)
What happens when number is 0? The loop never runs. You can't include 0 in the loop range because that would set every result to 0 by first multiplying it by 0. So you need to add an explicit check for 0 in the function logic:
if (number == 0)
return 1;
// continue with your loop here
Factorial of 0 is 1 by definition, not by calculation, and your code does not reflect that. Add a check before your code:
if (number == 0)
result = 1;
else
// compute factorial
Also think about creating a function that returns an integer value as the result.
You can use this :
if(number == 0){
result = 1;
}
for (int i = 1; i <= number; i++)
result *= i;
}
also your formula is wrong because n! = 1*2*3*.....*n
You can test the following code! tested and works. Recursive Implementation as well as basic implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Please Enter Factorial Number:");
int a= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("---Basic Calling--");
Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));
Console.WriteLine("--Recursively Calling--");
Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
public int recursively(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return recursively(num - 1) * num;
}
}
}
}