inputs in methods at visual c# 2005 - c#

I am facing a problem in creating a console application in Visual Studio c# 2005
I created the following program in which a method (to sum 2 predefined values) is called in the program
here is the code of it
class program
{
static void Main()
{
program a;
a = new program();
Console.WriteLine(a.am1(1,2));
Console.ReadLine();
}
int sum;
public int am1(int num1, int num2)
{
sum = num1 + num2;
return sum;
}
}
Now here is the main problem I am facing, well in this program two integers (num1 and num2) are predefined, I wanted those 2 numbers to be taken from user, means user input the two numbers and then the same program goes on like above. How it should be done?
P.S remember everything should be done in methods

i hope i got your requirements ... if not, please elaborate!
public sealed class Program
{
private readonly int _number1;
private readonly int _number2;
public Program(int number1, int number2)
{
this._number1 = number1;
this._number2 = number2;
}
public int Sum()
{
return this._number1 + this._number2;
}
public static void Main(string[] args)
{
// this one here is really brutal, but you can adapt it
int number1 = int.Parse(args[0]);
int number2 = int.Parse(args[1]);
Program program = new Program(number1, number2);
int sum = program.Sum();
Console.WriteLine(sum);
Console.ReadLine();
}
}
sry, this is not my main coding style ... pfuh ... really ugly!
edit:
don't give blind trust in int.Parse(). the params are coming from the user, you better double check them!
you better triple check them, as you are doing a sum ... thankfully c# compiles with unchecked - this code may fail with an OverflowException if compiled in vb - remember ranges of int
why do you want to do a simple addition in an extra class?
you should elaborate your style (regarding your comment): separate ui-code from business-layer code!
you do not need to create an instance variable for each task - you can do that with scope variables too...!
...

Use console application command line arguments. If it suites you. Below is an example from MSDN.
public class Functions
{
public static long Factorial(int n)
{
// Test for invalid input
if ((n < 0) || (n > 20))
{
return -1;
}
// Calculate the factorial iteratively rather than recursively:
long tempResult = 1;
for (int i = 1; i <= n; i++)
{
tempResult *= i;
}
return tempResult;
}
}
class MainClass
{
static int Main(string[] args)
{
// Test if input arguments were supplied:
if (args.Length == 0)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Try to convert the input arguments to numbers. This will throw
// an exception if the argument is not a number.
// num = int.Parse(args[0]);
int num;
bool test = int.TryParse(args[0], out num);
if (test == false)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Calculate factorial.
long result = Functions.Factorial(num);
// Print result.
if (result == -1)
System.Console.WriteLine("Input must be >= 0 and <= 20.");
else
System.Console.WriteLine("The Factorial of {0} is {1}.", num, result);
return 0;
}
}
// If 3 is entered on command line, the
// output reads: The factorial of 3 is 6.

Related

How to pass a value from one method to another method?

