calculating from each line of an array using c# - c#

I'm very new to c# and programming in general. I'm having some issues trying to get this program to work.
I've to input 5 names from a text file, add 5 scores to each name, remove the max and min score for each name, and then display the winner. What I have done so far only seems to be adding up all the scores. Could anyone point me in the right direction?
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diving_Championship
{
class Program
{
static void Main(string[] args)
{
string[] divers = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
string DiverScore;
int score = 0;
int max = 0;
int min = 10;
int Totalscore = 0;
int[] Finalscore = new int[5];
int max1 = 0;
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 5; i++)
{
DiverScore = divers[i];
Console.WriteLine("Please Enter a Score between 0 and 10 for {0}", DiverScore);
score = Convert.ToInt16(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Score Is Invalid, Please Re-Enter a score between 0 and 10");
score = Convert.ToInt16(Console.ReadLine());
}
if (score > max)
{
max = score;
}
if (score < min)
{
min = score;
}
Totalscore += score;
}
}
for (int i = 0; i < 5; i++)
{
Finalscore[i] = Totalscore - max - min;
if (Finalscore[0] > max1)
{
max1 = Finalscore[0];
}
if (Finalscore[1] > max1)
{
max1 = Finalscore[1];
}
if (Finalscore[2] > max1)
{
max1 = Finalscore[2];
}
if (Finalscore[3] > max1)
{
max1 = Finalscore[3];
}
if (Finalscore[4] > max1)
{
max1 = Finalscore[4];
}
}
Console.WriteLine("the max score is {0}", max1);
}
}
}

Looks like i was completely barking up the wrong tree, i have finally got my code to work, but thanks for all your input. It's not the prettiest code but it works :P
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DivingChampionship_Coursework
{
class Program
{
static void Main(string[] args)
{
string[] divers = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
int score1 = 0;
int score2 = 0;
int score3 = 0;
int score4 = 0;
int score5 = 0;
Diver1(ref divers, ref score1);
Diver2(ref divers, ref score2);
Diver3(ref divers, ref score3);
Diver4(ref divers, ref score4);
Diver5(ref divers, ref score5);
FindWinner(ref divers, ref score1, ref score2, ref score3, ref score4, ref score5);
}
static void Diver1(ref string[] divers, ref int score1)
{
int[] diver1 = new int[5];
int max1 = 0;
int min1 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[0]);
diver1[i] = Convert.ToInt16(Console.ReadLine());
while (diver1[i] < 0 || diver1[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver1[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver1[i] < min1)
{
min1 = diver1[i];
}
if (diver1[i] > max1)
{
max1 = diver1[i];
}
}
score1 = diver1[0] + diver1[1] + diver1[2] + diver1[3] + diver1[4] - max1 - min1;
Console.WriteLine("Total score is {0} from {1}", score1, divers[0]);
Console.WriteLine();
}
static void Diver2(ref string[] divers, ref int score2)
{
int[] diver2 = new int[5];
int max2 = 0;
int min2 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[1]);
diver2[i] = Convert.ToInt16(Console.ReadLine());
while (diver2[i] < 0 || diver2[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver2[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver2[i] < min2)
{
min2 = diver2[i];
}
if (diver2[i] > max2)
{
max2 = diver2[i];
}
}
score2 = diver2[0] + diver2[1] + diver2[2] + diver2[3] + diver2[4] - max2 - min2;
Console.WriteLine("Total score is {0} from {1}", score2, divers[1]);
Console.WriteLine();
}
static void Diver3(ref string[] divers, ref int score3)
{
int[] diver3 = new int[5];
int max3 = 0;
int min3 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[2]);
diver3[i] = Convert.ToInt16(Console.ReadLine());
while (diver3[i] < 0 || diver3[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver3[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver3[i] < min3)
{
min3 = diver3[i];
}
if (diver3[i] > max3)
{
max3 = diver3[i];
}
}
score3 = diver3[0] + diver3[1] + diver3[2] + diver3[3] + diver3[4] - max3 - min3;
Console.WriteLine("Total score is {0} from {1}", score3, divers[2]);
Console.WriteLine();
}
static void Diver4(ref string[] divers, ref int score4)
{
int[] diver4 = new int[5];
int max4 = 0;
int min4 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[3]);
diver4[i] = Convert.ToInt16(Console.ReadLine());
while (diver4[i] < 0 || diver4[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver4[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver4[i] < min4)
{
min4 = diver4[i];
}
if (diver4[i] > max4)
{
max4 = diver4[i];
}
}
score4 = diver4[0] + diver4[1] + diver4[2] + diver4[3] + diver4[4] - max4 - min4;
Console.WriteLine("Total score is {0} from {1}", score4, divers[3]);
Console.WriteLine();
}
static void Diver5(ref string[] divers, ref int score5)
{
int[] diver5 = new int[5];
int max5 = 0;
int min5 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[4]);
diver5[i] = Convert.ToInt16(Console.ReadLine());
while (diver5[i] < 0 || diver5[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver5[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver5[i] < min5)
{
min5 = diver5[i];
}
if (diver5[i] > max5)
{
max5 = diver5[i];
}
}
score5 = diver5[0] + diver5[1] + diver5[2] + diver5[3] + diver5[4] - max5 - min5;
Console.WriteLine("Total score is {0} from {1}", score5, divers[4]);
Console.WriteLine();
}
static void FindWinner(ref string[] divers, ref int score1, ref int score2, ref int score3, ref int score4, ref int score5)
{
int MaximumScore = 0;
int x = 0;
if (score1 > MaximumScore)
{
MaximumScore = score1;
}
if (score2 > MaximumScore)
{
MaximumScore = score2;
x = 1;
}
if (score3 > MaximumScore)
{
MaximumScore = score3;
x = 2;
}
if (score4 > MaximumScore)
{
MaximumScore = score4;
x = 3;
}
if (score5 > MaximumScore)
{
MaximumScore = score5;
x = 4;
}
Console.WriteLine("Max score is {0} from {1}", MaximumScore, divers[x]);
}
}
}

