View Poll Results: Who do you think is the best beginner?

Voters
19. You may not vote on this poll
Page 5 of 22 FirstFirst ... 3456715 ... LastLast
Results 41 to 50 of 217

Thread: [Beginner] Programming Challenge: 2

  1. #41
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: [Beginner] Programming Challenge: 2

    I see nobody has tried C yet...

    Question to our host, LaRoza:
    Are we allowed to use external libs? Or would be too advanced for a "beginner"?

  2. #42
    Join Date
    May 2006
    Beans
    562
    Distro
    Ubuntu Development Release

    Re: [Beginner] Programming Challenge: 2

    My version in C/C++ (First time using C/C++):
    PHP Code:
    #include <iostream>
    #include <string>
    #include <cstring>

    using namespace std;

    bool no_character(string input)
    {
        for (
    unsigned int i=0input.size(); i++)
            {
                if(
    isalpha(input[i]))
                    return 
    false;
            }
        return 
    true;
    }

    int main()
    {
        
    string input;
        
    string name;
        
    int age;
        
    int usrid;

        
    cout << "Welcome to Shae's solution to Programming Challenge 2." << endl;
        
    cout << "Type exit and press enter to close this program." << endl;

        
    // While loop to take the input for the name
        
    while(1)
        {
            
    cout << "Please type your forum name and press enter: ";
            
    getline (cininput'\n');

            if (
    input == "exit")
                return 
    0;
            else if (
    input.size() == 0)
                
    cout << "Your forum name cannot be blank, please try again." << endl;
            else if (
    input[0] == ' ')
                
    cout << "Your forum name cannot start with a space, please try again." << endl;
            else if (
    no_character(input))
                
    cout << "Your forum name must contain a non-numerical character, please try again." << endl;
            else
            {
                
    name input;
                break;
            }
        }

        
    // While loop to take the input for the age
        
    while(1)
        {
            
    cout << "Please type your age and press enter: ";
            
    getline (cininput'\n');
            
    age atoi(input.c_str());

            if (
    input == "exit")
                return 
    0;
            else if (
    input.size() == 0)
                
    cout << "Your age cannot be blank, please try again." << endl;
            else if (
    input[0] == ' ')
                
    cout << "Your age cannot start with a space, please try again." << endl;
            else if (
    age || age 120)
                
    cout << "Your age cannot be less than 1, greater than 120, and must be a number, please try again." << endl;
            else
                break;
        }

        
    // While loop to take the input for the user id
        
    while(1)
        {
            
    cout << "Please type your user id and press enter: ";
            
    getline (cininput'\n');
            
    usrid atoi(input.c_str());

            if (
    input == "exit")
                return 
    0;
            else if (
    input.size() == 0)
                
    cout << "Your user id cannot be blank, please try again." << endl;
            else if (
    input[0] == ' ')
                
    cout << "Your user id cannot start with a space, please try again." << endl;
            else if (
    usrid || usrid 999999)
                
    cout << "Your user id cannot be less than 1, greater than 999999, and must be a number, please try again." << endl;
            else
                break;
        }

        
    cout << "You are " << name << ", aged " << age << " next year you will be " << age << ", with user id " << usrid << ", the next user is " << usrid << "." << endl;
        return 
    0;

    Last edited by shae; August 6th, 2008 at 10:41 PM. Reason: Added checking if the forum name contains no characters

  3. #43
    Join Date
    Jul 2008
    Beans
    1,706

    Re: [Beginner] Programming Challenge: 2

    Quote Originally Posted by LaRoza View Post

    You can have one made with a GUI. It has to be free, and let me know what I need to compile it though. Packages should be in Ubuntu repos.
    are there any C++/C# IDE's in the repos that allow you to use a GUI to position the components then you just have to add your code to tell them what to do

  4. #44
    Join Date
    Jun 2008
    Beans
    204
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: [Beginner] Programming Challenge: 2

    Ok found it - ignore my comment in the other thread!
    Ill hopefully be posting a tested (this time) Fortran90 program soon

    Good luck everyone

    Tom

  5. #45
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: [Beginner] Programming Challenge: 2

    C / GTK+

    Ha, you didn't expect this. Actually, it's kinda cheating, because the high-level data types GLib offers like GString are designed to avoid the usual string problems that were the challenge's goal; so I wouldn't mind if I'm disqualified. But I hope it can be useful for someone, so I also GPL it and post it...

    EDIT: Forgot to mention that, as a consequence of using GTK+, this one supports UTF-8.

    You need the GTK+ libraries (for those using KDE. GNOME & Xfce users already have it installed) and the GTK+ development packages (libgtk2.0-0 and libgtk2.0-dev).

    Compile with:
    Code:
    gcc -o challenge challenge.c -Wall `pkg-config --cflags --libs gtk+-2.0`
    Here, the winner code:
    UPDATES:
    1) I decided to comment the code so anyone who's curious can see what I'm doing and why.
    2) Fixed parsing conditions. Previous version didn't handle negative values correctly.
    3) Fixed bug in parsing. It accepted null input as username.
    4) A cosmetic change that allows the main button to use the user's native locale.
    PHP Code:
    /* challenge.c - UF Beginner Challenge #2
     *
     * Copyright (C) 2008 Eugenio M. Vigo (aka "nvteighen")
     *
     * This program is free software: you can redistribute it and/or modify it under
     * the terms of the GNU General Public License as published by the Free Software
     * Foundation, either version 3 of the License, or (at your option) any later
     * version.
     *
     * This program is distributed in the hope that it will be useful, but WITHOUT 
     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
     * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 
     * details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>. */

    #include <string.h> /* For strlen() */
    #include <stdlib.h> /* For atoi() */
    #include <gtk/gtk.h>

    #define MSG_STRING "You are %s aged %d you will be %d, with user id %d, the next user is %d."

    /** FUNCTION PROTOTYPES:
     ** You should always do this! **/
     
    GtkWidget *my_win(void);
    GtkWidget *my_entry_with_label(const char *);
    void send_cback(GtkWidget *, gpointer *);
    void my_print(GtkWindow *, GString *, GString *, GString *);

    int parse(const char *, const char *, const char *);

    /** INTERFACE FUNCTIONS:
     ** These functions below are responsible of creating the user interface. 
     ** Nothing of the real implementation (data processing) is done here in order 
     ** to show how you can (and should) divide a program into the "stage" (what the 
     ** user sees) and the "backstage" (what the program does). Usually, this 
     ** division would imply to have more than one source file, but as this is a
     ** rather trivial program (compared to major projects like Nautilus), let's
     ** do all in the same file. **/

    GtkWidget *my_win(void)
    {
        
    /* Constructor for the main window. All settings for it are set here and 
         * nowhere else.
         *
         * RET: A pointer to the window widget. */

        
    GtkWidget *Window gtk_window_new(GTK_WINDOW_TOPLEVEL);
        
    gtk_window_set_default_size(GTK_WINDOW(Window), 400300);
        
    gtk_window_set_title(GTK_WINDOW(Window), 
            
    "Beginner Programming Challenge 2");
        
        
    gtk_container_set_border_width(GTK_CONTAINER(Window), 23); 
        
        
    /* Assigning callback to the "delete_event" (user closing window). */
        
    g_signal_connect(G_OBJECT(Window), "delete_event"gtk_main_quitNULL);
        
        return 
    Window;
    }

    GtkWidget *my_entry_with_label(const char *label)
    {
        
    /* Constructor for text entries; it takes a string as argument for label.
         *
         * RET: A pointer to the new text entry. */
        
        
    GtkWidget *NewEntry gtk_entry_new();
        
    gtk_entry_set_text(GTK_ENTRY(NewEntry), label);
        
        return 
    NewEntry;
    }

    void send_cback(GtkWidget *Sendgpointer *data)
    {
        
    /* What's this? GTK+ works using callbacks, a sort of wrapper activated by
         * an event that prepares the data for further processing. All callbacks
         * have the same argument structure: first argument is the widget and then,
         * a gpointer to the data, in this case, a gpointer to a gpointer (i.e an 
         * array of gpointers... isn't C great?). 
         *
         * RET: (void). */

        /* We take advantage of GLib's GString data type to store the user's input.
         * The input is taken from the entries, whose addresses are stored in the
         * data array indices 0-2. */
        
    GString *ForumName g_string_new(gtk_entry_get_text(GTK_ENTRY(data[0])));
        
    GString *Age g_string_new(gtk_entry_get_text(GTK_ENTRY(data[1])));
        
    GString *ForumID g_string_new(gtk_entry_get_text(GTK_ENTRY(data[2])));
        
        
    /* The GString data type allows direct access to the string from the 'str'
         * data member. */
        
    if(parse(ForumName->strAge->strForumID->str) == 0)
        {
            
    /* If all data meets the criteria at parse(), then we can display the
             * sentence. */
            
    my_print(GTK_WINDOW(data[4]), ForumNameAgeForumID);
        }
        else
        {
            
    /* If something failed, we display an error dialog box. */
            
    GtkWidget *Err gtk_message_dialog_new(GTK_WINDOW(data[4]), 
                
    GTK_DIALOG_MODALGTK_MESSAGE_ERRORGTK_BUTTONS_OK
                
    "Are you sure?");
            
            
    /* We have to give the "response" signal (when user presses the button)
             * a result: destroy the dialog box. */
            
    g_signal_connect(G_OBJECT(Err), "response"
                
    G_CALLBACK(gtk_widget_destroy), NULL);
            
            
    /* Show the dialog. gtk_widget_show() could also be used. */
            
    gtk_dialog_run(GTK_DIALOG(Err));
        }
        
        
    /* Free memory allocated for the GStrings. The second argument queries to 
         * also free internal data too. */
        
    g_string_free(ForumNameTRUE);
        
    g_string_free(AgeTRUE);
        
    g_string_free(ForumIDTRUE);
    }

    void my_print(GtkWindow *parentGString *ForumNameGString *Age
        
    GString *ForumID)
    {
        
    /* The display function which outputs the final sentence. The first argument
         * is needed to give the resulting message box a parent window.
         *
         * RET: (void). */
        
    GtkWidget *MsgBox gtk_message_dialog_new(parentGTK_DIALOG_MODAL
            
    GTK_MESSAGE_INFOGTK_BUTTONS_OKMSG_STRINGForumName->str
            
    atoi(Age->str), atoi(Age->str) + 1atoi(ForumID->str), 
            
    atoi(ForumID->str) + 1);
        
        
    /* Define what happens when "response" signal is emitted (destroy the dialog
         * box). */
        
    g_signal_connect(G_OBJECT(MsgBox), "response"
            
    G_CALLBACK(gtk_widget_destroy), MsgBox);
            
        
    /* Show the dialog. */    
        
    gtk_dialog_run(GTK_DIALOG(MsgBox));
    }

    int main(int argcchar **argv)
    {
        
    /* Here we design the main window and give GTK+ the control of the 
         * interface. The command line arguments are needed for GTK+. 
         *
         * RET: always 0. */
        
        /* All GTK+ apps need this. */
        
    gtk_init(&argc, &argv);

        
    /* Creating array that will hold all widgets' memory address. */
        
    gpointer All[5];

        
    /* Create widgets and set them. */
        
    GtkWidget *Window my_win();
        
        
    GtkWidget *ForumName my_entry_with_label("Forum Name");
        
    GtkWidget *Age my_entry_with_label("Age");
        
    GtkWidget *ForumID my_entry_with_label("Forum ID");
        
        
    GtkWidget *Send gtk_button_new_from_stock(GTK_STOCK_OK);
        
    /* Defining what happens if Send is clicked: send_cback() is called and 
         * 'All' serves as data container. */
        
    g_signal_connect(G_OBJECT(Send), "clicked"G_CALLBACK(send_cback), All);
        
        
    /* Assign the memory addresses into the array. */
        
    All[0] = ForumName;
        
    All[1] = Age;
        
    All[2] = ForumID;
        
    All[3] = Send
        
    All[4] = Window;
        
        
    /* Now, let's pack everything into a vertical box. A for-loop is used to 
         * take advantage of our 'All' array, but we have to stop at i = 3 so 
         * 'Window' is not packaged! */
        
    GtkWidget *Box gtk_vbox_new(FALSE10); /* 10 pixels between widgets. */
        
    size_t i;
        for(
    04i++)
            
    gtk_box_pack_start(GTK_BOX(Box), All[i], FALSEFALSE0);
        
        
    /* Now, insert 'Box' into the window. */
        
    gtk_container_add(GTK_CONTAINER(Window), Box);
        
        
    /* And, show all children widgets recursively! */
        
    gtk_widget_show_all(Window);
        
        
    /* Finally, call the GTK+ main loop, which takes care for the signals and
         * all the stuff behind the scenes. This line is needed in all GTK+ apps. */
        
    gtk_main();
        
        return 
    0;
    }

    /** IMPLEMENTATION FUNCTION:
     ** This function is responsible of data crunching and processing and is
     ** absolutely independent from the interface. As you see, only standard types 
     ** are used, so in theory any possible C program should be able to call this, 
     ** no matter what interface it uses, whether GTK+, ncurses or just plain 
     ** command line. **/

    int parse(const char *ForumName, const char *Age, const char *ForumID)
    {
        
    /* This function processes the data according to the criteria given by the
         * challenge.
         *
         * RET: 0 on success. 1 on error. */
         
        
    int parsed_age atoi(Age);
        
    int parsed_ID atoi(ForumID);
        
    int error 0;
        
        
    /* The C standard function atoi() returns 0 if input is not an integer, 
         * otherwise, it returns the converted integer. In this case, we need to 
         * avoid any negative and zero results. Forum ID also requires to be less 
         * than 99999. If one of these conditions fails, error is set to 1. */
        
    if(!((parsed_age 0) && (parsed_ID 0) && (parsed_ID 99999)))
            
    error 1;
        
        if(
    strlen(ForumName) == 0)
            
    error 1;
        
        return 
    error;

    Attached Images Attached Images
    Last edited by nvteighen; August 8th, 2008 at 08:59 PM.

  6. #46
    Join Date
    Jul 2008
    Beans
    1,491

    Re: [Beginner] Programming Challenge: 2

    Requires the CLI version of PHP (written in 5.x; may not work with older versions because of the shorthand for acquiring STDIN):

    PHP Code:
    <?php

        
    echo "A short, mildly inquisitive program written for fun. To quit type 'quit' or 'exit' (without the apostrophes/single quotes).\n";
        
        
    /*
        All the questions & checks in 2 arrays...
        */
        
    $questions=array(
                
    "Could you please give me your Username?",
                
    "I hope you don't mind, but could you also give me your age?",
                
    "May I further ask you to provide me your UID? I promise not to misuse it. ;)"
                
    );
        
    $checks      =array(
                
    '/^\w[\w ]*$/'// This construction ensures no leading whitespace will be allowed, but whitespace itself within the name is...
                
    '/^[1-9]\d?$/'// This construction prevents you from typing ages <= 0
                
    '/^\d{1,6}$/' // This construction prevents anyone from entering negative values [the minus character isn't a digit ;)]
                
    );
        
        function 
    askForInput ($question,$check) {
            
    $valid=false;
            while(
    $valid==false) {
                echo 
    "$question\n> ";
                
    $input=fgets(STDIN); // PHP shorthand
                
    $valid=preg_match($check,$input);
                if(
    preg_match('/^(qu|ex)it$/',$input))
                    
    forceQuit("Okay, I'll quit now.");
            }
            
            return 
    trim($input);
        }
        
        
    $data=array();
        foreach(
    $questions as $num => $question) {
            
    $data[$num]=askForInput($question,$checks[$num]);
            if(
    $num==&& $data[$num]==0)
                
    $data[$num]=askForInput($question,$checks[2]);
        }
        
        function 
    forceQuit ($exit) { die("$exit\n"); }
        
        
    $ouput "You are '".$data[0]."', aged ".$data[1]." and next year you will be ".($data[1]+1).". Your UID is '".$data[2]."', the next user is '".($data[2]+1)."'.\n";
        
        
    forceQuit($ouput);
        
        
    ?>
    Also: does this forum have some kind of spoiler tags? Like [spoil][/spoil] ? For those who don't know: spoiler tags are used to hide, erhm well, 'spoilers'...

    EDIT: @LaRoza: you may want to make the assignment a little more clear regarding the following few constraints:
    1) Are UID's required to be 6 digits long? I assume not as you said they could be anything from 1 thru 99999, still ...
    2) At one point you require people to be able to 'quit' the next time it's 'exit'. Which are the valid killer commands? Both, the former or the latter? (I assumed both.)
    Last edited by Reiger; August 6th, 2008 at 02:38 PM.

  7. #47
    Join Date
    Nov 2006
    Location
    Pennsylvania
    Beans
    423

    Re: [Beginner] Programming Challenge: 2

    can age be a float or only integers??
    Your Ubuntu User number is # 15355

    A must Read for anyone interested in Computer Programming.

  8. #48
    Join Date
    Feb 2008
    Location
    Cape Town, South Africa
    Beans
    Hidden!
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: [Beginner] Programming Challenge: 2

    Quote Originally Posted by Wybiral View Post
    It does for me...
    Firebugs version have been a bit off since the change from 2.* to 3.* at one point at work i had to down grade to 2.0.14 of firefox to get errors to show up on firebug.

    Give him a second chance.

  9. #49
    Join Date
    Feb 2008
    Location
    Cape Town, South Africa
    Beans
    Hidden!
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: [Beginner] Programming Challenge: 2

    Quote Originally Posted by Reiger View Post
    Requires the CLI version of PHP (written in 5.x; may not work with older versions because of the shorthand for acquiring STDIN):

    1) Are UID's required to be 6 digits long? I assume not as you said they could be anything from 1 thru 99999, still ...
    is 0000002 a valid forum Id? and is it different to 2

  10. #50
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Beginner] Programming Challenge: 2

    Quote Originally Posted by nvteighen View Post
    I see nobody has tried C yet...

    Question to our host, LaRoza:
    Are we allowed to use external libs? Or would be too advanced for a "beginner"?
    You can, although I would appreciate having instructions on what I need to do to get it to work.

    Quote Originally Posted by shae View Post
    My version in C/C++ (First time using C/C++):
    That is C++, not C.

    Quote Originally Posted by jimi_hendrix View Post
    are there any C++/C# IDE's in the repos that allow you to use a GUI to position the components then you just have to add your code to tell them what to do
    This is new, C++/C#. See the sticky for GUI development. C# has Monodevelop.

    Quote Originally Posted by Reiger View Post
    Also: does this forum have some kind of spoiler tags? Like [spoil][/spoil] ? For those who don't know: spoiler tags are used to hide, erhm well, 'spoilers'...
    No.

    EDIT: @LaRoza: you may want to make the assignment a little more clear regarding the following few constraints:
    1) Are UID's required to be 6 digits long? I assume not as you said they could be anything from 1 thru 99999, still ...
    2) At one point you require people to be able to 'quit' the next time it's 'exit'. Which are the valid killer commands? Both, the former or the latter? (I assumed both.)
    If I wanted leading zero's, I would have stated 000001 to 999999. Also, the forum doesn't use leading zero's (I am going by forum ID's when formulating the input)

    It should be obvious what the command is when I run the program, so it doesn't matter.

    Quote Originally Posted by TreeFinger View Post
    can age be a float or only integers??
    Integer.

    Quote Originally Posted by rubinboy View Post
    is 0000002 a valid forum Id? and is it different to 2
    I just checked the forum, and leading zeros are ignored, so I guess it is valid.

Page 5 of 22 FirstFirst ... 3456715 ... LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •