Development of a program for calculating the sum of negative elements of an array.

Development of a program for calculating the sum of negative elements of an array. Demonstration of using methods and properties of the DataGridView control


Contents


Task

An array of n numbers of type double (n = 1..10) is given. Develop a program that finds the sum of the negative items of this array. The program must be implemented as a Windows application created using the Windows Forms Application template. The program should provide for:

  • input the value n (array dimension);
  • input of values of the array items;
  • output of the result in a separate form.

Data input and output of the result should be performed in several stages according to the model of the master.

 

Instruction

1. Run MS Visual Studio. Create an application using the Windows Forms Application template. Save the project

After downloading Microsoft Visual Studio, you need to run the following command sequence to create an application using the Windows Forms Application template:

File -> New -> Project...

As a result, the ‘New Project’ window opens (Figure 1).

Figure 1. Creating a new project. Selecting a template, setting the location and name of the project

In the window that opens, select the template:

Visual C++ - Windows Forms Applicaiton

In the “Location:” field, specify the folder where the application will be located (“Browse …” button). In the field “Name:” specify the name of the application.

In our case, the application is named MyApp01 and is located in the following folder

C:\Programs\CPP

A more detailed example of creating an application using the Windows Forms Application template is described in the topic:

As a result of the performed actions, a new project will be created. The form whose main code is described in the file “Form1.h” corresponds to the project. Figure 2 shows the general view of the application at the moment.

Figure 2. Empty form of the application (program)

 

2. Development of the main form Form1 of the application

2.1. Placement of controls on the form Form1

Use the ToolBox toolbar from the “Common Controls” tab to place the following controls on the form as shown in Figure 3:

  • two controls of Button type. As a result, two objects (variables) with the names button1, button2 will be created. Using these names, you can have access to methods and properties of the corresponding controls;
  • one control of Label type. This will create an object (variable) named label1.

Also, you need to correct the size of the Form1.

Figure 3. Controls Button and Label

2.2. Configuring controls

To configure a property in some control that is placed on the form, you must first select this control (or form), and then change the values of this property in the Properties window (Figure 4).

Figure 4. The ‘Properties’ window for the button1 control

Configure the following properties of the controls:

  • in the Form1 control (main form of application), property Text = “Sum of negative items”;
  • in Form1, property StartPosition = “CenterScreen”;
  • in button1, property Text = “Exit”;
  • in button2, property Text = “Calculation”;
  • in label1, property Text = “Sum of the negative items of the array”.

After setting of controls the application form will look as shown in Figure 5.

Figure 5. The main form of application after configuring controls

 

3. Development of Form2 application form for setting the value n

3.1. Add a new form to application

The value n is entered in a new form. To create a new form, you need to call the command in the main menu

Project -> Add New Item...

Figure 6. The command to add a new element to the program

This will open the “Add New Item – MyApp01” window (Figure 7). In this window, in the list of existing templates, select “Windows Form”.

In the Name field, you must specify the name of the Form2 form. This is the name of the form object (variable). With this name, you can programmatically control the form.

Figure 7. The new form creating window

After the performed actions, a new form will be created, which corresponds to the file “Form2.h”.

 

3.2. Designing the Form2 form of inputting the value n
3.2.1. Placement of controls on the form

In form Form2, you can enter the value of n (the number of items in the array). In order to make an input, you need to use a TextBox control, which is a field for entering strings.

From the Common Controls tab of the ToolBox toolbar, you need to place the following controls on the form:

  • the control of Label type. An object with the name label1 is created;
  • two controls of Button type. Two objects with names button1 and button2 are created;
  • the control of TextBox type. This control is a field for entering a string. The object with name textBox1 is created.

After placement, the Form2 form window will have a view, as shown in Figure 8.

Figure 8. The Form2 form window after the placement of controls and correcting of form size

 

3.2.2. Configuring controls

Configure the following properties of the controls:

  • in the Form2 control, property Text = “Input n”;
  • in Form2, property StartPosition = “CenterScreen”;
  • in Form2, property FormBorderStyle = “FixedDialog”;
  • in Form2, property ControlBox = false;
  • in button1, property Text = “<<“;
  • in button1, property DialogResult = Cancel. This means that when the button1 is clicked, the form window with the ‘Cancel’ return code will close;
  • in button2, property Text = “>>”;
  • in button2, property DialogResult = OK (the return code of the form is ‘OK’);
  • in label1, property Text = “n = “;
  • in textBox1, property Modifiers = public. This means that the control becomes visible from the outside, from other forms. Thus, you can access this control from the main form of Form1 (as will be shown later).

After setting up, Form2 form window looks as shown in Figure 9.

Figure 9. The Form2 form window after setting up the controls

 

4. Developing the ‘Form3’ form of application to input array

4.1. Creating (adding to the application) Form3

The Form3 form is created in the same way as described in p. 3.1. In the form adding window, you need to specify the name of the Form3 form.

 