Appreciate you've already solved your problem, but thought I'd post this short example solution:
Console.WriteLine("The max score is " +
File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt")
.Select(driver =>
{
int score;
do Console.WriteLine("Please Enter a Score between 0 and 10 for " + driver);
while (!int.TryParse(Console.ReadLine(), out score) || score < 0 || score > 10);
return score;
}).Max());

It's not completely clear from the code what do you really aim. At least, the code differs from the task description you provided. Anyway, I'd suggest such a wild guess, for example:
Update - I fixed the code to fit your needs, according to the working code you provided.
using System.IO;
using System.Linq;
namespace Diving_Championship
{
class Program
{
private class Diver
{
internal Diver(string name)
{
Name = name;
}
internal readonly string Name;
internal readonly int[] Scores = new int[5];
internal int TotalScore
{
get { return Scores.OrderBy(sc => sc).Skip(1).Take(3).Sum(); }
}
}
static void Main(string[] args)
{
string[] diverNames = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
List<Diver> divers = new List<Diver>();
for (int j = 0; j < 5; j++)
{
var diver = new Diver(diverNames[j]);
for (int i = 0; i < 5; i++)
{
int score;
do
{
Console.WriteLine("Please Enter a Score between 0 and 10 for {0}", diver.Name);
score = Convert.ToInt32(Console.ReadLine());
} while (score < 0 || score > 10);
diver.Scores[i] = score;
divers.Add(diver);
}
}
var MaxScore = divers.Max(d => d.TotalScore);
var Winner = divers.First(d => d.TotalScore == MaxScore);
Console.WriteLine("The winner is {0} with score {1}", Winner.Name, MaxScore); }
}
}
}

Related

c# how to fill an array with user input

