Algoritma Soruları ve Çözümleri - 5


Aşağıdaki kurallara göre sayı dizileri elde edilecektir.
n-> n/2 (Eğer n, çift ise)
n-> 3n+1 (Eğer n, tek ise)
Örnek olarak: 13 sayısını bu kurala uyguladığımızda
13->40->20->10->5->16->8->4->2->1 Dizilimini elde ediliyor.
Buna göre klavyeden girilen bir sayı için oluşacak diziyi listbox ta gösteren program nasıl olacak onu paylaşacağım.

Çözüm: Projemize 1 adet textbox 1 adet button 1 adette listbox ekleyelim ve button click eventine kodlarımızı yazalım.

 private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                label1.Text = "Lütfen değer giriniz.";
            }
            else
            {
                listBox1.Items.Clear();
                int _deger = int.Parse(textBox1.Text);
                int _sayi = 0;
                bastaraf:

                if (_sayi == 0)
                {
                    if (_deger % 2 == 0)
                    {
                        int _sonuc = _deger / 2;
                        listBox1.Items.Add("Çift -" + _sonuc.ToString());
                        _sayi = _sonuc;
                        goto bastaraf;
                    }
                    else
                    {
                        int _sonuc = (_deger * 3) + 1;
                        listBox1.Items.Add("Tek -" + _sonuc.ToString());
                        _sayi = _sonuc;

                        goto bastaraf;

                    }
                }
                else if (_sayi != 1)
                {
                    if (_sayi % 2 == 0)
                    {
                        int _sonuc = _sayi / 2;
                        listBox1.Items.Add("Çift -" + _sonuc.ToString());

                        _sayi = _sonuc;
                        goto bastaraf;
                    }
                    else if (_sayi == 1)
                    {
                        listBox1.Items.Add("Bitti");

                    }
                    else
                    {
                        int _sonuc = (_sayi * 3) + 1;
                        listBox1.Items.Add("Tek -" + _sonuc.ToString());
                        _sayi = _sonuc;

                        goto bastaraf;

                    }
                }
            }

Yorumlar

Bu blogdaki popüler yayınlar

Asp.Net ile Uyarı Mesajları Vermek (msgbox)

Asp.Net Eval Kullanımı

Asp.Net ile T.C. Kimlik Doğrulama (Mernis) Web Service ile