4.2. Designing the Form3 form
4.2.1. Placement of controls on the form. The DataGridView control

In the Form3 form, an array of double numbers must be entered. The size of the array was specified in the previous Form2 form. To enter data in array, the DataGridView control is well suited. This control is placed in the “All Windows Forms” or “Data” tabs (Figure 10). This control allows you to receive data in the form of a two-dimensional table. Data can be retrieved from the keyboard, database, collection, array. Table DataGridView has fixed and non-fixed columns (Columns) and rows (Rows).

Figure 10. The DataGridView control in the Data tab

Place the following controls on the form:

  • a DataGridView control. Automatically an object called dataGridView1 is created;
  • control of Label type (label1);
  • two controls of Button type. Two objects with names button1, button2 are created.

After placement of controls, the Form3 form will look like as shown in Figure 11.

Figure 11. The Form3 form

 

4.2.2. Setting up of Form3 form controls

You need to configure the following controls:

  • in button1 property Text = “<<“;
  • in button1 property DialogResult = Cancel;
  • in button2 property Text = “>>”;
  • in button2 property DialogResult = OK;
  • in Form3 property Text = “Array Input”;
  • in Form3 property StartPosition = “CenterScreen”;
  • in Form3 property FormBorderStyle = “FixedDialog”;
  • in dataGridView1 property Modifiers = Public. The dataGridView1 control becomes visible from other modules;
  • in label1 property Text = “Input an array”.

After configuring the controls, the form has the form as shown in Figure 12.

Figure 12. The Form3 form after designing

 

5. Developing the Form4 application form to output the result

In the Form4 the result is displayed. The Form4 form is added in exactly the same way as Form2, Form3 (see p. 3, 4). You need to set the name of form class to Form4.

The Form4 form contains the following controls:

  • the control of Label type. The object named label1 is created;
  • the control of Button type. The object named button1 is created.

The following control properties are set:

  • in the Form4 control, property Text = “Result”;
  • in the Form4, property StartPosition = “CenterScreen”;
  • in Form4, property FormBorderStyle = “FixedDialog”;
  • in Form4, property ControlBox = false;
  • in button1 property Text = “OK”;
  • in button1 property DialogResult = OK;
  • in label1 property Modifiers = Public. The label1 control becomes visible from other modules, including the main form Form1.

There is no need to change the Text property of the label1 control, since this property outputs the result and will be generated programmatically from the main Form1 form.

After the performed actions, the Form4 form window is as follows (Figure 13).

Figure 13. The Form4 form after designing

 

6. The text of the file “Form1.h” corresponding to the main form Form1

At the moment, the text of file that corresponds to the main module of the form as follows:

#pragma once

namespace MyApp01 {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for Form1
    /// </summary>

    public ref class Form1 : public System::Windows::Forms::Form
    {
        public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

        protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }

        private: System::Windows::Forms::Button^ button1;
        protected:
        private: System::Windows::Forms::Label^ label1;
        private: System::Windows::Forms::Button^ button2;

        private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>

        void InitializeComponent(void)
        {
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->button2 = (gcnew System::Windows::Forms::Button());
            this->SuspendLayout();

            //
            // button1
            //
            this->button1->Location = System::Drawing::Point(15, 91);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(75, 23);
            this->button1->TabIndex = 0;
            this->button1->Text = L"Exit";
            this->button1->UseVisualStyleBackColor = true;

            //
            // label1
            //
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(12, 39);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(177, 13);
            this->label1->TabIndex = 1;
            this->label1->Text = L"The sum of negative items of the array";

            //
            // button2
            //
            this->button2->Location = System::Drawing::Point(131, 91);
            this->button2->Name = L"button2";
            this->button2->Size = System::Drawing::Size(75, 23);
            this->button2->TabIndex = 2;
            this->button2->Text = L"Calculation";
            this->button2->UseVisualStyleBackColor = true;
            this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);

            //
            // Form1
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(270, 169);
            this->Controls->Add(this->button2);
            this->Controls->Add(this->label1);
            this->Controls->Add(this->button1);
            this->Name = L"Form1";
            this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
            this->Text = L"The sum of negative items";
            this->ResumeLayout(false);
            this->PerformLayout();
        }

#pragma endregion

    };
}

 

7. Writing a program code of interaction between forms and calculation

After designing all forms, there remains the last “easiest” stage – writing the program code that solves this task.

The entire calculation process is performed in the module “Form1.h”, which corresponds to the main form of the program. All three Form2, Form3, Form4 forms are called from this form sequentially. The value of the properties of some controls of these forms is formed programmatically. Therefore, when designing Form2, Form3, Form4, for some controls, the Modifiers property was set to Public.

 

7.1. Connecting secondary forms to the main form

Since, from the main form, additional forms will be called sequentially, at the very beginning of the main form file “Form1.h” you need to add the following lines:

