Struggling With Instructor Tutorial - c#

I had an assignment that required me to request an array size from the user and then request numbers to fill the array. The program was to print only the unique numbers for each loop. It also would notify the user if the number they entered was a duplicate. I have completed this and it worked as it should. The instructor then posted a tutorial video on how it could/should have been written. That code is quite different from mine and I tried to rewrite it to understand her logic. I could not get it to work as the tutorial showed and I am not understanding some of the things she included. Can someone look at this and help me understand what she is trying to do and if it works as written?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DuplicateHandsOn
{
class Program
{
static void Main(string[] args)
{
//create an array of type int
int[] aList;
//create a counter to keep track of how many numbers have been entered
int counter = 0;
//create a boolean flag to let us know whether the number can be added or not
bool isDuplicate = false;
//ask the user how many numbers they will be entering
Console.WriteLine("How many numbers will you enter?");
int arraySize = Convert.ToInt32(Console.ReadLine());
//initialize the array with that amount
aList = new int[arraySize];
while (counter < arraySize)
{
//prompt the user for the first number
Console.Write("Enter Number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
//check if the number is between 10 and 100
if (num1 >= 10 || num1 <= 100)
{
//check if this number exists in the array
for (int i = 0; i < aList.Length; i++)
{
if (aList[i] == num1)
{
//this number exists in the list
Console.WriteLine("{0} has already been entered", aList[i]);
isDuplicate = true;
}
}
if (isDuplicate)
{
//put the number into the array
aList[counter] = num1;
}
//print the array
for (int j = 0; j < aList.Length; j++)
{
//exclude zeros
if (aList[j] == 0)
{
continue;
}
else
{
Console.WriteLine(aList[j]);
}
}
//increment the counter
counter++;
//reset the flag
isDuplicate = false;
}
else
{
Console.WriteLine("Numbers should be between 10 and 100");
}
}
#if DEBUG
Console.ReadKey();
#endif
}
}
}

There are three bugs in the code, and lots of style issues I'd have with it, but the bugs are easy to point out. I've added // FIX comments to show what I changed, hopefully it makes sense.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DuplicateHandsOn
{
class Program
{
static void Main(string[] args)
{
//create an array of type int
int[] aList;
//create a counter to keep track of how many numbers have been entered
int counter = 0;
//create a boolean flag to let us know whether the number can be added or not
bool isDuplicate = false;
//ask the user how many numbers they will be entering
Console.WriteLine("How many numbers will you enter?");
int arraySize = Convert.ToInt32(Console.ReadLine());
//initialize the array with that amount
aList = new int[arraySize];
while (counter < arraySize)
{
//prompt the user for the first number
Console.Write("Enter Number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
// FIX: This should be && instead of || to test if
// both of these conditions are true to match
// the comment
//check if the number is between 10 and 100
if (num1 >= 10 && num1 <= 100)
{
//check if this number exists in the array
for (int i = 0; i < aList.Length; i++)
{
if (aList[i] == num1)
{
//this number exists in the list
Console.WriteLine("{0} has already been entered", aList[i]);
isDuplicate = true;
}
}
// FIX: This should only happen if the number
// is not a duplicate
if (!isDuplicate)
{
//put the number into the array
aList[counter] = num1;
// FIX: Move this line into here to only increment
// the counter if th enumber is placed in the array
//increment the counter
counter++;
}
//print the array
for (int j = 0; j < aList.Length; j++)
{
//exclude zeros
if (aList[j] == 0)
{
continue;
}
else
{
Console.WriteLine(aList[j]);
}
}
//reset the flag
isDuplicate = false;
}
else
{
Console.WriteLine("Numbers should be between 10 and 100");
}
}
#if DEBUG
Console.ReadKey();
#endif
}
}
}

Related

Entering elements into an array and checking to see if the element already exists [duplicate]

This question already has answers here:
Check if a value is in an array (C#)
(10 answers)
Closed 4 years ago.
I'm working on a problem and i've tried it every way I can think of with a for loop but i can't figure out how to make it work as I only started on c# and programming as a whole a few weeks ago.
Write an app that inputs five numbers. As each number is read search the array if the number doesn’t exist in the array output the word “new” and insert the number into the array. If the number does exist in the array output “exists”. Once all five numbers have been entered output the content of the array.
This is what I have so far. Thanks for any help
using System;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
array[i] = Convert.ToInt32(Console.ReadLine());
for (int a = 0; a < 5; a++)
{
if (array[i] != array[a])
{
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("new\n");
}
}
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("exists\n");
}
Console.WriteLine(array);
Console.ReadKey();
}
} // end class
First of all try thinking about a solution before you actually start writing some code, couple of hints
You expect some user input, we will use a variable to save the user input
You need to validate that the values does not exist in you array or structure, this can be done using the Contains method.
If it exists we continue to the next user input and print the required message.
If the value does not exists we add the value and print the new message
We will do this until the Count of the structure is equal to 5.
for reference use this While loop, Hashset.Contains and Hashset
try this:
var numbers = new HashSet<int>();
while(numbers.Count < 5)
{
Console.WriteLine("Enter a number:"); //1.
var number = Convert.ToInt32(Console.ReadLine());
if (numbers.Contains(number)) // 2.
{
Console.WriteLine("exists\n"); //3.
continue;
}
Console.WriteLine("new\n"); //4.
numbers.Add(number);
}
foreach (var n in numbers)
{
Console.WriteLine(n);
}
Use .Any() in System.Linq. Also, you don't need to continuously grab user input in your loop:
using System;
using System.Linq;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// Get user input and convert to integer:
int input = Convert.ToInt32(Console.ReadLine());
// Check if given input is already in the array:
if (! array.Any(number => number == input))
{
array[i] = input;
Console.WriteLine("new\n");
}
else
{
Console.WriteLine("exists\n");
}
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
Edit: Another variant if you want the user to fill the array completely:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
// Btw, if this is not an array of nullables,
// we will not be able to insert a zero later, as
// we will treat them as duplicates.
int?[] array = new int?[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
int input = 0;
bool duplicateAttempt = false;
do {
// Get and convert the input.
input = Convert.ToInt32(Console.ReadLine());
// See if this number is already in.
duplicateAttempt = array.Contains(input);
// Report if we attempt to insert a duplicate.
if (duplicateAttempt) Console.WriteLine("exists");
}
while (duplicateAttempt); // Keep asking while we don't get a unique number.
array[i] = input; // Store the number
Console.WriteLine("new");
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
A couple of issues with your code. You should only increment the array index if successful - otherwise the missing values will be zero. It's also a good idea to validate the input in case the user entered an invalid value. You can use linq to check if the value already exists in the array:
Here's an example:
static void Main(string[] args)
{
int[] array = new int[5];
var index = 0;
while (index < array.Length)
{
Console.WriteLine("Enter a number:");
var input = Console.ReadLine();
var value = 0;
if (!int.TryParse(input, out value))
{
Console.WriteLine("Error - value entered was not a number");
}
else
{
var match = array.Where(a => a == value);
if (match.Any())
{
Console.WriteLine("exists\n");
}
else
{
array[index] = value;
Console.WriteLine("new\n");
index++;
}
}
}
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
This appears to be a homework question, so I think it's more helpful to explain what you've done wrong and tell you what you should do...
It won't help you learn to copy and paste other people's answers.
using System;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// you are putting the value into your array here. so it will always 'exist' below
array[i] = Convert.ToInt32(Console.ReadLine());
// you need to do this check before you insert the number into the array
// put the ReadLine into a variable, not directly into the array.
// then check if it's in the array already
for (int a = 0; a < 5; a++)
{
if (array[i] != array[a])
{
// here you are trying to read another value from the user.
// Console.ReadLine() will always wait for user input
// use the variable from above. but only after you have looped through all the items.
// and verified that it is not present
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("new\n");
}
}
// this is the third time you have assigned the number to the array
// and the third time you've asked for user input per loop
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("exists\n");
}
Console.WriteLine(array);
Console.ReadKey();
}
} // end class
To summarize:
you need a for loop that runs 5 times.
The for loop will do the following:
assign the user input to a variable
loop through your array (second loop) and see if it contains this variable
if the number is found, set a boolean to true. (found)
if after the loop is over, found = false, then print false
also add the number to the array (at the index of the outer loop is fine)

