Results 1 to 30 of 30

Thread: Functions and SubRoutines

  1. #1

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37

    Question Functions and SubRoutines

    I am taking a programming class and am having some trouble grasping some of this stuff. I am new to programming and was hoping maybe someone could maybe explain this to me in "plain english"? Any help would be most appreciated.........The following is the assignment I am having some trouble with.


    Fun with Functions and Subroutines

    · Create a subroutine (not a function) called SquareIt that will take a decimal number and square it. Use module-level vars for the decimal number and the result. Do not use parameters. In a button click event, call SquareIt. After it returns, display a message box that displays something like, "The square of 5 is 25".

    · Create a subroutine similar to as above, except use 2 parameters instead of module-level variables. The first parameter will be the decimal number to square. The second parameter will be a ByRef parameter that can be used to hold the squared decimal. Once again, display a message box as above.

    · Do the same as above, but make it a function called Square. Square takes one parameter (the decimal number to square), and returns the squared decimal number in its return value. Once again, display a message box as above.




    · Create a subroutine called ValidateRange that checks to see if an integer is within a specified range of numbers. Use parameters. The first parameter will be the integer to check. The second parameter will be the minimum number that is acceptable. The third parameter will be the maximum number that is acceptable. The fourth parameter is a boolean called bValid that holds whether the number is in range. In a button click event, call ValidateRange. After it returns, display a message box that displays something like, "The number 63 is not in range". Or, the number 7 is in range.

    · Create a function called ValidRange that does the same thing except that it take just one parameter (the number to check) and returns the boolean in its return value. Once again, display a message box as above.




    · Create a function called MonthName that accepts one integer parameter from 1 to 12 representing a month in the year. For example, 1 corresponds to January. The function should return a String representing the name of the month.

    · Enhance the MonthName function so that it validates that the incoming parameter is in the range of 1 to 12. If it's not, return an empty string:

    Return ""

  2. #2
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    What is it that you don't understand? If you ask more specific questions you'll probably get more answers.

    The main difference between a Sub (Subroutine) And A Function is that a function returns a value. Typically you assign something to the function result (i.e dim result=GetUser) and Subs just get called (i.e SetUser). If a parameter is passed into a sub ByRef then the Sub can motify the variable as it passes through otherwise it gets passed ByVal and any changes don't occur outside of the sub. So by passing a parameter into a Sub ByRef you can use a Sub a lot like a Function.

  3. #3

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    I guess I am looking for an example...I mean could some one show me what this means with one of my problems?

  4. #4
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Well I'm not going to do your homework for you but to give you a nudge here would be the method signatures for the required methods. A method signature is just the declaration part of the method.

    VB Code:
    1. '#1
    2. Public Sub SquareIt()
    3.  
    4. '#2
    5. Public Sub SquareIt(ByVal toSquare As Single,ByRef result As Single)
    6.  
    7. '#3
    8. Public Function SquareIt(ByVal toSquare As Single) As Single
    9.  
    10. '#4
    11. Public Sub ValidateRange(ByVal number As Integer, ByVal min As Integer, ByVal max As Integer, ByRef bValid As Boolean)
    12.  
    13. '#5
    14. Public Function ValidateRange(ByVal number As Integer) As Boolean
    Last edited by Edneeis; Nov 1st, 2002 at 03:06 PM.

  5. #5

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    Thank You.....thats a start.


  6. #6
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Nice nudge Edneeis .
    Dont gain the world and lose your soul

  7. #7

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    I have been messing with this for hours and this still makes absolutley no sense to me......I really want to understand this,although I have no ambitions of being a software engineer....could anyone please try to explain this in english without all the 'programming slang"
    Thank You so much

  8. #8
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    You gotta do the one thing where the deal messes with the thing and sends it back. Then do it again but with the things switched around and then where it returns the thing.




    Just kidding. So whats the problem exactly? Try asking specific questions. What don't you understand? What do you have so far? Post some code.

  9. #9

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    ok, Well first of all I posted the assignment and I dont understand what it is my Instructor is asking for nor do any of the other students in my class, but he isnt giving any clarification so i am trying to understand what it is on my own, to no avail. I will work a bit more on it and get back to you......than you so mcuh for answering me though, I truly appreciate it......

  10. #10
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    It looks like he is teaching you the difference between Functions, Subs, and ByRef, ByVal. See most of these are doing the samething, just in different ways. Like all the SquareIt things do the exact same thing just in different ways.

  11. #11

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    Fun with Functions and Subroutines

    For the problems below, you'll need to create a single form.

    · Add a textbox to the form called txtNbr, and a button with the caption SquareItMod. Create a subroutine (not a function) called SquareItMod that will take a decimal number from txtNbr and square it. Use module-level vars for the decimal number and the result. Do not use parameters. In the button click event, call SquareIt. After it returns, display a message box that displays something like, "The square of 5 is 25".

    · Add a button with the caption SquareItParm to the form. Create a subroutine named SquareItParm, similar to the above, except use 2 parameters instead of module-level variables. The first parameter will be the decimal number to square. The second parameter will be a ByRef parameter that can be used to hold the squared decimal. Once again, display a message box as above, when the button is clicked.

    · Add a button with the caption Square, to the form. Do the same as above, but make it a function called Square. Square takes one parameter (the decimal number to square), and returns the squared decimal number in its return value. Once again, display a message box as above, when the button is clicked.




    · Add a button with the caption ValidateRange to the form. Add 2 more textboxes to the form, called txtMin and txtMax. Create a subroutine called ValidateRange that checks to see if an integer is within a specified range of numbers. Use parameters. The first parameter will be the integer to check, taken from the txtNbr textbox. The second parameter will be the minimum number that is acceptable, taken from txtMin. The third parameter will be the maximum number that is acceptable, taken from txtMax. The fourth parameter is a boolean called bValid that holds whether the number is in range. In the button click event, call ValidateRange. After it returns, display a message box that displays something like, "The number 63 is not in range". Or, "The number 7 is in range".

    · Add a button with the caption ValidRange to the form. Create a function called ValidRange that does the same thing as above, except that it takes three parameters (the number to check, the minimum number, the maximum number) and returns the boolean in its return value. Once again, display a message box as above when the button is clicked.



    NOW HE HAS CHANGED THE WHOLE THING......

    THIS IS HIS NEW UPDATE:


    · Add a button with the caption MonthName to the form. Create a function called MonthName that accepts one integer parameter (taken from txtNbr). The function should return a String representing the name of the month. For example, if the user enters 1, display "January" in a message box. If the user enters 3, display "March". Call the function when the user clicks on the button.

    · Enhance the MonthName function so that it validates that the incoming parameter is in the range of 1 to 12. If it's not, return an empty string:

    Return ""

    Note that, for the above two problems, you only need to turn in ONE function called MonthName that incorporates the functionality of both.

  12. #12

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37

    Angry

    THIS IS HIS NEW UPDATE

  13. #13
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Nicky, it seems like this instructor is trying to teach you guys run first instead of walking j/k.

    Seriously though, can you answer these questions?

    1. Do you know what a module is?
    2. Do you understand what global variables are?
    3. Do you understand the difference between a function and a subroutine?
    4. Do the know the difference between ByRef and ByVal?
    5. Do you know what an if statement is?
    6. Do you know what a select statement is?

    What you have to do is not hard at all, you just need a better grasp of the programming concepts. BTW what text book are you using?
    Dont gain the world and lose your soul

  14. #14

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    Module-I beleive is a Var that can be used in any procudre or something

    global- can be used anywhere in the project

    functions and subroutines are what i am not getting at all

    I can look up the definitons for you......I am not a programmer and I really dont understand this stuff, but i am really trying to.
    I know how to use If statements......

    I am using the text "Programming In Visual Basic.Net" by Julia Case Bradley.

    The book was great the first 3 chapters and then varibles came along and I got lost and now we are doing this stuff and he doesnt explain it well......just does a few examples and says....there u go.....now go program, I am not looking for anyone to do my assignments for me.........just maybe explain it like a recipe or something....lol. I dont know

    SCREAMING!!

    lol
    ty for replying.......hope to hear from you again

  15. #15

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    Hello again,

    I have an example, my instructors example of how we are to build our code.....similar to how he did his. Now this is what I am wondering if one of you guys "please" could do for me. In remarks if you could, under each statemnet of code, just explain what is going on that way I might be abole to decipher what is going on...through the 3 books I have bought and my text and notes I am gathering throughout the web, maybe I can grasp this stuff.....I know its asking alot, but i would be so grateful for any hlep.
    Thank you all!!

    N
    Attached Files Attached Files
    • File Type: txt w.txt (10.6 KB, 80 views)

  16. #16
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Zip up the project and post the whole thing so we can see if you are doing things right. BTW is this your first time programming?

    I'll comment the code for you an report back.

    DevGrp out.
    Dont gain the world and lose your soul

  17. #17
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Ok, this code should be self explanitory. All thats going on is some basic validation. Checking for negative numbers, numerics, and empty textboxes.
    VB Code:
    1. Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    2.  
    3.     Try
    4.         If txtNbr1.Text = "" Then
    5.             MessageBox.Show("This field must not be blank")
    6.             txtNbr1.Focus()
    7.         ElseIf Not IsNumeric(txtNbr1.Text) Then
    8.             MessageBox.Show("This field must be numeric")
    9.             txtNbr1.Focus()
    10.         ElseIf ToDecimal(txtNbr1.Text) <= 0 Then
    11.             MessageBox.Show("This field must be greater than zero")
    12.             txtNbr1.Focus()
    13.         ElseIf txtNbr2.Text = "" Then
    14.             MessageBox.Show("This field must not be blank")
    15.             txtNbr2.Focus()
    16.         ElseIf Not IsNumeric(txtNbr2.Text) The
    17.             MessageBox.Show("This field must be numeric")
    18.             txtNbr2.Focus()
    19.         ElseIf ToDecimal(txtNbr2.Text) <= 0 Then
    20.             MessageBox.Show("This field must be greater than zero")
    21.             txtNbr2.Focus()
    22.         ElseIf txtNbr3.Text = "" Then
    23.             MessageBox.Show("This field must not be blank")
    24.             txtNbr3.Focus()
    25.         ElseIf Not IsNumeric(txtNbr3.Text) Then
    26.             MessageBox.Show("This field must be numeric")
    27.             txtNbr3.Focus()
    28.         ElseIf ToDecimal(txtNbr3.Text) <= 0 Then
    29.             MessageBox.Show("This field must be greater than zero")
    30.             txtNbr3.Focus()
    31.         Else
    32.             MessageBox.Show("Data has been saved")
    33.     End If
    34.  
    35.     Catch Ex As Exception
    36.         MessageBox.Show(Ex.ToString, "Unexpected Error")
    37.         Application.Exit()
    38.     End Try
    39.  
    40. End Sub

    Ok I see that you have made a SubRoutine to validate the texboxes on the form. Thats good. Now as you can see this subroutine does not return a value, thats why its called a subroutine. If it was to return a value, it would be called a function. To change this to function you would just change the word Sub to Function put the type of return value at the end.

    eg.Function ValidateField() As Boolean

    In that case Boolean would be the return value, which would be a true or false.

    VB Code:
    1. Private Sub ValidateField()
    2.  
    3.     Try
    4.         If m_txtNbr.Text = "" Then
    5.             MessageBox.Show("This field must not be blank")
    6.             m_txtNbr.Focus()
    7.             m_bInvalidField = True
    8.         ElseIf Not IsNumeric(m_txtNbr.Text) Then
    9.             MessageBox.Show("This field must be numeric")
    10.             m_txtNbr.Focus()
    11.             m_bInvalidField = True
    12.         ElseIf ToDecimal(m_txtNbr.Text) <= 0 Then
    13.             MessageBox.Show("This field must be greater than zero")
    14.             m_txtNbr.Focus()
    15.             m_bInvalidField = True
    16.         Else
    17.             m_bInvalidField = False
    18.         End If
    19.  
    20.     Catch Ex As Exception
    21.         MessageBox.Show(Ex.ToString, "Unexpected Error")
    22.         Application.Exit()
    23.     End Try
    24. End Sub
    Last edited by DevGrp; Nov 3rd, 2002 at 09:53 AM.
    Dont gain the world and lose your soul

  18. #18
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    I looked at the file. You seem to know what you are doing.

    Ok you said you are not getting Functions and Subroutines.

    Ok here goes. To understand them better, do not think of them as functions or subroutines. Just think of them as Methods. Just remember that Methods that return a value should be declared with the function keyword and Methods that does not return a value should be declared with the sub keyword.

    Here is an example.

    VB Code:
    1. '[b]This is a method that takes two integers parameters and returns an integer value (Function)[/b]
    2.  
    3. Function AddNums(ByVal num1 as Integer, num2 as Integer) as Integer
    4.  
    5.       return num1 + num2
    6.  
    7. End Function
    8.  
    9. '[b]This method does take any parameters and do not return a value (Sub)[/b]
    10. Sub AddNums()
    11.      
    12.       Dim num1 , num2 as Integer
    13.      
    14.       num1 = 12
    15.       num2 = 36
    16.      
    17.       MessageBox.Show(num1 + num2)
    18.  
    19. End Sub
    Dont gain the world and lose your soul

  19. #19

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37

    Question

    Dev,
    No I dont know what I am doing as this isnt MY code, its my Instructors... he sent it out as an example. I will use your notes though ......thank you so much for taking the time to look.

  20. #20

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    Hello Once again........I am still not getting this stuff.......how do I write the code? I mean.......it says I need to add a textbox named txtNBR which I have done and then I am too create a Subroutine...which I did, but i dont understand where am I supposed to put the code? In the btn click event or in the sub? how do I get it to square whatever the used puts in the box?
    I have been playing with this all week.....and nothing seems to make sense......can I hire someone to tutor me?
    I am desperate here

    ty

  21. #21
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Hello Once again........I am still not getting this stuff.......how do I write the code? I mean.......it says I need to add a textbox named txtNBR which I have done and then I am too create a Subroutine...which I did, but i dont understand where am I supposed to put the code? In the btn click event or in the sub? how do I get it to square whatever the used puts in the box?
    Ok Check this out, you can either create the subroutine inside the form where its going to be used or create a module, then create the all your functions and subroutines in it.

    To square whatever in put in the text box, you are going to have to parse the data. To parse the data from the TextBox, here is the SquareIt Subroutine.

    VB Code:
    1. Sub SquareIt(ByVal txtBox As TextBox)
    2.         Dim num As Decimal
    3.         Dim square As Decimal
    4.  
    5.         num = Decimal.Parse(txtBox.Text)
    6.  
    7.         square = num * num
    8.  
    9.         MessageBox.Show("The Square of " & num & " is " & square)
    10. End Sub
    Dont gain the world and lose your soul

  22. #22

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    I am using VB.Net Visual Studio


    Public Class frmSquareIt
    Inherits System.Windows.Forms.Form
    Public Sub SquareItMod()

    Dim m_decNumber As Decimal
    Dim m_decResult As Decimal=5

    m_decNumber = CDec(txtNbr.Text)
    m_decResult = CDec(txtNbr.Text)

    MsgBox(m_decNumber ^ m_decResult)

    End Sub

    #Region " Windows Form Designer generated code "




    Private Sub btnSquare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSquare.Click
    Call SquareItMod()

    End Sub
    End Class

  23. #23

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    Ok
    I got the first one to work, now onto the 2nd one.......

  24. #24
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Ok, now try and do the others. And always remember the more sweat in training the less you bleed in combat, so do some experiementing, read ahead and practice practice practice .
    Dont gain the world and lose your soul

  25. #25

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    What is a Parameter? ........Its says I need to add parameters instead of varibles......The first par. will be the decimal number to square and the second will be a BYRef that can be used to hold the squared decimal.

  26. #26
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Parameters are values that will be passed to the function when it is called.

    eg:
    VB Code:
    1. Function MonthName(ByVal mnt As Integer) As String 'mnt is the parameter being passed

    When you pass parameters to functions. You can either pass them by value (ByVal) or by reference (ByRef). ByVal is the default way for passing parameters. When parameters are passed by value, you are making a copy of the variable and passing it to the function or sub. Parameters passed by reference is a pointer to the memory address where that varible is stored. So it you passed a param by ref, you would be modifying the original variable instead of a copy, which is case if you passed a param by value. I hope that made sense.
    Dont gain the world and lose your soul

  27. #27

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    CAN YOU SHOW ME HOW TO DO THIS? I DONT GET IT......I need to hire a programmer.....do you know of any as this is not making sense to me.......I will FAIL and LOSE my WHOLE educatioon if I DONT pass this




    Add a button with the caption SquareItParm to the form. Create a subroutine named SquareItParm, similar to the above, except use 2 parameters instead of module-level variables. The first parameter will be the decimal number to square. The second parameter will be a ByRef parameter that can be used to hold the squared decimal. Once again, display a message box as above, when the button is clicked.

    · Add a button with the caption Square, to the form. Do the same as above, but make it a function called Square. Square takes one parameter (the decimal number to square), and returns the squared decimal number in its return value. Once again, display a message box as above, when the button is clicked.

  28. #28
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Ok, you need to calm down , I dont think you're gonna lose your education if you fail one class . I dont think I would be helping you much if I wrote the function for you. . Look at the examples that Edneeis provided and see if you can figure it out. Anyway I'm going to sleep now. I'll keep posting if you need anymore help.
    Dont gain the world and lose your soul

  29. #29

    Thread Starter
    Member
    Join Date
    Nov 2002
    Posts
    37
    Thank You

  30. #30
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    No prob. How did you do?
    Dont gain the world and lose your soul

Posting Permissions

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



Click Here to Expand Forum to Full Width