How do I add the result of factorial values? - c#

I'm having a logic problem here. I want to add the result of the factorial values but I'm not sure how to add them. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task_8_Set_III
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " +);
}
}
static double fact(double value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}
}
}

Not sure if this is what you meant but if for factorial of N you want to have the sum of all factorials up to that value this is how you do it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task_8_Set_III
{
class Program
{
static void Main(string[] args)
{
double sum = 0;
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
sum += c;
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + sum);
}
}
static double fact(double value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}
}
}

You need to add a total variable to keep track of the sum.
double total = 0; //the total
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
total += c; // build up the value each time
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + total);
}

short of totally understanding what you want to do exactly, here's two things...
in programming, the following expression is perfectly valid:
i = i + 1 Saying "the new value of i is the old value of i plus one"
variables live within scopes, their boundaries usually being braces { }, that is you will need a variable that is outside the braces of the foreach in order to "remember" stuff of the previous iteration.

static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 7; i++)
{
int c = fact(i);
sum += c;
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + sum);
}
}
static int fact(int value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}

Related

C# How to display vertical Histogram?

I am very new to C# and I am trying to create a console application to create a vertical and horizontal histogram, made of stars. So I am asking the user for 8 numbers between 1-10 and printing their results onto the screen as a histogram.
I need help with displaying the histogram vertically, I've done the horizontal one and can't figure out how to make it vertical. Here's what I've got so far:
Would appreciate any help greatly. Thank you in advance.
I'd like it to look something like this:
*
* *
* * *
* * * *
* * * * *(Height of row depends on numbers user enters.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class Program
{
static void Main(string[] args)
{
clsMainMenu MainMenu = new clsMainMenu();
ConsoleKeyInfo ConsoleKeyPressed;
do
{
MainMenu.DisplayMenu();
ConsoleKeyPressed = Console.ReadKey(false);
Console.WriteLine();
switch (ConsoleKeyPressed.KeyChar.ToString())
{
case "1":
clsHistogram Histogram = new clsHistogram();
Histogram.CreateHorizontalHistogram();
break;
case "2":
clsHistogram HistogramV = new clsHistogram();
HistogramV.CreateVerticalHistogram();
break;
}
} while (ConsoleKeyPressed.Key != ConsoleKey.Escape);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsMainMenu
{
public void DisplayMenu()
{
Console.WriteLine("1. Create a Horizontal Histogram.");
Console.WriteLine("2. Create a Vertical Histogram.");
Console.WriteLine("Press Esc to exit the Program.");
Console.WriteLine("..................................");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsHistogram
{
string strNumberChosen = "";
public void CreateHorizontalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" *");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Horizontal Array.
}
public void CreateVerticalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" * \n");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Vertical Array.
}
}
}
Here is a little test program that might get you started on creating the Vertical Histogram. Notice I combined the last solution I provided for the Horizontal Histogram and made the code more universally applicable:
private static readonly char star = '*';
private static readonly uint minValue = 1;
private static readonly int maxValue = 10;
static void Main(string[] args)
{
var list = GetHistorgramData();
CreateHorizontalHistogram(list);
CreateVerticalHistogram(list);
}
private static void CreateHorizontalHistogram(List<int> list)
{
Console.WriteLine("Your Horizontal Histogram looks like this: ");
//foreach(var value in list)
//{
// Console.WriteLine(string.Empty.PadRight(value, star));
//}
//Console.WriteLine("Or like this with LINQ");
list.ForEach(n => Console.WriteLine(string.Empty.PadRight(n, star)));
}
private static void CreateVerticalHistogram(List<int> list)
{
Console.WriteLine("Your Vertical Histogram looks like this: ");
for(int i = 0; i < maxValue + 1; i++)
{
var displayLine = string.Empty;
foreach(int x in list)
{
displayLine += ((x + i) - maxValue) > 0 ? star.ToString() : " ";
}
Console.WriteLine(displayLine);
}
}
private static List<int> GetHistorgramData()
{
var limits = "a number between " + minValue + " and " + maxValue + ": ";
Console.WriteLine("Please enter " + limits);
var list = new List<int>();
do
{
var message = string.Empty;
bool isNumber = false;
bool isRightSize = false;
int output;
do
{
var input = Console.ReadLine();
isNumber = int.TryParse(input, out output);
if(isNumber)
{
isRightSize = minValue <= output && output <= maxValue;
message = isRightSize ? "That will do: " : "Try again - value is not " + limits + output;
}
else
{
message = "Try again - " + input + " is not a Number";
}
Console.WriteLine(message);
}while(!isNumber || !isRightSize);
list.Add(output);
Console.WriteLine("Entered number at position" + list.Count + " : " + output);
}while(list.Count < 8);
return list;
}
Vertical Results:
*
**
**
****
****
******
*******
********
********
for input:
Please enter a number between 1 and 10:
2
Entered number at position1 : 2
4
Entered number at position2 : 4
6
Entered number at position3 : 6
8
Entered number at position4 : 8
9
Entered number at position5 : 9
6
Entered number at position6 : 6
4
Entered number at position7 : 4
3
Entered number at position8 : 3
NOTE:
I suggest you use the method GetHistorgramData() for both Vertical and Horizontal.
You can decide whether you wish to use LINQ for the Horizontal Histogram or the foreach loop version.
I think I could have made LINQ version for the Vertical Histogram, but I felt that might look confusing.
You might want to restyle the Histogram a bit, but keep in mind the width of a space " " is different than that of the star "*".
Please let me know if you have any questions.
int currentValue = 1;
bool allDone = false;
Console.WriteLine("Your Histogram looks like this: ");
while (!(allDone))
{
int x = 0;
for (int intcounter = 0; intcounter < 8; intcounter++)
{
if (intHistogramArray[intcounter] >= currentValue)
{
Console.Write(" * ");
}
else
{
Console.Write(" ");
x = x + 1;
}
}
if (x>=8) { allDone = true; }
currentValue = currentValue + 1;
Console.WriteLine();
}
output:
Your Histogram looks like this:
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
If you want to have them bottom-aligned, you have to make some slight modigfications, this is just to give you an idea on how to start.

