Calculating factorials in C# using loops - c#

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

Related

Need help creating console app that outputs percent response for a rating on a survey 1-5 (whole number)

Working on an assignment where i need to accomplish the following: On a survey a question asks the surveyed person to rate something from 1-5 (whole number). The end user of your program iinputs the answers for that question on an unknown number of surveys. Write a program that allows this and outputs the percent response for each value (1, 2, 3, 4, and 5).
I did a previous Console app with a loop to collect an average and I am unsure how to collect a percent response on 5 different possible inputs.
Below is my previous code.
namespace WhileLoopsMean
public class MeanProgram
static void Main(string[] args)
{
long test, sum, loop, count;
double avg;
Console.Write("How many tests? ");
count = long.Parse(Console.ReadLine());
sum = 0;
loop = 1;
while (loop <= count)
{
Console.Write("enter score " + loop + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
loop = loop + 1;
}
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.WriteLine("\n\nenter a score of -100 to end\n");
count = 1;
sum = 0;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
sum = sum + test;
while (test != -100)
{
count = count + 1;
Console.Write("enter score " + count + " : ");
test = long.Parse(Console.ReadLine());
if (test != -100)
{
sum = sum + test;
}
else { }
}
count = count - 1;
avg = sum;
avg = avg / count;
Console.WriteLine("\naverage : " + avg);
Console.ReadKey();
class Program {
static void Main(string[] args) {
string input = "";
List<List<int>> answers = new List<List<int>>();
int questionsCount = ReadInt32("The number of questions: ");
for (int i = 0; i < questionsCount; i++) {
answers.Add(new List<int>());
}
while (input == "" || input == "y") {
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
a.Add(ReadInt32($"Question [{i}]: "));
}
input = Read("Continue (y/n)? ").ToLower();
}
WriteLine("End of input!");
for (int i = 0; i < answers.Count; i++) {
List<int> a = answers[i];
Write($"Average for question[{i}]: {a.Average()}\n");
}
ReadKey();
}
static string Read (string a) {
Write(a);
return ReadLine();
}
static int ReadInt32 (string a = "") {
Write(a);
return ToInt32(ReadLine());
}
}
Try this out. You can customize the questions. And note that to use Write() and WriteLine(), you should add
using static System.Console;
at the top, in the references of the project.

To write summation of numbers with a for-loop

Basically I'm writing a method where I want to find the summation of whole numbers with a for loop.
The output should be something like this:
Enter value of number 1: 23
Enter value of number 2: 23
Enter value of number 3: 23
The sum is: 69
The user will be able choose of many numbers to be added.
My code currently looks like this:
private void ReadInput()
{
Console.Write("Number of values to sum?");
numOfInput = int.Parse(Console.ReadLine());
Console.WriteLine();
}
private void ReadInput()
{
Console.Write("Number of values to sum?");
numOfInput = int.Parse(Console.ReadLine());
Console.WriteLine();
}
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num = int.Parse(Console.ReadLine());
}
}
how should I fix it
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no <whole numbers> " + index);
num += int.Parse(Console.ReadLine());
num = sum;
}
}
private void ShowResults()
{
Console.WriteLine("----------------------------------------------\n");
Console.WriteLine("The sum is \t{0}", sum);
Seems to be the solution + the classes above it are still used but yes.
Thank y'all very much
Try this,
private static void SumNumbers()
{
int numOfInput = 3;
int index;
int num = 0;
for (index = 1; index <= numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum is:" + num.ToString());
Console.ReadLine(); // to keep console alive
}
Hope helps,
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
Console.WriteLine("The sum so far is : "+num.ToString("N0")+". Enter another number to continue summation.");
}
Console.WriteLine("Maximum input received. Total is: "+num.ToString("N0")+".");
Console.ReadLine();
}
This will work as per your need:
int index;
int num = 0;
Console.WriteLine("Number of values to sum: ");
int numOfInput = int.Parse(Console.ReadLine());
for (index = 1; index <= numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum is: " + num);
The following output will be generated:
Number of values to sum: 3
Please give the value of no 1
23
Please give the value of no 2
23
Please give the value of no 3
23
The sum is: 69

C# Programming arrays

I am writing a program that takes the scores of homework assignments, puts them in a array, then averages them. But I need to make it so that these grades range from 1-10. I am not sure how to make it only accept Numbers 1-10. Everything else is complete.
Here is what i have so far:
namespace AverageScore
{
class AverageScore
{
//prompt user to enter the size of the array
public int GetNum()
{
Console.WriteLine("Please enter how many scores you want to save!");
string strNum = Console.ReadLine();
int num = int.Parse(strNum);
return num;
}
static void Main(string[] args)
{
AverageScore scoreObject = new AverageScore();
int arraySize = scoreObject.GetNum();
//define a double array to save scores
double[] scoreArray = new double[arraySize];
string inValue = "";
double sum = 0,
intValue;
Console.WriteLine("Please enter all homework scores");
int counter = 0;
while (counter < arraySize)
{
inValue = Console.ReadLine();
while (double.TryParse(inValue, out intValue) == false)
{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Array.Sort(scoreArray);
double lowest= scoreArray[0];
double highest = scoreArray[arraySize-1];
sum = sum - lowest - highest;
double average = sum / arraySize;
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
Console.Read();
}
}
}
so your problem is to restrict a input to 1-10 correct?
Why not just:
public int InputGrade()
{
Console.Clear();
Console.WriteLine("Please enter a grade [1-10]");
var grade = -1;
if (!Int32.TryParse(Console.ReadLine(), out grade))
return InputGrade();
if (grade < 1 || grade > 10)
return InputGrade();
return grade;
}
then you should be able to use it like this and it is cleaner:
while (counter < arraySize)
{
var grade = InputGrade();
sum += grade;
scoreArray[counter++] = grade;
}
recommendation
Indeed you should refactor the input from the calculation part - you code will get much more cleaner and more readable:
IEnumberable<int> InputGrades()
{
var count = GetNum();
var grades = new List<int>();
for (var i = 0; i < count; i++)
grades.Add(InputGrade());
return grades;
}
void OutputScores(IEnumerable<int> grades)
{
var scores = grades.Cast<doulbe>().ToArray();
var lowest = scores.Min();
var highest = scores.Max();
var average = scores.Average();
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
}
Adjust the while loop condition to check that the number is in range (added a simple string format to present the previous invalid entry):
while (double.TryParse(inValue, out intValue) == false || intValue < 1.0 || intValue > 10.0**)
{
Console.WriteLine(String.Format("Invalid input = {0} stored in intValue", intValue));
inValue = Console.ReadLine();
}
This should do it:
while (counter < arraySize){
inValue = Console.ReadLine();
while (true){
if(double.TryParse(inValue ,out intValue) {
if(intValue >=1 && intValue <=10){
break;
}else{
Console.WriteLine("Input must be in the range 1-10");
inValue = Console.ReadLine();
}
}else{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Uses a loop to check if the value entered is correct:
while (int.Parse(inValue) < 1 || int.Parse(inValue) > 10) inValue = Console.ReadLine();

Console (Input string was not in correct format)

Hi guys so i'm starting to learn C# and I came up with this problem when I was trying to mix things up
It says "Input string was not in correct format" at the
n = Convert.ToInt32(Console.ReadLine());
Here's the whole code
namespace Exercise13
{
class Program
{
static void Main(string[] args)
{
char choice;
Console.Write("What operation would you like to use?");
Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
choice = (char)Console.Read();
if (choice == 'a')
{
sumValues();
}
else if (choice == 'b')
{
minusValues();
}
else if (choice == 'c')
{
timesValues();
}
Console.ReadLine();
}
static void sumValues()
{
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
n = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("\nInput number: ");
val = Convert.ToInt32(Console.ReadLine());
sum += val;
}
Console.Write("\nThe Answer is: "+sum);
}
static void minusValues()
{
int diff = 0, m, z, value;
Console.Write("How many numbers do you want calculate: ");
m = int.Parse(Console.ReadLine());
for (z = 0; z < m; z++)
{
Console.Write("\nInput number: ");
value = int.Parse(Console.ReadLine());
diff -= value;
}
Console.Write("\nThe Answer is: " + diff);
}
static void timesValues()
{
int prod = 0, e, i, val;
Console.Write("How many numbers do you want to calculate: ");
e = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < e; i++)
{
Console.Write("\nInput number: ");
val = int.Parse(Console.ReadLine());
prod *= val;
}
Console.Write("\nThe answer is: " + prod);
}
}
}
Use Integer.TryParse to handle the strings potentially not being numbers. Then prompt the user if the input is not parsable to enter valid input.
Convert and Parse both will throw exceptions if the string is not an exact number.
https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
if(!isValidNumber) {
Console.WriteLine("Invalid number entered!");
}
else {
//Use the number
}

Adding the sum of the entered numbers when you enter 0 in C#?

I am absolutely new to C# and I am at total lost. What I need to do is enter numbers as many as possible and keep entering but when you enter the value "0" that is when you add all the entered numbers all up.
This is my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Activity2
{
class Program
{
static void Main(string[] args)
{
int n, sum, x = 0;
do
{
Console.WriteLine("Enter a Number: ");
n = int.Parse(Console.ReadLine());
}
while (n != 0);
{
sum = n + x;
x = n;
n = sum;
Console.WriteLine("The sum is: " + n);
}
Console.ReadLine();
}
}
}
Some advices:
The while loop is a better practice than the do..while loop.
You should use the int.TryParse method for input validation.
You should calculate sum of numbers inside loop.
You can solve the problem with only two int variables: n for readed numbers and sum for numbers sum.
For example, you can solve your problem with the following code:
static void Main(string[] args)
{
int sum = 0;
while (true)
{
Console.WriteLine("Enter a Number: ");
int n;
if (int.TryParse(Console.ReadLine(), out n))
{
if (n == 0)
break;
sum += n;
}
}
Console.WriteLine("The sum is: " + sum);
}
you can simply do that with do ... while ... loop.
private static void Main(string[] args)
{
int n, sum = 0;
do
{
Console.WriteLine("Enter a number:");
n = Convert.ToInt32(Console.ReadLine());
sum += n;
} while (n != 0);
Console.WriteLine("Sum is:"+sum);
Console.ReadKey();
}
ConvertToInt32() is a method for converting a string to int32 (int).
You print the sum outside while loop.
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Activity2
{
class Program
{
static void Main(string[] args)
{
int n, sum, x = 0;
do
{
Console.WriteLine("Enter a Number: ");
n = int.Parse(Console.ReadLine());
}
while (n != 0);
{
sum = n + x;
x = n;
n = sum;
}
Console.WriteLine("The sum is: " + n);
Console.ReadLine();
}
}
}

Categories