I'm creating a lottery program that users can choose from a series of numbers between a particular range and the program then creates its own version of numbers and compares those user values against the program's random numbers which any matches that the program then finds are then displayed to the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assessment1.Lottery
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please insert 6 lottery numbers:");
int range = 100;
int minValue = 0;
int maxValue = 100;
int a = 0;
Random rnd = new Random();
int[] myArray = new int[6];
for ( int i=0; i < myArray.Length; i++ )
{
int randomNumber = rnd.Next(minValue, maxValue);
myArray[i] = randomNumber;
Console.WriteLine(randomNumber);
myArray[i] = int.Parse(Console.ReadLine());
Console.WriteLine(myArray[i]);
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out myArray[a]))
a++;
else
Console.WriteLine("invalid integer");
}
double arry = myArray.Average();
if(arry > 0)
Console.WriteLine("found");
else
Console.WriteLine("not found");
int BinarySearch(int[] array, int value, int low, int high)
{
if ( high >= low)
{
int mid = (low + high) / 2;
if (array[mid] == value) return mid;
if (array[mid] == value) return BinarySearch(array, value, low, mid - 1);
return BinarySearch(array, value, mid + 1, high);
}
return -1;
}
}
Console.ReadLine();
}
}
}
when I run the program it shows the following
Please insert 6 lottery numbers: 64
how can I fix this so that the array can be filled with user input
Here is a version of something I wrote a while back and modified to your parameters, if there are bugs please don't ask me to fix.
static void Main(string[] args)
{
int stop = 0;
int[] chosenNum = new int[6];
while (stop == 0)
{
Console.Clear();
string con = "";
Console.WriteLine("Enter six numbers between 1-100 separated by a comma with no duplicates:");
string numbers = Console.ReadLine();
string[] userNumbers = numbers.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToArray();;//remove ex: ,, issues
string[] checkDup = userNumbers.Distinct().ToArray();//remove duplicates
if (userNumbers.Count() < 6)
{
Console.WriteLine("You entered less than six numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (userNumbers.Count() > 6)
{
Console.WriteLine("You entered more than 6 numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (checkDup.Count() < 6)
{
Console.WriteLine("You entered duplicate numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (!isNumeric(userNumbers))
{
Console.WriteLine("You entered non-numeric value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (isInRange(userNumbers) < 6)
{
Console.WriteLine("You entered out of range value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else
{
var lowerBound = 1;
var upperBound = 100;
var random = new Random();
int[] randomNum = new int[6];
int count = 0;
foreach(string str in userNumbers){
var rNum = random.Next(lowerBound, upperBound);
randomNum[count] = rNum;
count++;
}
string[] ourPicks = Array.ConvertAll(randomNum, s => s.ToString()).ToArray();
Array.Sort(userNumbers);
Array.Sort(ourPicks);
//string[] ourpicks = { "1", "2" };//for testing
Console.WriteLine("Your Numbers: {0}", string.Join(", ", userNumbers));
Console.WriteLine("Our Numbers: {0}", string.Join(", ", ourPicks));
string[] result = userNumbers.Intersect(ourPicks).ToArray();
if(result.Count() > 0)
{
Console.WriteLine("Matchs: {0}", string.Join(", ", result));
}
else
{
Console.WriteLine("Match's = 0");
}
stop = 1;
}
}
Console.ReadLine();
}
public static bool isNumeric(string[] num)
{
foreach (string str in num)
{
bool check = int.TryParse(str, out int test);
if (!check)
{
return false;
}
}
return true;
}
public static int isInRange(string[] num)
{
int count = 0;
foreach (string str in num)
{
int.TryParse(str, out int test);
if (test > 0 & test <= 100)
{
count++;
}
}
return count;
}

Is there a way to throw an exception when string is typed in an arrayc#?

I am new in this fascinating world of programming. I have done this array, but when I type a non integer it crashes. I have tried many ways like int.Parse(console.readLine)), tryparse(text, out int) and ConvertTo32 ,However it continues saying that "Input string was not in correct format." Thanks
using System;
namespace BubbleSort
{
class Program
{
public static void HelpME(int[] a, int t)
{
for (int j = 0; j <= a.Length - 2; j++)
{
for (int i = 0; i <= a.Length - 2; i++)
{
if (a[i] > a[i + 1])
{
t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
}
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
a[0 + x] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}
}
}
you should validate the user unput by using int.TryParse method. If the entered string can be converted to int then only it should be inserted into the array, otherwise the program should ignore that value.
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
int temp = 0;
string input = Console.ReadLine();
if(int.TryParse(input, out temp))
{
a[0 + x] = Convert.ToInt32(input);
}
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}

c# subtract a number from an array index in a for loop

I need to find the difference of each number value in an array from an average value. I need to loop through each value and subtract each value FROM the average and display the difference. I have tried several different ways but the difference always comes out as 0 at the end. What am i doing wrong here?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace AvgNDiff
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[10];
int x = 0;
int i;
string entryString = "";
int counter = 0;
int countdown = 10;
int sum = 0;
int average = 0;
while (counter < numbers.Length && numbers[x] != 10 && entryString != "0")
{
if (x == 0)
Write("Enter up to 10 numbers or type 0 to stop > ");
else if (x == 9)
Write("Enter {0} more number or type 0 to stop > ", countdown);
else
Write("Enter up to {0} more numbers or type 0 to stop > ", countdown);
entryString = ReadLine();
numbers[x] = Convert.ToInt32(entryString);
if (entryString != "0")
{
sum += numbers[x];
counter++;
x++;
}
countdown--;
}
average = sum / x;
WriteLine("\n\nYou entered {0} numbers with a sum of {1}", x, sum);
WriteLine("The average of your numbers is " + average);
WriteLine("\n\nNumber Difference");
WriteLine("-------------------------------");
for (i=0; i < x; i++)
{
int value = numbers[i];
int diff = average-value;
WriteLine(String.Format("{0,-10} {1,-10}", (numbers[i]), diff));
}
ReadKey();
}
}
}
Take a look here
int value = numbers[i];
int diff = value - average;
WriteLine(String.Format("{0,-10} {1,-10}", (numbers[i]), value));
the key issue here is the writeline statement.
Youve told it to display numbers[i], and oh wait.. numbers[i] (as thats what value is)
yet diff contains the variance from the average...
static void Main(string[] args)
{
List<int> numberList = new List<int>();
Console.WriteLine("Enter up to 10 numbers or type 0 to stop:");
for (int i = 0; i < 10; i++)
{
int userInput = 0;
while (!int.TryParse(Console.ReadLine(), out userInput))
{
Console.WriteLine("Only integer numbers accepted, let's try again...:");
}
if (userInput == 0)
{
break;
}
else
{
numberList.Add(userInput);
if (i < 9)
{
Console.WriteLine("Yeah, {0} more number{1} to go!", (9 - i), (i == 8 ? "" : "s"));
}
}
}
double average = numberList.Average();
for (int i = 0; i < numberList.Count; i++)
{
Console.WriteLine("#{0}: {1} - {2} = {3}", (i+1), numberList[i], average, (numberList[i] - average));
}
Console.ReadLine();
}
Do not cram the entire soultion into the single Main, extract (and debug) a method:
// Subtract each item from the average
private static double[] MyNormalize(int[] source) {
double sum = 0.0;
foreach (var item in source)
sum += item;
double[] result = new double[source.Length];
for (int i = 0; i < source.Length; ++i)
result[i] = sum / source.Length - source[i];
return result;
}
...
static void Main(string[] args) {
int[] numbers = new int[10];
...
// Input
while (counter < numbers.Length && numbers[x] != 10 && entryString != "0") {
...
entryString = ReadLine();
numbers[x] = Convert.ToInt32(entryString);
}
// Business logic
double[] norm = MyNormalize(numbers);
// Output
for (int i = 0; i < numbers.Length; ++i)
WriteLine(String.Format("{0,-10} {1,-10}", numbers[i], norm[i]));
}

sequence with min & max numbers

I'm trying to get this program to let me enter a desired number(entries), then enter a desired value to this entries. It should write out the biggest value(green), smallest(red) then the rest of the sequence. And in the next row, biggest and smallest should change places(didn't even type code for this). What am I doing wrong(especially in the last 'for loop' )
int max = int.MinValue;
int min = int.MaxValue;
Console.WriteLine("How many numbers do you want to enter ? ");
int kolicinaBrojeva = int.Parse(Console.ReadLine());
int[] niz = new int[kolicinaBrojeva];
for (int i = 0; i < kolicinaBrojeva; i++)
{
Console.WriteLine("Enter {0}. a number:", i + 1);
niz[i] = int.Parse(Console.ReadLine());
if (niz[i] > max)
{
max = niz[i];
}
if (niz[i] < min)
{
min = niz[i];
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(max + ", ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(min + ", ");
Console.ResetColor();
for (int i = 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
The last for loop should be like below:
for (int i = kolicinaBrojeva - 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
Your current code will read in kolicinaBrojeva numbers correctly, but min and max will not be set correctly. No other int is greater than int.MaxValue and similarly, no other int is less than int.MinValue. You could do the following instead:
int max = int.MinValue;
int min = int.MaxValue;
With this, you'll get the correct min and max, however, I'm not sure of what you're trying to do in the last loop.
Try this.
using System;
class Test
{
static void Main()
{
string[] temp = Console.ReadLine().Split();
int[] numbers = new int[temp.Length];
for (var i = 0; i < numbers.Length; i++)
numbers[i] = int.Parse(temp[i]);
int minIndex = 0;
int maxIndex = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] < numbers[minIndex])
minIndex = i;
if (numbers[i] > numbers[maxIndex])
maxIndex = i;
}
Swap(ref numbers[maxIndex], ref numbers[0]);
Swap(ref numbers[minIndex], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Green, ConsoleColor.Red);
Swap(ref numbers[0], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Red, ConsoleColor.Green);
}
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Print(int[] array, ConsoleColor a, ConsoleColor b)
{
Console.ForegroundColor = a;
Console.Write(array[0] + " ");
Console.ResetColor();
for (int i = 1; i < array.Length - 1; i++)
Console.Write(array[i] + " ");
Console.ForegroundColor = b;
Console.WriteLine(array[array.Length - 1]);
Console.ResetColor();
}
}

Number of zeroes at the end of factorial

I need to find the number of zeroes at the end of a factorial number. So here is my code, but it doesn't quite work :/
using System;
class Sum
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
long factoriel = 1;
for (int i = 1; i <= n; i++)
{
factoriel *= i;
}
Console.WriteLine(factoriel);
int timesZero = 0;
while(factoriel % 10 != 0)
{
timesZero++;
}
Console.WriteLine(timesZero);
}
}
I know I can use a for loop and divide by 5, but I don't want to. Where is the problem in my code and why isn't it working?
There's problem with your algorithm: integer overflow. Imagine, that you are given
n = 1000
and so n! = 4.0238...e2567; you should not compute n! but count its terms that are in form of (5**p)*m where p and m are some integers:
5 * m gives you one zero
25 * m gives you two zeros
625 * m gives you three zeros etc
The simplest code (which is slow on big n) is
static void Main(string[] args) {
...
int timesZero = 0;
for (int i = 5; i <= n; i += 5) {
int term = i;
while ((term % 5) == 0) {
timesZero += 1;
term /= 5;
}
}
...
}
Much faster implementation is
static void Main(string[] args) {
...
int timesZero = 0;
for (int power5 = 5; power5 <= n; power5 *= 5)
timesZero += n / power5;
...
}
Counting Trailing zeros in Factorial
static int countZerosInFactOf(int n)##
{
int result = 0;
int start = 1;
while (n >= start)
{
start *= 5;
result += (int)n/start;
}
return result;
}
Make sure to add inbuilt Reference System.Numeric
using System.Text;
using System.Threading.Tasks;
using System.Numeric
namespace TrailingZeroFromFact
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a no");
int no = int.Parse(Console.ReadLine());
BigInterger fact = 1;
if (no > 0)
{
for (int i = 1; i <= no; i++)
{
fact = fact * i;
}
Console.WriteLine("{0}!={1}", no, fact);
string str = fact.ToString();
string[] ss = str.Split('0');
int count = 0;
for (int i = ss.Length - 1; i >= 0; i--)
{
if (ss[i] == "")
count = count + 1;
else
break;
}
Console.WriteLine("No of trailing zeroes are = {0}", count);
}
else
{
Console.WriteLine("Can't calculate factorial of negative no");
}
Console.ReadKey();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter the number:");
int n = int.Parse(Console.ReadLine());
int zero = 0;
long fac=1;
for (int i = 1; i <= n; i++)
{
fac *= i;
}
Console.WriteLine("Factorial is:" + fac);
ab:
if (fac % 10 == 0)
{
fac = fac / 10;
zero++;
goto ab;
}
else
{
Console.WriteLine("Zeros are:" + zero);
}
Console.ReadLine();
}
Your code seems fine, just a little correction in the while-condition:
public static int CalculateTrailingZeroes(BigInteger bigNum)
{
int zeroesCounter = 0;
while (bigNum % 10 == 0)
{
zeroesCounter++;
bigNum /=10;
}
return zeroesCounter;
}
That works, I just tested it.

Categories

Resources