Wednesday

Qt C++: Programming Fundamental Concepts: if-else statement

Program title: if-else statement

C++ Code:

#include <QApplication> 

#include <QDebug>
#include <QMainWindow> //QMainWindow *window
#include <QLabel>
#include <QHBoxLayout> //layout->addWidget(label)
#include <QWidget> //centralWidget->setLayout(layout)
#include <QInputDialog>
#include <QString>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QMainWindow *window = new QMainWindow();

    QLabel *label = new QLabel("No Result");

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(label);

    QWidget *centralWidget = new QWidget(window); //centralWidget parent is the window
    centralWidget->setLayout(layout);

    window->setCentralWidget(centralWidget);
    window->setWindowTitle("My Main Window");
    window->resize(400, 400);
    window->show();

    int n = QInputDialog::getInt(window, "Input Dialog",
                                 "Enter a percentage", 25, //25 is the default value
                                 0, 100, 1); //min, max, step

    if(n>=50) {
        qDebug() << "Percentage is greater than or equal to fifty";
        QString s = "Percentage is greater than or equal to fifty";        
        label->setText(s);
    }
    else {
        qDebug() << "Percentage is less than fifty";
        QString s = "Percentage is less than fifty";
        label->setText(s);
    }

    return app.exec();
} 

Program Output: Vertical Toolbar > Run 

Advantages:
-- input dialog: built-in spin box for integer input
-- input dialog: can set default value
-- input dialog: built-in regular expression and input validation
-- input dialog: prevent input error

No comments:

Measure execution time with Julia, example using sorting algorithms

# random integers between 1 and 100 inclusive, generate thousands of them x = rand ( 1 : 100 , 100000 ) @time sort (x; alg=InsertionSort, r...