Beginner question about a task in a course in C# - c#

The code
class Program
{
static int Add(int x, int y)
{
x = 4;
y = 3;
int f = x + y;
return f;
}
static void Main(string[] args)
{
int x = 4;
int y = 3;
Console.WriteLine("Answer: ");
Add(x, y);
}
}
Doing a beginner course in C# and I have been stuck at this question for two days now.
I know its probably really simple, but I have tried so many different things that I think I have made it harder for me than it really.
I fixed to call strings in methods, but numbers seems hard.
The task is about to take two numbers in and that return the answer.
Tried searching around all the different errors I got with all the different tries, but didn't find the help, or the answers I understand.

You almost did all of it, just with 2 issues.
You should relay on the numbers you pass from Main to Add and not reassign the values inside Add otherwise passing them is useless and unusable for other numbers.
Add returns a value but you never save it + print it.
Example for #1
static int Add(int x, int y)
{
int f = x + y;
return f;
}
Example of #2
var result = Add(x, y);
Console.WriteLine(result);

Corrected Example:
class Program
{
static int Add(int x, int y)
{
// You don't need to redefine the variables x and y,
// because you get them when you call the method
// You can shorten the last part
// and just return the Addition
return x + y;
}
static void Main(string[] args)
{
int x = 4;
int y = 3;
// Prints the Word Answer
// as well as the Addition result into the Console now
Console.WriteLine("Answer: " + Add(x, y));
}
}
Your Errors:
You never printed the Result into the Console!
You shouldn't redefine the variables in the Function, because if you do that you don't need to use a function in the first place
You can shorten the return statement (you don't have to)
You can add Add(x,y) into the Console.WriteLine because it returns a Integer, therefore it is basically like writting Console.WriteLine("Answer: " + 7);

Here is an working version with explaination:
class Program
{
static int Add(int x, int y)
{
//x = 4; these are passed in as parameter, no need to set it
//y = 3;
int f = x + y;
return f;
}
static void Main(string[] args)
{
int someX = 4; //these are only known inside the scope of "Main"
int someY = 3;
int result = Add(someX, someY); //these are passed inside the function,
//the value is copied
Console.WriteLine("Answer: " + result.ToString());
}
}

You can do it even easier and simple In addition , this answer is more dynamic as you can choose the two numbers every time you run the program:
class Program
{
static int Add(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
Console.WriteLine("Answer: " + Add(Convert.ToInt32(Console.ReadLine()),
Convert.ToInt32(Console.ReadLine())).ToString());
Console.ReadLine(); //In order to be able to see the result in the screen
}
}

Related

C# Class Inheritance Issue with Simple Calculator

I am beginner to C# and am trying to get my second class, MyCalc2, to inherit from MyCalc. But I encounter the following error message in regards to MyCalc2:
There is no argument given that corresponds to the required formal parameter 'x' of 'MyCalc.MyCalc(int, int, string, string)'
The goal here is to just add another class that inherits from the base class.
I know that I need to add something like 'MyCalc: base(x)' to my base class but am lost to where to place the parameter (if that is even the correct thing to do). Any guidance would be appreciated. Here is what I have so far:
using System;
class MyCalc
{
// class variable
public int x;
public int z;
public string y;
public string n;
// constructor
public MyCalc(int x, int z, string y, string n)
{
this.x = x; // assign the parameter passed to the class variable
this.z = z;
this.y = y;
this.n = n;
}
// calculate the operations
public int GetAdd()
{
return (this.x + this.z);
}
public int GetSubtract()
{
return (this.x - this.z);
}
public int GetMultiply()
{
return (this.x * this.z);
}
public int GetDivide()
{
return (this.x / this.z);
}
public string GetYes()
{
return (this.y);
}
public string GetNo()
{
return (this.n);
}
}
class MyCalc2:MyCalc //where the error is occurring
{
static void Main(string[] args)
{
bool repeat = false;
do
{
repeat = false;
int x = 0; int z = 0; string y; string n;
Console.WriteLine("Enter the First Number");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Second Number");
z = Convert.ToInt32(Console.ReadLine());
//Using a switch statement to perform calculation:
Console.WriteLine("Enter operator\r");
switch (Console.ReadLine())
{
case "+":
Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
break;
case "-":
Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
break;
case "*":
Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
break;
case "/":
Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
break;
}
//Repeat or Exit program using the do-while loop:
string input = Console.ReadLine();
Console.WriteLine("Do you want another operation(Y / N) ?");
input = Console.ReadLine();
repeat = (input.ToUpper() == "Y");
}
while (repeat);
Console.WriteLine("Thanks for using our system.");
Console.ReadKey();
}
}
MyCalc2 does not have a way of initializing MyCalc (Base Class) Because in your BaseClass you do not have a parameter less constructor.
Solution:
Add a param less constructor in Base Class
Add a constructor in Derived class which has a way of calling base class constructor
for your code below should work:
class MyCalc2 : MyCalc
{
public MyCalc2 () : base(0, 0, "", "")
{
}
}
MyCalc2 has no explicit constructor. Which means it has only one implicit constructor which takes no arguments and sets no values. If made explicitly it would look like this:
public MyCalc2()
{
}
However, MyCalc does have an explicit constructor. Which means it has no implicit constructor. And its constructor does take arguments:
public MyCalc(int x, int z, string y, string n)
{
this.x = x; // assign the parameter passed to the class variable
this.z = z;
this.y = y;
this.n = n;
}
So when you create an instance of MyCalc2 it has no way of providing any values to MyCalc. You essentially have three options:
Add a constructor to MyCalc (you can have as many constructors as you want, as long as the parameters differ) which takes no parameters. However, in that case the class-level values for MyCalc would all be default values. You'd have to set them explicitly after constructing the object.1
Add a constructor to MyCalc2 which accepts those values and passes them to the parent constructor, or at least passes default values to the parent constructor.
Don't use inheritance here.
Honestly, in this case I'd go with the third option. What is inheritance meant to accomplish here? MyCalc2 isn't meaningfully an instance of MyCalc. All it does it hold the initial entry point of the application (the Main method), and that's really all it should do.
The logic in your Main method should create and use an instance of MyCalc, but the class which has that Main method shouldn't try to be an instance of MyCalc. That will only cause more confusion than solve any meaningful problems.
1 Side Note: Public class fields are historically a bad habit to get into in object-oriented programming. There's a variety of talk on the subject, and you'll see this often as you continue in your experience. In general you want your objects to expose behaviors, not values. The methods on the object look somewhat Java-like in convention. For C# conventions consider using properties (which compile down to methods themselves, the syntax is just semantically different). You can have { get; set; } auto-properties for the values themselves, and explicit read-only { get { /*...*/ } } properties for the calculated values.
Here is a possible solution. There are two classes MyClass, for the calculator (you may want to rename it) and Propram. Program holds just the method Main, which get your program started. It works like this, but there are some bugs left. I leave it to you to fix them. Except that you miss a clear understanding of the concepts class and inheritance, your code is not too bad for a beginner. It is almost working.
using System;
namespace TestCalculator
{
class MyCalc
{
// class variable
public int x;
public int z;
public string y;
public string n;
// constructor
public MyCalc(int x, int z, string y, string n)
{
this.x = x; // assign the parameter passed to the class variable
this.z = z;
this.y = y;
this.n = n;
}
// calculate the operations
public int GetAdd()
{
return (this.x + this.z);
}
public int GetSubtract()
{
return (this.x - this.z);
}
public int GetMultiply()
{
return (this.x * this.z);
}
public int GetDivide()
{
return (this.x / this.z);
}
public string GetYes()
{
return (this.y);
}
public string GetNo()
{
return (this.n);
}
}
class Program
{
static void Main(string[] args)
{
bool repeat = false;
do
{
repeat = false;
int x = 0; int z = 0; string y; string n;
Console.WriteLine("Enter the First Number");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Second Number");
z = Convert.ToInt32(Console.ReadLine());
//Using a switch statement to perform calculation:
Console.WriteLine("Enter operator\r");
switch (Console.ReadLine())
{
case "+":
Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
break;
case "-":
Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
break;
case "*":
Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
break;
case "/":
Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
break;
}
//Repeat or Exit program using the do-while loop:
string input = Console.ReadLine();
Console.WriteLine("Do you want another operation(Y / N) ?");
input = Console.ReadLine();
repeat = (input.ToUpper() == "Y");
}
while (repeat);
Console.WriteLine("Thanks for using our system.");
Console.ReadKey();
}
}
}

c# passing Parameters values from function to other function

are there any way to get the values from Parameters in "functionone" and calculate it in the "functiontwo" without writing that again that's a small code for example what i mean
public void functionone(int x, int y)
{
x = 1;
y = 2;
}
public void functiontwo(int a , int b )
{
a=x+y;
b=x-y;
Console.WriteLine(a);
Console.WriteLine(b);
}
You are implementing functionone wrongly I guess
doing this:
public void functionone(int x, int y)
{
x = 1;
y = 2;
}
is normally not the way to pass parameters and change its values in the method,
or saying in another way, x and y should be holding the values you pass as parameters, and no getting assigned inside the method..
define a global x and global y, then you can access to it everywhere in that scope..
Example:
class Abc{
int globalX;
int globalY;
....
public void functionone(int x, int y)
{
globalX = 1 + x;
globalY = 2 + y;
}
public void functiontwo(int a , int b )
{
a=globalX + globalY;
b=globalX - globalY;
Console.WriteLine(a);
Console.WriteLine(b);
}
}
To explain my comment:
int globalX;
int globalY;
public void functionone(ref int x, ref int y)
{
x = 1;
y = 2;
}
public void functiontwo(ref int a , ref int b)
{
a = globalX + globalY;
b = globalX - globalY;
Console.WriteLine(a);
Console.WriteLine(b);
}
// in main
functionone(ref globalX, ref globalY);
// globalX and globalY are now 1 and 2
functiontwo(ref a, ref b);
// a = 3 and b = -1 -> 'globalX +/- globalY'
This way you can set the values of any variables you pass to functionone or functiontwo.
However it doesn't look good and in my opinion it's not a good code. Your concept seems wrong, so maybe you can post a description of the problem you encountered?

c# create program using function to generate multiplication table using [Class Library] and test the function with different scenarios [NUnit]

Hi I need a little help creating a simple program that will Generate multiplication table (using for-loop) by using Class Library from VS C#.
I have here below the incomplete code for the for-loop but I got lost coz it's a bit different than application form and console application. If you're using class library you cannot use debug, you can run or check the codes by using Test Explorer/ Test.
(Edited Update 1) For this 2 things are needed.
Class Library (Main program)
Same solution but another class name, now it comes with NUnit that is referenced to the Main Program.
(Edited Update 2)
I'll be back to check for some info
Update 3. Here's the new code
namespace FunctionTest
{
[TestFixture]
public class Class1
{
[Test]
public void Multiplication()
{
int i;
int n = 0;
n = Convert.ToInt32(Console.ReadLine());
for (i = 1; i < 13; i++)
{
Console.WriteLine(i + "x" + n + " = " + i * n);
}
}
}
Here's the idea or what it should be look like. (Below is the program)
using System;
namespace ExerciseFunction
{
public class Equations
{
public int addition(int x, int y)
{
int z = x + y;
return z;
}
public int subtraction(int x, int y)
{
int z = x - y;
return z;
}
public int multiplication(int x, int y)
{
int z = x * y;
return z;
}
public int division(int x, int y)
{
int z = x / y;
return z;
}
static void Main(string[] args)
{
}
}
}
Now this one is the NUnit to check if the input or answer is correct or not of the Program.
using NUnit.Framework;
using ExerciseFunction;
namespace ExerciseNunit
{
[TestFixture]
public class Operations
{
[Test]
public static void addition()
{
Equations result = new Equations ();
float r = result.addition(4, 5);
Assert.AreEqual(9, r);
Assert.AreNotEqual(13, r);
}
[Test]
public static void subraction()
{
Equations result = new Equations();
int t = result.subtraction(5, 3);
Assert.AreEqual(2, t);
Assert.AreNotEqual(5, t);
}
[Test]
public static void multiplication()
{
Equations result = new Equations();
int y = result.multiplication(6, 3);
Assert.AreEqual(18, y);
Assert.AreNotEqual(15, y);
}
[Test]
public static void division()
{
Equations result = new Equations();
int u = result.division(4, 2);
Assert.AreEqual(2, u);
}
}
}
Thanks and looking forwards hearing your response. Your help is appreciated!
If you want to write a program, you probably want to execute it too. So you need and executable, not a library.
So first create a new project "Console Application" or "Windows Forms Application", or maybe a "WPF application" but not a Class Library. Also writing some unit test is useful, but I don't thing that in this case.
Secondly: do not declare loop variable i before the cycle. Do it in the cycle like this
for (int i = 0; i < 15; ++i) //or i++ there is a difference but not relevant right now.
Then... You probably want to get some input from a user to get your n.
In console application you can do that like this
int n;
string input = Console.ReadLine();
if (int.TryParse(input, out n))
{
//do your math here.
}
else
{
Console.WriteLine("That was not a number.");
}
Your for-cycle would work but the formatting of the output will be poor and most importantly, you are not printing or giving the output anywhere. So let's fix it like this (put that to place "//do your math here."):
for (int i = 1; i < 15; ++i)
{
Console.WriteLine(string.Format("{0} x {1} = {2}", i, n, i * n));
}
In the end you might want the application not to exit immediately. If you add Console.ReadLine(); in the end. It will wait for pressing any key before it exits.
If you so much want to have the algebra part in another project (which doesn't really make sense, but OK), you can create another project (Class Library) with this class in it (or put just the class in the existing project):
public static class Algebra
{
public static int Multiply(int a, int b)
{
return a * b;
}
//.... other methods
}
and then call it in the for loop like this:
int product = Algebra.Multiply(i, n);
Console.WriteLine(string.Format("{0} x {1} = {2}", i, n, product));
And of course you can then unit-test the Multiply method as much as you want.

Get name of delegate method

Out of curiosity I've been looking into delegate methods and am interested in getting the name of the current delegate method that is being used (just for fun, really).
The code I have is as follows (with the current/desired outputs):
private delegate int mathDelegate(int x, int y);
public static void Main()
{
mathDelegate add = (x,y) => x + y;
mathDelegate subtract = (x,y) => x - y;
mathDelegate multiply = (x,y) => x * y;
var functions = new mathDelegate[]{add, subtract, multiply};
foreach (var function in functions){
var x = 6;
var y = 3;
Console.WriteLine(String.Format("{0}({1},{2}) = {3}", function.Method.Name, x, y, function(x, y)));
}
}
/// Output is:
// <Main>b__0(6,3) = 9
// <Main>b__1(6,3) = 3
// <Main>b__2(6,3) = 18
/// Desired output
// add(6,3) = 9
// subtract(6,3) = 3
// multiply(6,3) = 18
Does anyone know of any way(s) I could achieve this? Thanks.
Your methods are anonymous delegates, so the the compiler gives each of them a name that doesn't have any meaningful connection back to the variable name. If you want them to have better names then make them actual methods:
public int Add(int x, int y)
{
return x + y ;
}
etc. Then reference them by name:
var functions = new mathDelegate[]{this.Add, this.Subtract, this.Multiply};
Note that the this. is optional but illustrates that they are class members rather than local variables.

c# print the power of a number using recursion

I am learning about recursion and I am required to multiply and do the power of two given numbers. When I run my code it doesn't work (meaning nothing shows on the console)
Methods:
static int multiply (int x, int y)
{
if ( y == 1 )
return x ;
else
return (x + multiply(x, y - 1));
}
static int power(int x,int y)
{
if (y == 0)
return 0;
else
return (x * power(x, y - 1));
}
Main method:
static void Main(string[] args)
{
multiply(2, 4);
power(2, 5);
Console.ReadLine();
}
Anybody have any ideas? I have a feeling im doing something obviously stupid.
Output your code to console:
Console.WriteLine(multiply(2, 4));
Console.WriteLine(power(2, 5));
You may also need to fix the bug on power:
if (y == 0) return 1; // x⁰ = 1
Currently, you are not outputting any data to the console so you can see it. The function Console.WriteLine() will write to the console. Console.ReadLine() on the other hand, will continually wait for input from the console, this is to prevent the program from exiting immediately. Your Main method should look more like this:
static void Main(string[] args)
{
int z = multiply(2, 4);
int p = power(2, 5);
Console.WriteLine("z : " + z);
Console.WriteLine("p : " + p);
Console.ReadLine();
}
You will notice a bug in your power function, but I'll let you debug that once you can see the output.
Try this:
static void Main(string[] args)
{
Console.WriteLine("2*4=" + multiply(2, 4));
Console.WriteLine("2^5=" + power(2, 5));
Console.ReadLine();
}

Categories

Resources