C# array won't work

I have created a piece of code to create an array of 100 elements which will randomize based on the numbers from a set array. However whenever I enter "y" I am looking the array to delete the last element and add a new random element to the start and move everything in between one to the right to allow for this. However at the moment it is completely changing the array every time I enter "y". Can anyone help with this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
int[] values = { 1, 2, 3, 4, 5, 6 };
int Min = values[0];
int Max = values[5] + 1;
int w = 0 ;
int[] rndValues = new int[100];
Random rndNum = new Random();
Console.WriteLine("Random001 " + w);
for (int i = 0; i < rndValues.Length; i++)
{
rndValues[i] = rndNum.Next(Min, Max);
}
Console.WriteLine("Random " + w);
foreach(var item in rndValues)
{
Console.Write(item.ToString() + " ");
}
if (w==0)
{
Console.WriteLine(Environment.NewLine);
prob(rndValues, Min, Max,w);
Console.WriteLine(Environment.NewLine);
w++;
}
if (w>0)
{
while(true)
{
Console.WriteLine("To change elements in the array press y");
// read input
var s = Console.ReadLine();
if(s == "y")
{
//rndValues[99] = 0;
for(int i = 0; i == rndValues.Length; i++)
{
if (i != rndValues.Length)
{
rndValues[rndValues.Length-i] = rndValues[(rndValues.Length-i)-1];
}
else if (i == rndValues.Length)
{
rndValues[0] = rndNum.Next(Min, Max);
}
}
}
else
{
break;
}
prob(rndValues, Min, Max,w);
}
}
}
public static void prob(int[] rndValues, int Min, int Max, int w )
{
double[] count = new double[rndValues.Length];
//Loop through min to max and count the occurances
for (int i = Min; i <Max; i++)
{
for (int j = 0; j < rndValues.Length; j++)
{
if (rndValues[j] == i)
{
count[i] = count[i] + 1;
}
}
}
//For displaying output only
foreach(var item in rndValues)
{
Console.Write(item.ToString() + " ");
}
Console.WriteLine("W " + w);
for (int i = Min; i < Max; i++)
{
count[i] = (count[i] / rndValues.Length) * 100;
Console.WriteLine("Probability of the number " + i + " is " + count[i]);
}
}
}
}
Thanks.

Calculating factorials in C# using loops

