How to pass a value from one method to another method? - c#

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}");
}

Related

Input any mathematical table without using loops

I need to print mathematical table without using any loop (for, while, do while, etc.). Can anyone help me out, the easiest example I could find was writing console.writeline 10times for each line.
This is my code!
using System;
using System.Linq;
class Question4
{
int product, i=1;
public static void Main(string[] args)
{
int num;
Console.Write("Enter the Number to Print its Multiplication Table: ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nMultiplication Table For {0}: ",num);
TableFunctionName (num);
}
public void TableFunctionName(int n)
{
if(i<=10)
{
table=n*i;
Console.WriteLine("{0} x {1} = {2}",n,i,table);
i++;
}
return;
}
}
Using recursion
static void Multiply(int a, int b) {
if (a > 1)
Multiply(a - 1, b);
Console.WriteLine($"{a} * { b} = {a * b}");
}
static void Main(string[] args) {
Multiply(10, 5);
}
}
You could use recursion
public static void Main()
{
Console.Write("Enter the Number to Print its Multiplication Table: ");
var input = Console.ReadLine();
var number = Convert.ToInt32(input);
CalculateAndPrint(number, 1);
}
static void CalculateAndPrint(int number, int factor)
{
if (factor > 9) return;
Console.WriteLine("{0} x {1} = {2}", number, factor, number * factor);
CalculateAndPrint(number, ++factor);
}

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).

Sum the values of the array with a method

So I'm trying to get 10 inputs from a user via Console, store in them in an array, calculate in a method what the sum is and return it. I'm still in the process, so this isn't mean to be completed code, but I'm confused at this point why my error list says Main should be closed after the while statement?
class Program
{//Start class
//We need to declare the size of our array
const int ARRAYSIZE = 10;
static void Main()
{//Start main
//We need to create a counter for how many entries we currently have
int entries = 0;
int sumScore = 0;
//We need to create the array
int[] myArray = new int[ARRAYSIZE];
//Start a loop to ask for input
do
{//Start loop
Console.Write("Please enter the score of each test: ");
int entry = int.Parse(Console.ReadLine());
myArray[entries] = entry;
entries++;
}
while (entries < ARRAYSIZE);//End loop
static void PrintArray(int[ ] myArray)
{
foreach(int value in myArray)
{
Console.WriteLine(value);
Console.ReadLine();
}
}
}//End main
}//End class
At the position of static void PrintArray(int[ ] myArray), you are declaring a new function. You need the }//End main before you declare a new function:
do
{//Start loop
Console.Write("Please enter the score of each test: ");
int entry = int.Parse(Console.ReadLine());
myArray[entries] = entry;
entries++;
}
while (entries < ARRAYSIZE);//End loop
}//End main
static void PrintArray(int[ ] myArray)
{
foreach(int value in myArray)
{
Console.WriteLine(value);
Console.ReadLine();
}
}
You have misplaced the closing bracket of your Main method. You may also want to call your PrintArray method after while (entries < ARRAYSIZE);//End loopand also compute your sum inside that method. But I guess it is because, as you said, it is a work in progress. Here is what it looks like
class Program
{
const int ARRAYSIZE = 10;
static void Main()
{//Start main
//We need to create a counter for how many entries we currently have
int entries = 0;
int sumScore = 0;
//We need to create the array
int[] myArray = new int[ARRAYSIZE];
//Start a loop to ask for input
do
{//Start loop
Console.Write("Please enter the score of each test: ");
int entry = int.Parse(Console.ReadLine());
myArray[entries] = entry;
entries++;
}
while (entries < ARRAYSIZE);//End loop
PrintArray(myArray);
}//End main
static void PrintArray(int[ ] myArray)
{
int sum = 0;
foreach(int value in myArray)
{
sum += value;
Console.WriteLine(value);
Console.ReadLine();
}
Console.WriteLine(sum);
}
}
This isn't a direct answer to your question, but I thought it might be interesting for you.
If you'd like to do this in a slightly easier way, then try this:
static void Main()
{
var sum =
Enumerable
.Range(0, ARRAYSIZE)
.Select(n =>
{
Console.WriteLine("Please enter the score of each test:");
return int.Parse(Console.ReadLine());
})
.Sum();
Console.WriteLine();
Console.WriteLine("The sum is:");
Console.WriteLine(sum);
}

Variable (iUserNum2) does not exist in the current context in PowerOf function in C#

/* Hello I am a student trying to do some practice programming tasks, but I can't seem to get one of my variables to work in a function, I need the value of the variable to be inputted by the user, but it wants we to declare it inside the PowerOf function rather than the Main function, sorry to be a n00b, but any help would be greatly appreciated. [:*/
using System;
namespace ThePowerOf
{
class MainClass
{
public static void Main (string[] args)
{
string sUserInput;
int iUserNum1 = 0;
int iUserNum2 = 0;
int iPower = 0;
Console.WriteLine ("Enter a number");
sUserInput = Console.ReadLine();
iUserNum1 = Int16.Parse(sUserInput);
Console.WriteLine ("Enter a number");
sUserInput = Console.ReadLine();
iUserNum2 = Int16.Parse(sUserInput);
iPower = PowerOf(iUserNum1);
Console.WriteLine((iUserNum1) + (" To the power of ") + (iUserNum2) + (" = ") + (iPower));
Console.ReadLine();
}
static int PowerOf(int iUserNum1)
{
for (int i = 0; i < iUserNum2; ++i)
{
iUserNum1 = (iUserNum1 * iUserNum1);
}
return iUserNum1;
}
}
}
You function was declared wrong way, how can you calculate power raised to a number by passing a single parameter (unless one of the value is constant)
Fixed Method Deceleration :
static int PowerOf(int iUserNum1, int iUserNum2)
{
int result = 1;
for (int i = 0; i < iUserNum2; i++)
{
result = result*iUserNum1;
}
return result;
}
And do change the way you are invoking the function, invoke it properly with 2 parameters!
static void Main()
{
string sUserInput;
int iUserNum1 = 0;
int iUserNum2 = 0;
int iPower = 0;
Console.Write("Enter a number : ");
sUserInput = Console.ReadLine();
iUserNum1 = Int32.Parse(sUserInput); // iUserNum1 is declared as 'int' so Int32.Parse()
Console.Write("Enter a number to waise power to :");
sUserInput = Console.ReadLine();
iUserNum2 = Int32.Parse(sUserInput); // iUserNum2 is declared as 'int' so Int32.Parse()
iPower = PowerOf(iUserNum1, iUserNum2);
Console.WriteLine(iUserNum1 + " To the power of " + iUserNum2 + " = " + iPower);
Console.ReadLine();
}
Move your declaration of iUserNum2 into the class level:
class MainClass
{
int iUserNum2 = 0; // PUT IT HERE
public static void Main (string[] args)
{
Variables declared in methods aren't shared. Variables declare within a class are shared (provided they are non-static and used in non-static methods.. but that's for you to learn later).

inputs in methods at visual c# 2005

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.

Categories

Resources