C#: Cannot reassign variable within For loop - c#

I am writing a program to to calculate a specific value in Fibonacci sequence. The recursive method works perfectly, but when I try to use for loop, it doesn't work so well:
class Program
{
static int loopF(int n)
{
int result=0;
if (n == 1)
{
result = n;
}
else if (n == 2)
{
result = n;
}
else if (n>2)
{
int S1 = 1; int S2 = 2;
for (int i = 3; i>n; i++) {
result = S1 + S2;
S1 = S2;
S2 = result;
}
}
else{
Console.WriteLine("Input Error");
}
return (result);
}
static void Main()
{
Console.WriteLine(loopF(10)); //it gives me 0; wrong
Console.WriteLine(loopF(1)); //it gives me 1; correct.
}
}
Does anybody know where I go wrong? Thanks in advance.

Your loop is not executing
for (int i = 3; i>n; i++)
Variable i starts at 3 - in your test case n = 10.
(10 < 3) = false so the loop does not execute.
try using less than instead
for (int i = 3; i < n; i++)

Your loop's exit condition is wrong. It should be
for (int i = 3; i < n ; i++) { ...

Related

why this method has this error?<Returns only some of the code paths.>

I just studied C#.
I have no idea about this error
'return' not supposed to be inside for loop || if Conditional sentence?
class Palindrome
{
public int ***Solution***(int x, int y)//<<---error happen here :(
{
int a = 0;
int data;
string DataString;
int answer;
for(int i = x; i < 1000; i--)
{
for (int j = y; j < 1000; j--)
{
data = i * j;
DataString = data.ToString();
if (DataString[a] == DataString[DataString.Length - 1 - a])
{
answer = int.Parse(DataString);
return answer;
}
}
}
}
}
CS0161: not all code paths return a value
The issue is coming because you are only returning whenever if condition is matched.
But what happens when if condition is not met. Or Code never reaches to If condition even????
It will never return anything
So you probably need to return something outside your first for loop.
class Palindrome
{
public int ***Solution***(int x, int y)//<<---error happen here :(
{
int a = 0;
int data;
string DataString;
int answer;
for(int i = x; i < 1000; i--)
{
for (int j = y; j < 1000; j--)
{
data = i * j;
DataString = data.ToString();
if (DataString[a] == DataString[DataString.Length - 1 - a])
{
answer = int.Parse(DataString);
return answer;
}
}
}
return 0; //return something here
}
}
You have to use return for all code blocks. Up there you are only returning the If code block. make changes according to it and try.

Substring causing index and length error

I have a section in my code that I run to check to see if the item is an spanish item or english item. I am using this logic from an old vb.net application.
public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 1; i <= 15; i++)
{
ss = sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 16;
}
}
return k;
}
The following code loops around
then I get this error message :
ex.Message "Index and length must refer to a location within the
string.\r\nParameter name: length" string
please help!!!
You always go from 1 to 15 - if the (trimmed) text of TxtItem.Text is shorter then 15 chars you'll get the exception.
You should use the length-2 of sp_item as upper bound to avoid the error.
Also, instead of setting i = 16 you should use break to stop the for loop.
However, I think your algorithm could also be written like this instead of the for loop:
if (sp_item.IndexOf("XX")>=1) {
k=1;
}
In c# the first position is at index 0 not 1 like vb
public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 0; i < sp_item.len-2; i++)
{
ss = sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 15;
}
}
return k;
}
you can use
if (sp_item.IndexOf("XX")>=0) {
k=1;
}

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.

For loop to calculate factorials

