P
P
P_Zeger2013-11-18 23:42:23
C++ / C#
P_Zeger, 2013-11-18 23:42:23

Why is there an error in if loop in C# code?

Good afternoon/evening!
I recently started learning C# on my own using Head first C# 3d Ed. In one of the tasks, it was necessary to select sections of code and insert them into the program code instead of spaces. I made a mistake in the second if loop with a condition and I don't understand why the answer is x>0. I would be glad if someone could explain. Below is the solution to the problem.
Thanks in advance!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PoolPuzzle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string result = "";
            Echo e1 = new Echo();
            Echo e2 = new Echo(); // Bonus answer: Echo e2 = e1;
            int x = 0;
            while (x < 4)
            {
                result = result + e1.Hello() + "\n";
                e1.count = e1.count + 1;
                if (x == 3) // Alternate solution: x == 4
                {
                    e2.count = e2.count + 1;
                }
                if (x > 0) // Alternate solution: x < 4
                {
                    e2.count = e2.count + e1.count;
                }
                x = x + 1;
            }
            MessageBox.Show(result + "Count: " + e2.count);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
P_Zeger, 2013-11-19
@P_Zeger

The window prints out four "hellooooo..." lines and counts the number of attempts (response: 10).
The number of attempts in the alternative solution is 24 because the second object is a reflection of the first (if I understood correctly).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question