Noob needing help on breaking out of loop

I'm very sorry this is such an easy question, I'm just starting out. I've created code that allows a user to enter a number of random dice rolls, and outputs the sum of those rolls. I've now been asked to create a loop that repeats these steps, including the prompt, until the user types 'quit'. My issue is that my code converts the string to an integer, so typing anything kills the code. Any tips of how to insert the loop and break? My code is:
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
int numberDice = Convert.ToInt32(numberDiceString);
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.ReadKey();
}
I wouldn't use a "while(true)" statement. As someone pointed out in the comments i would prefer using the right condition in there.
That being said i would do it this way:
static void Main(string[] args)
{
Random random = new Random();
string numberDiceString;
int numberDice;
Console.WriteLine("Enter a number of dice to roll:");
while ((numberDiceString = Console.ReadLine()) != "quit")
{
bool parsed = int.TryParse(numberDiceString, out numberDice);
if (!parsed)
{
//Handle the error. The user input was not a number or "quit" word
break;
}
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.WriteLine("Enter a number of dice to roll:");
}
}
I have to say that i prefer this way because you can easily see when the loop will stop. Also i added an error handling that you should be doing (What happen if the user enters any words that are not numbers?).
Hope this helps.
This change should be fairly simple. What you need to do is to create a while loop, and then a check before you actually parse for an int. The psuedocode for this would be something like.
while(true) {
//Ask for input
//Check if it equals "quit"
//If so -> break;
//If not convert to int
//For Loop for dice rolls
//Print Total
}
I'm sure it could be a little more elegant than this, and you would want to put some more checks to make sure that invalid input doesn't crash the program, but it should get the job done.
This is a very simple solution that shows how to parse the user input.
using System;
namespace Simpleton
{
class Program
{
static public int GetChoice()
{
int choice = 0;
while (true)
{
Console.Write("Enter number of rolls or \"quit\" to finish: ");
var answer = Console.ReadLine();
if (String.Compare(answer, "quit", true) == 0)
{
return 0; // Done
}
if (Int32.TryParse(answer, out choice))
{
return choice;
}
}
}
static void Main(string[] args)
{
var choice = 0;
while ((choice = GetChoice()) > 0)
{
Console.WriteLine($"You'll be looping {choice} times.");
for (int tries = 0; tries < choice; tries++)
{
// Looping
}
}
}
}
}
Try this code:
static void Main(string[] args)
{
Random random = new Random();
while(true)
{
String numberDiceString = "";
int numberDice = 0;
Console.WriteLine("Enter a number of dice to roll:");
numberDiceString = Console.ReadLine();
if (numberDiceString == "quit") { return; }
int total = 0;
if (Int32.TryParse(numberDiceString, out numberDice))
{
total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
}
Console.WriteLine(total);
}
}
I'm not a C# programmer, but you can test for "quit" explicitly and use a goto
BeginLoop:
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
if (numberDiceString == "quit")
{
goto EndLoop;
}
int numberDice = Convert.ToInt32(numberDiceString);
/* Rest of code you want to do per iteration */
goto BeginLoop;
EndLoop:

Getting User Input and Adding it to an array at C#

I am trying to get input from user 5 times and add those values to marks array;
Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements". After getting input from user how can I add them to marks array? Any tips would be helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
double average =0;
int [] marks = new int[] { };
for (int a = 0; a < 5; a++){
Console.WriteLine("Enter 5 elements:");
string line = Console.ReadLine();
Console.WriteLine(line);
}
for (int i = 0; i < marks.Length; i++){
average = marks.Average();
}
if(average>0){
Console.WriteLine("Positive");
}else{
Console.WriteLine("Negative");
}
}
}
I would use a while loop combined with int.TryParse to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average(); inside a for loop, because LINQ Average calculates the average of a collection (in your case the marks array).
static void Main()
{
int[] marks = new int[5];
int a = 0;
Console.WriteLine("Enter 5 elements:");
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out marks[a]))
a++;
else
Console.WriteLine("You didn't enter a number! Please enter again!");
}
double average = marks.Average();
if (average > 0)
Console.WriteLine("Positive");
else
Console.WriteLine("Negative");
}
DEMO HERE
Edited my answer to illustrate solving your problem without a for loop.
class Program
{
const int numberOfMarks = 5;
static void Main()
{
List<int> marks = new List<int>();
Enumerable.Range(1, numberOfMarks)
.ForEach((i) => {
Console.Write($"Enter element {i}:");
marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
Console.WriteLine($" {valueRead}");
});
Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
}
}
This will help you, just copy and paste it.
There are some explanation with comments.
class Program
{
static void Main()
{
const int numberOfMarks = 5;
int[] marks = new int[numberOfMarks];
Console.WriteLine("Enter 5 elements:");
for (int a = 0; a < numberOfMarks; a++)
{
// If entered character not a number, give a chance to try again till number not entered
while(!int.TryParse(Console.ReadLine(), out marks[a]))
{
Console.WriteLine("Entered not a character");
}
Console.WriteLine("You entered : " + marks[a]);
}
// Have to call Average only once.
var avg = marks.Average();
Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
Console.ReadLine();
}
}
Follow Stackoverflow Answer
since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For e.g.
string words = "83";
int number = int.Parse(words);
Edit: using string variable in parsing.

How can I catch five consecutive numbers in an array of int[5] in C#?

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.

C# factorial calculator is not working right

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;
}
}
}
}

Categories