This is what I have so far:
namespace factorials
{
class Program
{
static void Main(string[] args)
{
int number;
do
{
Console.WriteLine("What non-negative integer do you want to factorial?");
while (!int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Please enter a whole number only");
calculate(ref number);
} while (number >= 0);
Console.WriteLine("Please enter a non-negative number");
}
static void calculate(ref int number)
{
int factorial;
int counter;
for (counter = number; counter <= number; counter++)
{
factorial = number * number;
Console.WriteLine("The factorial of {0} is {1}", number, factorial);
}
}
}
}
Right now it just gives me the square of the numbers, not the factorial of them. How do I make it repeat the number of times as the input so it results in a factorial?
Also I am not sure if it's necessary to limit the program to non-negative integers only but if I want to that part is just ending the program right there instead of looping back to the beginning.
The for loop doesn't make any sense at all! If you are looking for a factorial, then you have to multiply all the numbers from one to the given number. That would be:
int factorial = 1;
for (counter = 1; counter <= number; counter++)
{
factorial = factorial * counter;
}
Console.WriteLine("The factorial of {0} is {1}", number, factorial);
This would calculate the factorial of one number. You would have to repeat it for all the numbers you wanted.
Your loop assigns the square of the number to the result in a loop, and exits right away. You need to change it so that the result is repeatedly multiplied by numbers from 1 to N, inclusive.
Assign 1 to factorial, and multiply it by counter inthe loop:
factorial *= counter;
Don't forget to start your counter at 1.
I will give you hint.
Have a variable initialized to 1. Let's say it as Answer.
Run a loop from 1 to Number doing the operation of Answer = Answer * loopIterationVariable. After each iteration, increment loop iteration variable by 1.
static void Main(string[] args)
{
Console.WriteLine("Enter an integer number to factorise");
int ans = 1;
int a = int.Parse(Console.ReadLine());
for (int i = 1; i <= a; i++)
{
ans = ans * i;
}
Console.WriteLine(ans.ToString());
Console.ReadLine();
}
string str = Interaction.InputBox("Enter the number to find the factorial of: ");
double counter = double.Parse(str);
long factorial = 1;
while (counter > 1)
{
factorial *= (long)counter--;//factorial = factorial * counter - 1
}
MessageBox.Show("The factorial of " + str + " is " + String.Format("{0:N}", factorial));
I used a Microsoft.VisualBasic reference for Interaction.InputBox() method
Recursive Implementation as well as basic implementation is as follows
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;
}
}
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
userinputF = Int32.Parse(txtFaculteit.Text);
for (counter = 1; counter <= userinputF; counter++)
{
answer = answer *= counter;
}
}
catch (Exception exception)
{
MessageBox.Show("Please fill in a number " + exception.Message);
}
lblAnswerFaculteit.Text = lblAnswerFaculteit.Text + "The faculty of " + userinputF + " = " + answer;
}
}
}
int userinputF;
int counter;
int answer =1;
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
userinputF = Int32.Parse(txtFaculteit.Text);
for (counter = 1; counter <= userinputF; counter++)
{
answer = answer *= counter;
}
}
catch (Exception exception)
{
MessageBox.Show("Please fill in a number " + exception.Message);
}
lblAnswerFaculteit.Text = lblAnswerFaculteit.Text + "The faculty of " + userinputF + " = " + answer;
}
}
}

Print a string of fibonacci recursively in C#

