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();
}
Related
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
}
}
I'd like to achieve something like this:
Time consuming operation...OK
Another time consuming operation...
And another one, but it completed, so...OK
I displayed 3 line of text, each one related with a thread which can end sooner or later. But if the second one complete later than the third one, I'll get something like this:
Time consuming operation...OK
Another time consuming operation...
And another one, but it completed, so...OKOK
Which is of course unacceptable. I know how to go back in current line, but is there a way to go UP? I'd swear I've seen it somewhere, though it could be a Linux console :)
Forget it. See Far File Manager! It works in Windows console, it works even in PowerShell! How to make something like this? And the coolest part is it restores console state after exiting. So maybe I should ask - how to access console buffer directly? I assume I'll need some native code to do the trick, but maybe there's another way? I thought of clearing console with each update, but this seems like overkill. Or maybe it isn't? Will it blink?
You can move cursor wherever you want: Console.SetCursorPosition or use Console.CursorTop.
Console.SetCursorPosition(0, Console.CursorTop -1);
Console.WriteLine("Over previous line!!!");
Use a carriage return. This sample prints a single line, overwriting what was there before.
Console.WriteLine();
for (int i = 0; i <= 100; i++)
{
System.Threading.Thread.Sleep(10);
Console.Write("\x000DProgress: " + i);
}
This works as long as all your strings are less than 80 columns (or whatever your terminal buffer is set to).
Note: the following answer was originally edited into the question by the OP.
Here's complete solution with demo:
using System;
using System.Collections.Generic;
using System.Threading;
namespace PowerConsole {
internal class Containers {
internal struct Container {
public int Id;
public int X;
public int Y;
public string Content;
}
public static List<Container> Items = new List<Container>();
private static int Identity = 0;
public static int Add(string text) {
var c = new Container();
c.Id = Identity++;
c.X = Console.CursorLeft;
c.Y = Console.CursorTop;
c.Content = text;
Console.Write(text);
Items.Add(c);
return c.Id;
}
public static void Remove(int id) {
Items.RemoveAt(id);
}
public static void Replace(int id, string text) {
int x = Console.CursorLeft, y = Console.CursorTop;
Container c = Items[id];
Console.MoveBufferArea(
c.X + c.Content.Length, c.Y,
Console.BufferWidth - c.X - text.Length, 1,
c.X + text.Length, c.Y
);
Console.CursorLeft = c.X;
Console.CursorTop = c.Y;
Console.Write(text);
c.Content = text;
Console.CursorLeft = x;
Console.CursorTop = y;
}
public static void Clear() {
Items.Clear();
Identity = 0;
}
}
internal class Program {
private static List<Thread> Threads = new List<Thread>();
private static void Main(string[] args) {
Console.WriteLine("So we have some threads:\r\n");
int i, id;
Random r = new Random();
for (i = 0; i < 10; i++) {
Console.Write("Starting thread " + i + "...[");
id = Containers.Add("?");
Console.WriteLine("]");
Thread t = new Thread((object data) => {
Thread.Sleep(r.Next(5000) + 100);
Console.ForegroundColor = ConsoleColor.Green;
Containers.Replace((int)data, "DONE");
Console.ResetColor();
});
Threads.Add(t);
}
Console.WriteLine("\n\"But will it blend?\"...");
Console.ReadKey(true);
i = 0;
Threads.ForEach(t => t.Start(i++));
Threads.ForEach(t => t.Join());
Console.WriteLine("\r\nVoila.");
Console.ReadKey(true);
}
}
}
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.
I want to know if it is possible to get back to the last line when I'm at the beginning of the next line? (in C# Console, of course)
I mean Console.WriteLine() cause going to the next line and I want to stay in my line even after pressing enter. (And I think there isn't another way to ReadLine without going to the next line , is there?)
I found that Console.SetCursorPosition() can be useful, like below:
int x, y;
Console.WriteLine("Please enter the point's coordinates in this form (x,y):");
Console.Write("(");
x = Convert.ToInt32(Console.ReadLine());
Console.SetCursorPosition(x.ToString().Length + 1, Console.CursorTop - 1);
Console.Write(",");
y = Convert.ToInt32(Console.ReadLine());
Console.SetCursorPosition(x.ToString().Length + y.ToString().Length + 2, Console.CursorTop - 1);
Console.WriteLine(")");
This seems to work fine but when I try to change Console.Write("(");
into something like Console.Write("Point A=("), I need to change the the Console.SetCursorPosition() arguments every time.
Also it would be very helpful if I could move the cursor to the last character (except spaces) in the console buffer.(I think it would be easy if I could copy a specific line from console into a string.)
Thanks in advance.
How about using a simple helper class that fits your specific use case and helps make your code logic a bit more readable.
public class Prompt
{
public struct CursorPosition
{
public int CursorLeft;
public int CursorTop;
}
private CursorPosition _savedPosition;
public Prompt Write(string prompt)
{
Console.Write(prompt);
return this;
}
public Prompt Write(string promptFormat, params object[] args)
{
return Write(string.Format(promptFormat, args));
}
public Prompt WriteLine(string prompt)
{
Write(prompt);
Console.WriteLine();
return this;
}
public Prompt WriteLine(string promptFormat, params object[] args)
{
return WriteLine(string.Format(promptFormat, args));
}
public string ReadLine(bool advanceCursorOnSameLine = false, bool eraseLine = false)
{
if (advanceCursorOnSameLine || eraseLine)
{
SavePosition();
if (eraseLine)
WriteLine(new string(' ', Console.WindowWidth - _savedPosition.CursorLeft)).RestorePosition();
}
var input = Console.ReadLine();
if (advanceCursorOnSameLine)
RestorePosition(input.Length);
return input;
}
public Prompt SavePosition()
{
_savedPosition = GetCursorPosition();
return this;
}
public CursorPosition GetCursorPosition()
{
return new CursorPosition {
CursorLeft = Console.CursorLeft,
CursorTop = Console.CursorTop
};
}
public Prompt RestorePosition(CursorPosition position, int deltaLeft = 0, int deltaTop = 0)
{
var left = Math.Min(Console.BufferWidth - 1, Math.Max(0, position.CursorLeft + deltaLeft));
var right = Math.Min(Console.BufferHeight - 1, Math.Max(0, position.CursorTop + deltaTop));
Console.SetCursorPosition(left, right);
return this;
}
public Prompt RestorePosition(int deltaLeft = 0, int deltaTop = 0)
{
return RestorePosition(_savedPosition, deltaLeft, deltaTop);
}
}
Which can then be used like this:
class Program
{
public static void Main(params string[] args)
{
int x, y;
var prompt = new Prompt();
prompt.WriteLine("Please enter the point's coordinates in this form (x,y):");
var savedPos = prompt.GetCursorPosition();
while (true)
{
x = Convert.ToInt32(prompt.Write("(").ReadLine(true, true));
y = Convert.ToInt32(prompt.Write(",").ReadLine(true));
prompt.WriteLine(")");
// do something with x and y
var again = prompt.Write("More (Y):").ReadLine(true, true);
if (!again.StartsWith("Y", StringComparison.OrdinalIgnoreCase))
break;
prompt.RestorePosition(savedPos);
}
}
}
I'd like to achieve something like this:
Time consuming operation...OK
Another time consuming operation...
And another one, but it completed, so...OK
I displayed 3 line of text, each one related with a thread which can end sooner or later. But if the second one complete later than the third one, I'll get something like this:
Time consuming operation...OK
Another time consuming operation...
And another one, but it completed, so...OKOK
Which is of course unacceptable. I know how to go back in current line, but is there a way to go UP? I'd swear I've seen it somewhere, though it could be a Linux console :)
Forget it. See Far File Manager! It works in Windows console, it works even in PowerShell! How to make something like this? And the coolest part is it restores console state after exiting. So maybe I should ask - how to access console buffer directly? I assume I'll need some native code to do the trick, but maybe there's another way? I thought of clearing console with each update, but this seems like overkill. Or maybe it isn't? Will it blink?
You can move cursor wherever you want: Console.SetCursorPosition or use Console.CursorTop.
Console.SetCursorPosition(0, Console.CursorTop -1);
Console.WriteLine("Over previous line!!!");
Use a carriage return. This sample prints a single line, overwriting what was there before.
Console.WriteLine();
for (int i = 0; i <= 100; i++)
{
System.Threading.Thread.Sleep(10);
Console.Write("\x000DProgress: " + i);
}
This works as long as all your strings are less than 80 columns (or whatever your terminal buffer is set to).
Note: the following answer was originally edited into the question by the OP.
Here's complete solution with demo:
using System;
using System.Collections.Generic;
using System.Threading;
namespace PowerConsole {
internal class Containers {
internal struct Container {
public int Id;
public int X;
public int Y;
public string Content;
}
public static List<Container> Items = new List<Container>();
private static int Identity = 0;
public static int Add(string text) {
var c = new Container();
c.Id = Identity++;
c.X = Console.CursorLeft;
c.Y = Console.CursorTop;
c.Content = text;
Console.Write(text);
Items.Add(c);
return c.Id;
}
public static void Remove(int id) {
Items.RemoveAt(id);
}
public static void Replace(int id, string text) {
int x = Console.CursorLeft, y = Console.CursorTop;
Container c = Items[id];
Console.MoveBufferArea(
c.X + c.Content.Length, c.Y,
Console.BufferWidth - c.X - text.Length, 1,
c.X + text.Length, c.Y
);
Console.CursorLeft = c.X;
Console.CursorTop = c.Y;
Console.Write(text);
c.Content = text;
Console.CursorLeft = x;
Console.CursorTop = y;
}
public static void Clear() {
Items.Clear();
Identity = 0;
}
}
internal class Program {
private static List<Thread> Threads = new List<Thread>();
private static void Main(string[] args) {
Console.WriteLine("So we have some threads:\r\n");
int i, id;
Random r = new Random();
for (i = 0; i < 10; i++) {
Console.Write("Starting thread " + i + "...[");
id = Containers.Add("?");
Console.WriteLine("]");
Thread t = new Thread((object data) => {
Thread.Sleep(r.Next(5000) + 100);
Console.ForegroundColor = ConsoleColor.Green;
Containers.Replace((int)data, "DONE");
Console.ResetColor();
});
Threads.Add(t);
}
Console.WriteLine("\n\"But will it blend?\"...");
Console.ReadKey(true);
i = 0;
Threads.ForEach(t => t.Start(i++));
Threads.ForEach(t => t.Join());
Console.WriteLine("\r\nVoila.");
Console.ReadKey(true);
}
}
}