C
C#2y ago
katze

❔ Trying to write to file of a Collatz Conjecture program

hello, complete beginner here. im trying to make a program that takes a random number and puts it through the collatz conjecture, then sends every number used in the collatz conjecture to a .txt file on a USB drive. (quite a mouthful, i know). ive got the part about the collatz conjecture done, but i cant write to a file; i tried using streamwrite and File.WriteAllLines with an array
static void Main(string[] args)
{
Random randgen = new Random();
UnicodeEncoding encoder = new UnicodeEncoding();

Console.ReadLine();

start:

var values = Array.Empty<string>();

int selectedNum = randgen.Next();
int x = selectedNum;

string localPath = (@"D:\COLLATZ\" + Convert.ToString(x) + ".txt");

Console.WriteLine("Input: {0}", selectedNum);

while (x > 0)
{
if (x == 1)
{
break;
}
if (x % 2 == 0)
{
x = x / 2;
Console.WriteLine("{0} | {1} | {2}", x, "div", Convert.ToString(x % 2));

}
else
{
x = (x * 3) + 1;
Console.WriteLine("{0} | {1} | {2}", x, "mul", Convert.ToString(x % 2));
}

values.Append(Convert.ToString(x));

}

File.WriteAllLines(localPath,values);

Console.WriteLine(String.Join(",", values));
Console.ReadKey();

goto start;
}
}
}
static void Main(string[] args)
{
Random randgen = new Random();
UnicodeEncoding encoder = new UnicodeEncoding();

Console.ReadLine();

start:

var values = Array.Empty<string>();

int selectedNum = randgen.Next();
int x = selectedNum;

string localPath = (@"D:\COLLATZ\" + Convert.ToString(x) + ".txt");

Console.WriteLine("Input: {0}", selectedNum);

while (x > 0)
{
if (x == 1)
{
break;
}
if (x % 2 == 0)
{
x = x / 2;
Console.WriteLine("{0} | {1} | {2}", x, "div", Convert.ToString(x % 2));

}
else
{
x = (x * 3) + 1;
Console.WriteLine("{0} | {1} | {2}", x, "mul", Convert.ToString(x % 2));
}

values.Append(Convert.ToString(x));

}

File.WriteAllLines(localPath,values);

Console.WriteLine(String.Join(",", values));
Console.ReadKey();

goto start;
}
}
}
3 Replies
reflectronic
reflectronic2y ago
values.Append(Convert.ToString(x)); does not do what you think it does it does nothing, actually, in this instance it returns a new list, it doesn't change values i think you want values to be a List<string>:
var values = new List<string>();
var values = new List<string>();
and then you want to call Add on values:
values.Add(x.ToString());
values.Add(x.ToString());
in C#, an array cannot be "appended" to, it has a fixed size. you use List<T> instead
katze
katzeOP2y ago
thanks!
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server