I'm a new to C#, please give me some advice on my program. How to pass a value from a method to another method? I am trying to do a calculation by using the value n from part_number in another method.
class Program
{
static void Main(string[] args)
{
int n;
part_number(out n);
Athlete myobj = new Athlete();
int n1 = 0;
for (n1 = 0; n1 < n; ++n1)
{
Write("Enter your participant name >> ");
myobj.participant_Name = ReadLine();
WriteLine("Event codes are:");
WriteLine("T Tennis");
WriteLine("B Badminton");
WriteLine("S Swimming");
WriteLine("R Running");
WriteLine("O Other");
Write("Enter event code>> ");
myobj.event_Code0 = ReadLine();
}
double totalCost;
const double cost = 30.00;
totalCost = cost * n1;
WriteLine("The total cost is {0}", totalCost);
static void part_number(out int n)
{
n = 0;
WriteLine("Enter the number the participant this year>> ");
n = System.Convert.ToInt32(ReadLine());
while (n >= 40)
{
WriteLine("Please enter number between 0 to 40");
n = System.Convert.ToInt32(ReadLine());
}
}
}
How to pass the value of n from part_number method and another method? I need to the use that value to do a calculation in another method. Should I build a class for it?
Thank you!
You would simply add an argument to the method such as:
void MyOtherMethod(int number)
{
// do something with number
}
If you wanted, you could pass multiple things by commad delimiting them:
void MyOtherMethod(int number, string name)
{
}
You can also have a method returning a value:
int MyReturningMethod(int number)
{
return number + 2;
}
The possibilities are endless.
You will have to call your other method and pass it in.
public static Main(string[] args)
{
PartNumer(out var partNumber);
OtherMethod(partNumber);
}
static void PartNumber(out int pn)
{
pn =1;
}
static void OtherMehtod(int partNumber)
{
Console.WriteLine($"Your part number is {partNumber}");
}

Dividing 2 integer without using / operator using c#. Can anyone convert this to for loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Can I ask for this question to be deleted? To help me recover my account. Thank you
int[] numbers = { 200, 100, 50, 3, 1 };
int count = int.Parse(txtNumber.Text);
double number = 0;
double number1 = 0;
double number2 = 0;
double number3 = 0;
double number4 = 0;
if (count == 0)
{
MessageBox.Show("Can't Divide 0");
return;
}
while (count >= numbers[0])
{
count = count - numbers[0];
number++;
}
txt200.Text = number.ToString();
label1.Text = count.ToString();
while (decimal.Parse(label1.Text) >= numbers[1])
{
label1.Text = (int.Parse(label1.Text) - numbers[1]).ToString();
number1++;
}
txt100.Text = number1.ToString();
Can somebody help me to vote this for deletion??
You can do it with an empty for loop, where all the operations occur in the loop's condition and the iterator:
int result = 1;
for (int numCopy = numerator; numCopy > denominator; numCopy -= denominator, result++);
Here's a sample method:
public static int Divide(int numerator, int denominator)
{
int result = 0;
for (; numerator >= denominator; numerator -= denominator, result++) ;
return result;
}
Note that I'm working only with integers here. Converting strings to integers and then back to strings again inside a loop is not very efficient. Now we can convert the Text properties once, pass the integers to our method, and then convert the result once.
Here's a sample usage (using a Console application):
static void Main()
{
int numerator = GetIntFromUser("Please enter the numerator: ");
int denominator = GetIntFromUser("Please enter the denominator: ");
int result = Divide(numerator, denominator);
Console.WriteLine($"{numerator} / {denominator} = {result}");
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
Oh, and these are the helper methods I'm using:
private static int GetIntFromUser(string prompt)
{
int input;
do
{
Console.Write(prompt);
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
A typical while-loop looks like this:
// Initialize loop variable
int i = 0;
while (i < count) // Test loop condition
{
//TODO: Do some work.
// Increment loop variable
i++;
}
The for-loop allows you to initialize, test and increment the loop variable at one spot
for (int i = 0; i < count; i++) {
//TODO: Do some work.
}
But while-loops seem appropriate here. If you extract the calculation into a function, you can reuse it. This is better than copy-pasting the code to apply it to several inputs.
private static int Divide(int dividend, int divisor)
{
int result = 0;
int remainder = dividend;
while (remainder >= divisor) {
remainder -= divisor;
result++;
}
Console.WriteLine($"{dividend} / {divisor} = {result}, remainder = {remainder}");
return result;
}
Don't assign the label text inside the loop, as the label will only keep the last assignment. Also, labels are not a good place to store numbers.
Convert all the numbers that are in labels and textboxes to integers before you start any calculation.
Do the calculations without referencing any UI controls.
Convert and assign the result of the calculations to labels and textboxes.
Mixing UI stuff and calculations makes the code unnecessarily complicated and difficult to read.
Give speaking names to controls and variables. Nobody knows what a textbox named txt3, a label named label1 or a variable named number2 are supposed to represent. Good names are txtDividend, txtResult or dividend and result for the respective variables.

C# Zero-One Multiple OverflowException using ULong

I am trying to find the smallest zero-one number (a number that composes of only zeroes and ones i.e. 11001) that is a multiple of the number input through STDIN, but the program crashes when i input 99999, and this is one of the test cases that should work as the input value should range between 1 and 100000, the program crashes at
ulong.Parse(binary); in Getmultiple(ulong n).
What change should i make for it to work ?
class Program
{
static void Main(string[] args)
{
while (true)
{
string s = Console.ReadLine();
ulong l;
ulong.TryParse(s, out l);
Console.WriteLine(Getmultiple(l));
}
}
private static ulong Getmultiple(ulong n)
{
for (ulong i = 1; ; i++)
{
String binary = Convert.ToString((long) i, 2);
ulong no = ulong.Parse(binary);
if (no % n == 0)
{
return no;
}
}
}
}
ERROR MESSAGE:
An unhandled exception of type 'System.OverflowException' occurred in
mscorlib.dll
Additional information: Value was either too large or too
small for a UInt64.
You're overflowing the unsigned long variable, meaning that there isn't a multiple of 99999 fitting your requirements that's also less than 2^64. If you refactor your code to use BigInteger instead of unsigned long, then you won't have the overflow problem. It might take some time for your algorithm to find the solution, though...
I'd also make this change, to sanity check your input:
BigInteger l;
if(BigInteger.TryParse(s, out l))
Console.WriteLine(Getmultiple(l));
else
Console.WriteLine("Not a valid integer");
looks like you are getting too large of a number for ulong no, you can use ulong.TryParse to avoid this.
private static ulong Getmultiple(ulong n)
{
for (ulong i = 1; ; i++)
{
String binary = Convert.ToString((long)i,2);
ulong no = 0;
if (ulong.TryParse(binary,out no))
{
if (no % n == 0)
{
return no;
}
}
else
{
return 0;
}
}
}
I chose to return 0 for an invalid result.
Using BigInteger works!! Some testcases that failed with ulong are now
working, thanks Esoteric Screen Name!
static void Main(string[] args)
{
while (true)
{
string s = Console.ReadLine();
BigInteger l;
if (BigInteger.TryParse(s, out l))
Console.WriteLine(Getmultiple(l));
else
Console.WriteLine("Not a valid integer");
}
}
private static BigInteger Getmultiple(BigInteger n)
{
for (BigInteger i = 1; ; i++)
{
String binary = Convert.ToString((long) i, 2);
BigInteger no = BigInteger.Parse(binary);
if (no % n == 0)
{
return no;
}
}
}

Using a reference parameter

I'm learning C# by myself by book and would appreciate some help. I want to create a simple console program to allow the user to enter a number to be doubled. It says that the variable result in the Main method is unassigned, however, what am I doing wrong?
using System;
class Program
{
private static void Double(ref int num, ref int result)
{
result = num * 2;
}
private static int readNumber(string question)
{
Console.Write(question);
string ans = Console.ReadLine();
int number = int.Parse(ans);
return number;
}
public static void Main()
{
int num, result;
num = readNumber("Enter an integer to be doubled: ");
Double(ref num, ref result);
Console.WriteLine("The double of {0} is {1}", num, result);
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
The compiler is yelling at you because it wants to force you to initialize the variables before passing them to the method call.
Meaning:
int num, result;
Should be:
int num = 0;
int result = 0;
There may be a better way of doing what you're trying to do, without any ref parameters at all, by simply using the return value of the method:
private static int Double(int num)
{
return num * 2;
}
And consume it like this:
public static void Main()
{
int num = readNumber("Enter an integer to be doubled: ");
int result = Double(num);
Console.WriteLine("The double of {0} is {1}", num, result);
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
This may even (IMO) enhance the readability of your code and convey your intentions better.
´Why don´t you simply change the methods signatur to return a double instead of using a ref?
private static double Double(int num)
{
return num * 2;
}
Now you can simply call result = Double(num).

ASP.NET MVC app: Debugging a function that returns "true" if input number is a Happy number using Lists vs Hashsets in array

So I'm working on an MVC view model that will tell a user if a given integer input is a Happy Number or not. As stated, the final code will sit in an MVC view model, but in the meantime, I've been checking the logic by debugging the code as a separate console app. I've got the console app working, but when I migrate the code back to the view model and then debug in the full application, literally nothing happens and IIS eventually times out the request. My view and controller implementations look solid (I'm leaving out that code for now), so I think I'm screwing up the logic in my actual model. Thoughts?
The code explained in further detail:
I'm new to OO programming, so for the sake of my own comprehension, I have split up the program into to two separate functions (Yes, I am aware this is bad practice, but it's homework). The first function (see below), which I've called "sumPowered", takes an integer input, separates the individual digits into an array, squares the individual digits, and returns the sum of the squared digits. Next, I have created a validation function called "isHappy" in which I call the preceding sumPowered function, pass through the parameters, generate a result array, and compare them to the happy number conditions.
To provide a clear outline, the first block of code below is the working code as it appears in my console app. The second block demonstrates how the code appears in the view model (doesn't work).
EDIT: I should have clarified that I am not producing any build errors or errors in the console view of Chrome's property inspector when I run the MVC code, yet the function did not work. I have since found a fix (answer post pending).
CONSOLE APP
//CONSOLE APP
namespace MoreCSharpPractice
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number");
int number = Convert.ToInt32(Console.ReadLine());
isHappy(number);
}
public static int sumPowered(int num, int pow)
{
int sum = 0;
List<int> numsL = new List<int>();
while (num > 0)
{
numsL.Add(num % 10);
num = num / 10;
}
int[] nums = numsL.ToArray();
for (int a = 0; a < nums.Length; a++)
{
sum += Convert.ToInt32(Math.Pow(Convert.ToDouble(nums[a]), Convert.ToDouble(pow)));
}
return sum;
}
//HAPPY NUMBER
//return true if 'number' is a happy number.
private static void isHappy(int number)
{
List<int> sumArray = new List<int>();
bool running = true;
while (running)
{
int result = sumPowered(number, 2);
if (result == 1)
{
running = false;
Console.WriteLine("Is a Happy Number!");
}
else if (sumArray.Contains(result))
{
running = false;
//return false;
Console.WriteLine("Is not a Happy Number");
}
number = result;
sumArray.Add(result);
}
//return true;
Console.ReadKey();
}
}
}
MVC CODE
//VIEW MODEL CODE: SUM POWERED FUNCTION
public static int sumPowered(int num, int pow)
{
int sum = 0;
List<int> numsL = new List<int>();
while (num > 0)
{
numsL.Add(num % 10);
num = num / 10;
}
int[] nums = numsL.ToArray();
for (int i = 0; i < nums.Length; i++)
{
sum += Convert.ToInt32(Math.Pow(Convert.ToDouble(nums[i]), Convert.ToDouble(pow)));
}
return sum;
}
//VIEW MODEL CODE: HAPPY NUMBER FUNCTION
//return true if 'number' is a happy number.
private static bool isHappy(int number)
{
List<int> sumArray = new List<int>();
while (true)
{
int result = sumPowered(number, 2);
if (result == 1)
{
return true;
}
else if (sumArray.Contains(result))
{
return false;
}
number = result;
sumArray.Add(result);
}
}
Determined that this wasn't a logic error but instead a performance issue while running debug. By changing the data type of variable sumArray in my isHappy() function from a List to a HashSet, I was able to run through the function without having to iterate through an entire list when invoking else if (sumArray.Contains(result)).
//HAPPY NUMBER
//return true if 'number' is a happy number.
private static bool isHappy(int number)
{
HashSet<int> sumArray = new HashSet<int>();
while (true)
{
int result = sumPowered(number, 2);
if (result == 1)
{
return true;
}
else if (sumArray.Contains(result))
{
return false;
}
number = result;
sumArray.Add(result);
}
}

Categories

Resources