Currently I have this set of code and its meant to calculate factorials.
int numberInt = int.Parse(factorialNumberTextBox.Text);
for (int i = 1; i < numberInt; i++)
{
numberInt = numberInt * i;
}
factorialAnswerTextBox.Text = numberInt.ToString();
For some reason it doesn't work and i have no clue why. For example i will input 3 and get the answer as -458131456 which seems really strange.
Any help appreciated. Thanks
int numberInt = int.Parse(factorialNumberTextBox.Text);
int result = numberInt;
for (int i = 1; i < numberInt; i++)
{
result = result * i;
}
factorialAnswerTextBox.Text = result.ToString();
on a side note: this would normally NOT be the correct way to calculate factorials.
You'll need a check on the input before you can begin calculation, in case your starting value is 1 or below, in that case you need to manually return 1.
On another side note: this is also a perfect example of where recursive methods can be useful.
int Factorial(int i)
{
if (i <= 1)
return 1;
return i * Factorial(i - 1);
}
A little late to the party:
Func<int, int> factorial = n => n == 0 ? 1 :
Enumerable.Range(1, n).Aggregate((acc, x) => acc * x);
You can use this (rather elegant) solution:
Func<int, int> factorial = null;
factorial = x => x <= 1 ? 1 : x * factorial(x-1);
int numberInt = int.Parse(factorialNumberTextBox.Text);
factorialAnswerTextBox.Text = factorial(numberInt).ToString();
public static int Factorial(int facno)
{
int temno = 1;
for (int i = 1; i <= facno; i++)
{
temno = temno * i;
}
return temno;
}
i am late to the party but here it is
public ulong Factorial(uint numb)
{
if (numb <= 1) return 1;
ulong final = 1;
for (uint i = 1; i <= numb; i++)
{
final *= i;
}
return final;
}
Note:
i used un-signed types for better range
as this calculates up to Factorial(65), while normal signed types will give negative values
Trying to make a more bulletproof solution for n factorial. Here is one that guards for overflows, as well as negative and zero values of n. Using a result variable of type long (instead of int) allows for "larger" values to be calculated (for long, you can calculate up to and including n = 20).
This code returns 0 if an overflow occurred, but you can change it to do whatever is more appropriate.
static long nFactorial(int n)
{
if (n <= 1)
{
return 1;
}
long result = 1;
try
{
for (int i = 1; i <= n; i++)
{
result = checked(result * i);
}
}
catch (OverflowException)
{
return 0;
}
return result;
}
I had to create a factorial method for calculating combinations and tripped over the fact that factorials get very big very fast with relatively small inputs. Here's my solution without using recursion to avoid stack overflow and implemented using System.Numerics.BigInteger.
static BigInteger factorial(int num) {
BigInteger result = 1;
while (num > 1) {
result *= num--;
}
return result;
}
Obviously, you could also using BigInteger for input but my use case was that I was processing int values.
use factorial function:
static long Factorial(long number)
{
if( number <= 1 )
return 1;
else
return number * Factorial(number - 1);
}
and then call the function:
long result = Factorial(int.Parse(factorialNumberTextBox.Text));
factorialAnswerTextBox.Text = result.ToString();
int numberInt=1 ;
for (int i = 1; i <= int.Parse(factorialNumberTextBox.Text); i++)
{
numberInt = numberInt * i;
}
factorialNumberTextBox.Text = numberInt.ToString();
Try this,
int numberInt = int.Parse(textBox1.Text);
int answer = 1;
for (int i = 1; i <= numberInt; i++)
{
answer = answer * i;
}
textBox1.Text = answer.ToString();
Two methods are implemented: Recursive and Basic factorial calculation.
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;
}
}
}
}
static void Main()
{
int numberFactorial = int.Parse(Console.ReadLine());
int result = numberFactorial;
for (int i = 1; i < numberFactorial; i++)
{
result = result * i;
Console.WriteLine("{0}*{1}",numberFactorial,i);
}
Console.WriteLine(result);
}
A nice factorial solution for your nice evening.
int num = Convert.ToInt32(Console.ReadLine());
int fact = 1;
for (int i = num; i > 0; --i)
fact *= i;
Console.WriteLine(fact);
public static void Main(string[] args)
{
string result = Convert.ToString(GetFactorial(5));
Console.WriteLine(result);
}
internal static int GetFactorial(int factNumber)
{
int factorial =1;
int i = factNumber;
while(factNumber>=1)
{
factorial = factNumber * factorial;
factNumber--;
}
return factorial;
}
How about this?
public int FactorialFunction(int Factorial){
int Product = Factorial -1;
for(int Number = Factorial - 1; Number < Factorial; Number++ ) {
Factorial = Product * Factorial;
Product--;
}
return Factorial;
}

Find out how long the longest sequence is in a string