Can that be done with no while loops?
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" #" + Fibonacci(number));
}
public static int Fibonacci(int number)
{
if (number <= 1)
{
return 1;
}
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}
I can't even add a Console.WriteLine in the body of base case since it gets executed [number] number of times; Not sure how to do this without loops...
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Fibonacci(0, 1, 1, number);
}
public static void Fibonacci(int a, int b, int counter, int number)
{
Console.WriteLine(a);
if (counter < number) Fibonacci(b, a+b, counter+1, number);
}
public static int Fibonatchi(int position) {
if(position == 0) {
return 1;
}
if(position == 1) {
return 1;
} else {
return Fibonatchi(position - 2) + Fibonatchi(position - 1);
}
}
I didn't find a way to do it closest way is it to combine both loops + recursion
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
for(int counter=0;counter<number;counter++)
Console.WriteLine(" \n" + Fibonacci(counter) );
}
public static int Fibonacci(int number)
{
if (number == 0)
return 0;
else if(number ==1)
return 1;
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}
namespace Algorithms
{
class Program
{
static void Main(string[] args)
{
string fibResult = "";
fibResult = FibCal(10);
Console.WriteLine(fibResult);
Console.ReadLine();
}
public static string FibCal(int n)
{
string series = "";
int k, f1, f2 , f = 0;
f1 = f2 = 1;
if (n < 2)
return n.ToString();
else
for (k = 0; k < n; k++)
{
f = f1 + f2;
f2 = f1;
f1 = f;
series += f.ToString() + ",";
}
return series;
}
}
}
Hope this helps
Using recursion in this fashion is a very bad idea. It will cause memory problems very quickly. I know you want to avoid using while/for loops, but an array is really the best way to go.
Using LINQ
public static void fibSeriesEx3()
{
List<int> lst = new List<int> { 0, 1 };
for (int i = 0; i <= 10; i++)
{
int num = lst.Skip(i).Sum();
lst.Add(num);
foreach (int number in lst)
Console.Write(number + " ");
Console.WriteLine();
}
}
That's a way to do it by returning a value into the main.
public static void Main() {
Console.WriteLine("Introduce the number");
int num = Convert.ToInt32(Console.ReadLine());
int num1 = 1, num2 = 1, counter = num-2;
//Take 2 out to match the list as first 2 numbers doesn't count in the function.
Console.WriteLine(Fibo(num1, num2, counter));
}
public static int Fibo(int num1, int num2, int counter) {
int temp = num1;
if (counter <= 0)
return num2;
else
return Fibo(num1 = num2, num2 += temp, counter-1);
}
public static class Golden
{
public static IEnumerable<long> Fibonacci()
{
var a = 0L;
var b = 1L;
var s = 0L;
yield return a;
while (a < long.MaxValue - b)
{
yield return b;
s = a + b;
a = b;
b = s;
}
}
public static IEnumerable<long> FibonacciR()
{
IEnumerable<long> Fibo(long a, long b)
{
yield return a;
if (a < long.MaxValue - b)
{
foreach (var v in Fibo(b, a + b))
{
yield return v;
}
}
}
return Fibo(0, 1);
}
}
I realize this may be an old thread, but oh well I think this kinda question is good in its nature.
Using while loop/or recursive way of doing is not the optimal way of doing as it takes a O(2^n) times. A better way to do this is using what is already in memory like below. This should take at most O(n) time.
Cheers!
static double fibDynamic(int n)
{
double[] array = new double[n];
array[0] = array[1] = 1;
for(int i = 2; i < n; i++)
{
array[i] = array[i - 1] + array[i - 2];
}
return array[n-1];
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
int n, i = 0, c;
Console.WriteLine("Enter the number of terms:");
n = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Fibonacci series\n");
for (c = 1; c <= n; c++)
{
int result = FibonacciFunction(i);
Console.Write(result + " " );
i++;
}
Console.WriteLine();
return 0;
}
public static int FibonacciFunction(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return (FibonacciFunction(n - 1) + FibonacciFunction(n - 2));
}
}
}
}
Simple and easy solution :
static void Main(string[] args)
{
int number;
Console.WriteLine("enter number");
number = int.Parse(Console.ReadLine());
Console.WriteLine(Recursive(number));
Console.ReadLine();
}
public static int Recursive(int number)
{
if (number <= 2)
{
return 1;
}
else
{
return Recursive(number - 1) + Recursive(number - 2);
}
}
Using one line code:
public static int Fibonacci(int i)
{
return i <= 2 ? 1 : Fibonacci(i - 1) + Fibonacci(i - 2);
}

Calculating factorials in C#

I am trying to write a program that will take the users input value and asks whether they want to calculate the value of the numbers 1 to n or the factorial of n!
This is what I have so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project_2_Part_B
{
class Program
{
static void Main(string[] args)
{
var Fkeylow = "f";
var FkeyCap = "F";
var Skeylow="s";
var SkeyCap="S";
int n = 0;
long factorial = n;
Console.WriteLine("Input a value n");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Do you want to calculate factorial or sum");
Console.WriteLine("Enter F or S");
var A = Console.ReadLine();
if (A == Fkeylow)
Console.WriteLine();
if (A == FkeyCap)
Console.WriteLine();
var B=Console.ReadLine();
if (B == Skeylow)
Console.WriteLine();
if (B == SkeyCap)
Console.WriteLine();
Console.WriteLine("Press any key to close...");
Console.ReadLine();
}
}
}
My issue is with the syntax of the calculation to make the code execute the n*(n-1) while n>1.
static void Main(string[] args)
{
Console.WriteLine("Input a value n");
string number = Console.ReadLine(); // Read number
int n = Convert.ToInt32(number); // Converting to int
Console.WriteLine("Do you want to calculate factorial or sum? ");
Console.WriteLine("Enter F or S. ");
string choose = Console.ReadLine(); // F or S
int result = -1; // To view later
if (choose == "f" || choose == "F")
{
result = 1;
for (int i = n; i >= 1; i--) // Loop for calculating factorial
result *= i;
}
else if (choose == "s" || choose == "S")
{
result = 0;
for (int i = n; i >= 1; i--) // Loop for calculating sum
result += i;
}
Console.WriteLine(result); // Printing answer
Console.WriteLine("Press any key to close...");
Console.ReadLine();
}
Using recursion is another way of doing it:
static void Main(string[] args)
{
int n = 5;
Console.WriteLine(factorial(n));
Console.WriteLine(sum(n));
Console.Read();
}
public static int sum(int n)
{
if(n==0)
return 0;
return n+sum(n-1);
}
public static int factorial(int n)
{
if (n == 1)
return 1;
return n * factorial(n - 1);
}
Prints:
120 -->5!
15 -->1+2+3+4+5
Basic solution is here, tested,
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("Factorial of six is :" + manipulator.factorial(16));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
}
}

Categories