C# Generate Odd and Even Numbers

This is a simple C# program to generate even numbers and odd numbers up to a limit.
Here a text box will accept a number as limit to generate even numbers or odd numbers. If you click on ‘Even numbers’ button, list box will show even numbers up to given limit. If you click on ‘Odd numbers’ button, list box will display odd numbers up to given limit.



Interface with Example Input – Output:

C# Generate Odd and Even Numbers

Code behind interface:


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 Odd_and_even_numbers
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       private void button1_Click(object sender, EventArgs e)
        {
            try
             {
                 listBox1.Items.Clear();
                 int limit = Convert.ToInt32(textBox1.Text);
                 for (int i = 1; i <= limit; i = i + 2)
                 {
                     listBox1.Items.Add(i).ToString();
                 }
            }
            catch (Exception)
            {
                MessageBox.Show("Invalid Limit");
            }
        }

       private void button2_Click(object sender, EventArgs e)
       {
           try
            {
               listBox1.Items.Clear();
               int limit = Convert.ToInt32(textBox1.Text);
               for (int i = 2; i <= limit; i = i + 2)
                 {
                   listBox1.Items.Add(i).ToString();
                 }
            }
           catch (Exception)
           {
               MessageBox.Show("Invalid Limit");
           }
       }

    }
}




No comments:

Post a Comment