I recently had this question in an interview and this is what I came up with. Any feedback?
Find out how long the longest sequence is in a string. For example, in the string "abccdeeeeef" the answer would be 5.
static int LongestSeq(string strPass)
{
int longestSeq = 0;
char[] strChars = strPass.ToCharArray();
int numCurrSeq = 1;
for (int i = 0; i < strChars.Length - 1; i++)
{
if (strChars[i] == strChars[i + 1])
{
numCurrSeq++;
}
else
{
numCurrSeq = 1;
}
if (longestSeq < numCurrSeq)
{
longestSeq = numCurrSeq;
}
}
return longestSeq;
}
This will return 0 for strings of length 1 (when it should return 1).
First comment: you don't need to convert it to a char array. You can index straight into the string.
Second comment: you could easily generalize this to IEnumerable<T> if you wanted to, using foreach and remembering the "current" item.
Third comment: I think the comparison between longestSeq and numCurrSeq would be clearer as:
if (numCurrSeq > longestSeq)
To me that's more natural as I usually have the varying part of the expression first.
Just to add my 2 pence in, here's an alternative using Regex:
string source = "eeabccdeeeeef";
Regex reg = new Regex(#"(\w)\1+");
MatchCollection matches = reg.Matches(source);
int longest = 0;
foreach (System.Text.RegularExpressions.Match match in matches)
{
if (longest < match.Length) longest = match.Length;
}
Due to not reading the question properly in the first place when posting my previous answer, I should probably add in some actual feedback considering that's the question posted by the OP. However, every point I've come up with has been mentioned by Henrik or Job Skeet, so I'll just stress the point Jon Skeet made; you do not have to convert a string to a char array, you can just index a particular point in the string as follows:
char letter = someString[4];
So it should all still work if you replace strChars with strPass.
You can always rember the last character, so you don't need to access the array twice in an iteration.
Inside your loop you can use another loop which iterates as long as the current character is the same as the last character. After this subloop you can place the check if the current numCurrSeq > longestSeq you you don't need this check every iteration but for every subsequence.
I don't really know whatever langauge this is (C#?) so excuse any minor syntactic glitches (I don't know if it's "else if" or "elseif" or "elif" or something else)
static int LongestSeq(string strPass)
{
int longestSeq = 1;
int curSeqStart = 0;
for (int i = 1; i < strPass.Length; i++)
{
if (strPass[i] != strPass[curSeq])
{
curSeqStart = i;
}
else if (i - curSeqStart + 1 > longestSeq)
{
longestSeq = i - curSeqStart + 1;
}
}
return longestSeq;
}
It might be more efficient to do
...
else
{
len = i - curSeqStart + 1
if ( len > longestSeq )
{
longestSeq = len;
}
}
or even just
...
else
{
longestSeq = max(longestSeq, i - curSeqStart + 1)
}
depending on how good your 'max' implementation and compiler are.
I think this works? I don't ussually write recursive methods, I would have totally come up with the posters answer..
public static int recurse(Char last, int seqLength, int currentIndex, int largestSeqLength, string source)
{
if (currentIndex > source.Length)
{
return largestSeqLength;
}
if (source[currentIndex] == last)
{
seqLength++;
if (seqLength > largestSeqLength)
{
largestSeqLength = seqLength;
}
}
else
{
seqLength = 1;
}
return recurse(source[currentIndex], seqLength, currentIndex++, largestSeqLength, source);
}
And another implementation
public static int LongestSeq<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException("source");
int result = 0;
int currentCount = 0;
using (var e = source.GetEnumerator())
{
var lhs = default(T);
if (e.MoveNext())
{
lhs = e.Current;
currentCount = 1;
result = currentCount;
}
while (e.MoveNext())
{
if (lhs.Equals(e.Current))
{
currentCount++;
}
else
{
currentCount = 1;
}
result = Math.Max(currentCount, result);
lhs = e.Current;
}
}
return result;
}
A simple (untested) solution would be:
int GetLongestSequence(string input)
{
char c = 0;
int maxSequenceLength = 0;
int maxSequenceStart = 0;
int curSequenceLength = 0;
int length = input.Length;
for (int i = 0; i < length; ++i)
{
if (input[i] == c)
{
++curSequenceLength;
if (curSequenceLength > maxSequenceLength)
{
maxSequenceLength = curSequenceLength;
maxSequenceStart = i - (curSequenceLength - 1);
}
}
else
{
curSequenceLength = 1;
c = input[i];
}
}
return maxSequenceStart;
}
Or a better structured code (also untested):
private int GetSequenceLength(string input, int start)
{
int i = start;
char c = input[i];
while (input[i] == c) ++i; // Could be written as `while (input[i++] == c);` but i don't recommend that
return (i - start);
}
public int GetLongestSequence(string input)
{
int length = input.Length;
int maxSequenceLength = 0;
int maxSequenceStart = 0;
for (int i = 0; i < length; /* no ++i */)
{
int curSequenceLength = this.GetSequenceLength(input, i);
if (curSequenceLength > maxSequenceLength)
{
maxSequenceLength = curSequenceLength;
maxSequenceStart = i;
}
i += curSequenceLength;
}
return maxSequenceStart;
}
This extension method find the longest sequence of same characters in a string.
public static int GetLongestSequenceOfSameCharacters(this string sequence)
{
var data = new List<char>();
for (int i = 0; i < sequence.Length; i++)
{
if (i > 0 && (sequence[i] == sequence[i - 1]))
{
data.Add(sequence[i]);
}
}
return data.GroupBy(x => x).Max(x => x.Count()) + 1;
}
[TestMethod]
public void TestMethod1()
{
// Arrange
string sequence = "aabbbbccccce";
// Act
int containsSameNumbers = sequence.GetLongestSequenceOfSameCharacters();
// Assert
Assert.IsTrue(containsSameNumbers == 5);
}

Categories

Resources