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;
}
}
}
}
Related
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.
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()));
}
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
}
}
}
I am trying to create a console application where the user inputs a base 10 number and the program outputs the number in binary.
I want to get the exact number of times to execute the for loop to get correct value (the value HERE in the code below).
I also have to reverse everything that the console is now outputting for everything to be correct but that I can do on my own later.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Decimal_to_Binary
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number and the computer will convert it into binary.");
string NumberIn = Console.ReadLine();
decimal Number = Decimal.Parse(NumberIn);
decimal[] Squared = new decimal[100];
for (int i = 0; i < HERE + 1; i++)
{
//Squared[i] = Math.Pow(2, i);
Squared[i] = 2 ^ i ;
if (Number == Squared[i])
{
Console.Write("1");
}
else
{
Console.Write("0");
}
}
Console.ReadKey();
}
}
}
A nice feature of logarithms is that they'll tell you the highest order bit (in the case of log2) or digit that is set for any number. You can use log2 to find out the highest order bit set and then shift the number repeatedly checking for the 0th bit and print the binary representation.
using System;
using System.Text;
namespace BinaryCount
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number and the computer will convert it into binary.");
string NumberIn = Console.ReadLine();
int Number = Int32.Parse(NumberIn);
double loopCount = Math.Log(Number, 2); // Log2 of a number will tell you the highest order bit that's set
StringBuilder s = new StringBuilder();
for (int i = 0 ; i < loopCount ; ++i)
{
if (Number % 2 == 1)
s.Append("1");
else
s.Append("0");
Number = Number >> 1;
}
StringBuilder done = new StringBuilder();
for (int i = s.Length - 1 ; i >= 0 ; i--)
{
done.Append(s[i]);
}
Console.WriteLine(done);
Console.ReadLine();
}
}
}
Is there a way to check a lenth of integer variable, and if is to long just trim it.
I hava a field in database that accepts 3 character, lenth is 3.
So is it possible to do like it's done with string variable
example:
cust_ref = cust_ref.Length > 20 ? cust_ref.Substring(0, 19) : cust_ref;
Thanks!
The easiest answer would be:
//The length would be 3 chars.
public int myint = 111;
myint.ToString().Length;
The following worked a treat for me!
public static int IntLength(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if (i == 0)
return 1;
return (int)Math.Floor(Math.Log10(i)) + 1;
}
Original Source: http://www.java2s.com/Code/CSharp/Data-Types/Getthedigitlengthofanintvalue.htm
You don't have to convert it to a string to make it shorter, that can be done numerically:
if (num > 999) {
num %= 1000;
}
This will cut of digits from the left, if you want to cut them off from the right:
while (num > 999) {
num /= 10;
}
If the value can be negative, also check:
if (num < -99) {
num = -(-num % 100);
}
or:
while (num < -99) {
num = -(-num / 10);
}
cust_ref = cust_ref.ToString().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
or simply use
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
Use like this
cust_ref= cust_ref.Tostring().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
Nont very clear what you're asking for, but as much as I unerstood you're asking for:
int a = 1234567890;
for some reason you want to make it shorter, like
int b = MakeShorter(a);
//b == 1234 (say)
If so, the easiest solution may be, convert it to string, made what you already implemented and reconvert it back to int.
If this is not what you're asking for, please clarify.
The conversion to the string is ugly way to implement it.
It's require a pure math solution
int CutTheNumber(int number, int maxLen)
{
var maxSize = (int)Math.Pow(10, maxlen);
if(maxSize <= Math.Abs(number))
{
number %= maxSize;
}
return number;
}
Checking length
length = cust_ref.ToString().Length;
Remove extra bits
if (length > need)
{
cust_ref =Convert.ToInt32( cust_ref.ToString().Remove(length -(length- need)));
}
for this u will have to do some simple stuffs.
like
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
or u can manually store it in any variable and the
You can try this code. use if else statement to check the validation ..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace avaragescore
{
class Program
{
static void Main(string[] args)
{
float quiz;
float midterm;
float final;
float avrg=0;
Start:
Console.WriteLine("Please enter the Quize Score here");
quiz = float.Parse(Console.ReadLine());
if(quiz > 100)
{
Console.WriteLine("You have entered wrong score please re-enter");
goto Start;
}
Start1:
Console.WriteLine("Please enter the Midterm Score here");
midterm = float.Parse(Console.ReadLine());
if(midterm > 100)
{
Console.WriteLine("You have entered wrong score please re- enter");
goto Start1;
}
Start3:
Console.WriteLine("Please enter the Final Score here");
final = float.Parse(Console.ReadLine());
if(final > 100)
{
Console.WriteLine("You have entered wrong Score Please re-enter");
goto Start3;
}
avrg = (quiz + midterm + final) / 3;
if(avrg >= 90)
{
Console.WriteLine("Your Score is {0} , You got A grade",avrg);
}
else if (avrg >= 70 && avrg < 90)
{
Console.WriteLine("Your Score is {0} , You got B grade", avrg);
}
else if (avrg >= 50 && avrg < 70)
{
Console.WriteLine("Your Score is {0} , You got C grade", avrg);
}
else if (avrg < 50)
{
Console.WriteLine("Yor Score is {0} , You are fail", avrg);
}
else
{
Console.WriteLine("You enter invalid Score");
}
Console.ReadLine();
}
}
}