#include "Form2.h"
#include "Form3.h"
#include "Form4.h"

After that, there is programmatic access to the classes Form2, Form3, Form4, which correspond to the created forms.

 

7.2. Programming the event handler for the process of calculating

At this stage, you need to program a click on the “Calculation” button of the main form Form1. Accordingly, the system will generate an OnClick event, for which a method is created to handle this event (event handler). In this method, you need to write the entire calculation code in accordance with the condition of the task.

A detailed example of programming the click event on a button is given in the topic:

Without going into the details of the solution of the task (finding the sum of array elements), the text of the event handler has the following form:

private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
    // the event handler of click on the "Calculation" button
    Form2 f2; // declare an object of type Form2
    Form3 f3; // declare an object of type Form3
    Form4 f4;

    double A[10]; // array of numbers
    int n; // number of items in the array

    // the Form2 calling with OK check
    if (f2.ShowDialog()== System::Windows::Forms::DialogResult::OK)
    {
        // if in the form Form2 selected ">>"
        // 1. Check if a value is entered in f2.textBox1-> Text
        if (f2.textBox1->Text=="") return;

        // 2. Get the value of n
        n = System::Int32::Parse(f2.textBox1->Text);

        // 3. Form the dataGridView1 in Form3
        // 3.1. Add a column named "column" with no title ("")
        f3.dataGridView1->Columns->Add("column","");

        // 3.2. Add rows. Number of rows = n
        for (int i=0; i<n; i++)
            f3.dataGridView1->Rows->Add(""); // adding blank lines

        // 4. Calling the Form3 form of entering an array
        System::Windows::Forms::DialogResult DR; // return variable from form

        // Call the form and read the result of the return of DR (OK or Cancel)
        DR = f3.ShowDialog();

        if (DR == System::Windows::Forms::DialogResult::OK) // check for OK
        {
            // if the result is OK, then we continue to calculate
            String ^s; // additional variable - string with dataGridView1

            // 5. Check if all fields are filled in dataGridView1
            for (int i=0; i<n; i++)
            {
                // take a string with dataGridView1
                s = f3.dataGridView1->Rows[i]->Cells[0]->Value->ToString();
                if (s == "") return; // checking whether the string is empty
            }

            // 6. Convert the value of rows from dataGridView1 to an array of numbers A
            for (int i=0; i<n; i++)
            {
                s = f3.dataGridView1->Rows[i]->Cells[0]->Value->ToString(); // get a string
                A[i] = System::Double::Parse(s);
            }

            // 7. Calculating the sum
            double sum = 0; // result - sum
            for (int i=0; i<n; i++)
                if (A[i]<0)
                    sum += A[i];

            // 8. Display the result in the Form4 form
            f4.label1->Text = "The sum of the negative elements of array = " + sum.ToString();
            f4.ShowDialog();
        }
    }
}

Let’s explain some code snippets. At the beginning of the method, three variables f2, f3, f4 corresponding to Form2, Form3, Form4 are declared.

Calling any form is done using the ShowDialog() method. For example, for Form2, the call is as follows:

f2.ShowDialog();

The form after the call returns the result. In our case, for example, the form Form2 returns the result OK or Cancel (the DialogResult property of the buttons1, button2 buttons of the form). The list of all possible return results from the form is described in the enum

System::Windows::Forms:DialogResult

To convert a string value to a numeric value (int or double), use the Parse() method, which is invoked in different classes (Int32, Double)

System::Int32::Parse(s)
System::Double::Parse(s)

where s is the string to be converted to a numeric value. For example “234” => 234

To add a row to dataGridView1, use the Add() method.

To get the value of a given cell, use the code

f3.dataGridView1->Rows[i]->Cells[0]->Value->ToString()

where

  • i – the number of row in the dataGridView1;
  • 0 – column number. In our case, we have only 1 column, which is numbered from zero. The value of the cell is placed in the Value property.

 

7.3. Programming the event handler of the output from the program

To exit the program by clicking on the “Exit” button, you need to use the Close() method. The text of the click event handler on the “Exit” button is the following

private:
System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
    // the "Exit" command
    Close();
}

 

8. The text of Form1.h module

In the shortened (general) form, the text of the module Form1.h has the form (the implementation of the methods of the class Form1 is omitted)

#include "Form2.h"
#include "Form3.h"
#include "Form4.h"

#pragma once

namespace MyApp01 {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for Form1
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
        public:
        Form1(void)
        {
            ...
        }

        protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            ...
        }

        private: System::Windows::Forms::Button^ button1;
        protected:
        private: System::Windows::Forms::Label^ label1;
        private: System::Windows::Forms::Button^ button2;

        private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            ...
        }

#pragma endregion

        private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
        {
            // the event handler of click on the "Calculation" button
            ...
        }

        private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
        {
            // the "Exit" command
            ...
        }
    };
}

 

9. Run the program

After the performed actions, you can run the program and test it.

 


Related topics