Doing Factorial in C# for Windows Application
Here, an example is shown how to implement factorial code in C# for the Windows application.
First, you need to use Design to set up form like this (how to set up components, like button or text box, are not shown).
Recursion Class is shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Recursion
{
class Factorial
{
public
Factorial()
{
}
public
int fact(int
n)
{
if
(n == 0)
{
return
1; //base
case
}
else
{
return
n * fact(n - 1);
}
}
}
}
|
The GUI part is shown below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Recursion
{
public partial class txbFactInput : Form
{
public
txbFactInput()
{
InitializeComponent();
}
private
void button1_Click(object
sender, EventArgs e)
{
//MessageBox.Show("testing");
//int n
= Convert.ToInt16(txtb1.Text);
//
Using TryParse, test if an integer was entered
int
n;
if
(int.TryParse(txtb1.Text, out n))
{
//
Integer was put in test box
txtb1.Text = null;
//clear text box
Factorial
t = new Factorial(); //create
Factorial object
lblAnswer.Text =
t.fact(n).ToString(); //answer here
}
else
{
//
Error
lblAnswer.Text = "Error! Input an integer";
}
}
}
}
|
The form in Windows Application
No comments:
Post a Comment