• Home
  • Quick Bytes
  • Algorithms
  • Java
  • iOS
  • Android
  • Certifications
  • About Me

Lets Code Them Up!

  • Learning Swift: Functions [Parameters]

    March 14th, 2017

     

    In the previous post on functions, we started with defining and calling functions. 

    Today we will go a bit deeper into function parameters or popularly called arguments.

    Parameters are the inputs for the function.

    If you recall from the previous video, this is the factorial function we studied. This factorial function has only one parameter i.e. number.

     

    func factorial (number: Int) -> Int{
        var factorial = 1
        var temp = number
        while(temp>1){
            factorial =  factorial * temp
            temp = temp - 1
        }
        return factorial
    }

     

    Here the number is the input for the factorial function.

    There are functions with one parameter and function with more than one parameters also.

    To see an example of the function with zero parameters we will remove the parameter number from the function factorial. And add a constant number 7 inside the function.

    func factorial () -> Int{
        let number = 7
        var factorial = 1
        var temp = number
        while(temp>1){
            factorial =  factorial * temp
            temp = temp - 1
        }
        return factorial
    }
    
    //functionName(paramName: paramValue)
    
    print("Factorial is \(factorial(number: 7))")

     

    But we see an error in the print function where we call our function. The error says, “Argument passed to call that takes no arguments”

    Learning Swift: Functions [Parameters] errors

    This is happening because the function we defined has no parameters but the function we are calling has one parameter. To remove the error we remove number: 7 from the function call. And now there is no error and we get our output 5040.

    Learning Swift: Functions [Parameters] error gone

    func factorial () -> Int{
        let number = 7
        var factorial = 1
        var temp = number
        while(temp>1){
            factorial =  factorial * temp
            temp = temp - 1
        }
        return factorial
    }
    
    //functionName(paramName: paramValue)
    
    print("Factorial is \(factorial())")

     

    Now to study an example of a function with two parameters, we will define a function product, having two parameters x and y, both integers, and the function will return the product of x and y as an integer.

    //product of two numbers
    
    func product(x: Int, y: Int) -> Int {
        return x*y
    }
    
    print("Product of 6 and 14 is \(product(x: 6, y: 14))")
    

     

    We can see that this function has two parameters in the definition x and y. And we call the function product with values of x as 6 and y as 14 and get the product 84.

    Learning Swift: Functions [Parameters] product

    Similarly, there can be functions with three or even four or five parameters.

    With this, we complete the function parameters. In next post, we will focus on the return types.

    You can find the source code for this post here.

    If you have any questions or comments do leave them in the comment section below.

  • Learning Swift: Functions [Define and Call]

    March 8th, 2017

     

    Hello Friends,

    From the past few posts, we have been learning swift one step at a time. In our previous post, we completed control flow. The code for this post is available here.

    Starting today next few posts will be on functions. Function definition and function call will be covered in this post. Subsequent posts will focus on parameters, return types and argument labels respectively.

    So, what are functions?

     

    Functions are self-contained blocks of code that solve a specific purpose. For example, the factorial function that you see here is used to find the factorial of a given number.

    func factorial (number: Int) -> Int{
        var factorial = 1
        var temp = number
        while(temp>1){
            factorial =  factorial * temp
            temp = temp - 1
        }
        return factorial
    }
    

     

    Or this print that we use so much. The print is also a function which is used to print the results on the console.

    How do we define functions?

     

    We do that using the following syntax

    func functionName (paramName: paramType  ) -> returnType{
     
        //block of code
        return object
     
     }
    

     

    It is clear that the function definition can be broken down into three main parts:

    1. Function name through which we can call this function.
    2. Parameters list which is actually list of inputs for this function
    3. Return type which defines the type of result the function is going to return.

    Let’s see this factorial function definition to better understand function definition

    As we can see, the function name is defined as factorial. The parameter name is number. And the Parameter type is an integer. Return Type is also Integer. Then we have a code inside the curly brackets which calculates the factorial and stores it into a factorial variable and returns it. The data type of factorial variable is Integer, similar to the return type mentioned in the first line of the function.

    How to call a function?

     

    Now that we have defined factorial, how do we use it? How do we call it? How can we find the factorial of number 7 using this function?

    The syntax for the function call is given below:

    functionName(paramName: paramValue)
    

     

    Like in this example we use print factorial of a number is factorial(number: 7). 7 is an integer and we have defined the parameter of the number as an integer.

     

    print("Factorial is \(factorial(number: 7))")

     

    In the next post, we will begin going deeper into functions.

  • How to Open an Existing Android Studio Project

    March 1st, 2017

    Today’s post is a very short one. We will see how to open an existing Android Studio Project.

    To know how to create a project in Android Studio, click here.

     

     

    1. Head over to the Android Studio main screen. Click on “Open existing android studio project”

    Head over to the Android Studio main screen. Click on “Open existing android studio project” 1

    2. Then move to the location where your project is located.

    Our example project is located in the documents folder. So I click on documents. Select the project: Java quiz. Click on “Ok”

    3. Android studio will immediately start building your project.

    Head over to the Android Studio main screen. Click on “Open existing android studio project”

    4. Once the build finishes, Android studio opens the project.

    How to Open an Existing Android Studio Project 4

    5. If there are any errors in building the project they will appear at the bottom. You can also check for errors by clicking on the event log. This project’s event log shoes “Gradle build finishes in 2s and 863 ms”. When you go to Gradle console, it shows “Build Successful”.

    How to Open an Existing Android Studio Project 5

    How to Open an Existing Android Studio Project 6

    6. Let’s just open the main activity file to assure us one last time.

    And here also no errors.

    How to Open an Existing Android Studio Project

    We are done. The project has opened successfully. Go ahead and do some editing.

  • Learning Swift: Control FLow [Switch]

    February 27th, 2017

     

    In our last post, we studied If-Else statements and implemented them in Swift.

    In this post we will learn about Switch statements.

    You can find the source code for this post here.

     

     

    Consider the following example from previous post. I have updated the first condition, which now sets upper limit of marks to 100.

     

    var marksOfStudents = 85
    if(marksOfStudents >= 75){
        print("First Division")
    } else if(marksOfStudents > 30 && marksOfStudents < 75){
        print("Second Division")
    }else{
        print("Student Fails")
    }

     

    Right now if marksOfStudents is greater than 100. We will get an output of “Student Fails” which is wrong. As marks should never be greater than 100. Therefore to handle values more than 100 or less than zero, we will have to add one more condition.

     

    var marksOfStudents = 185
     if(marksOfStudents >= 75 && marksOfStudents<=100){
     print("First Division")
     } else if(marksOfStudents > 30 && marksOfStudents < 75){
     print("Second Division")
     }else if(marksOfStudents>=0 && marksOfStudents<=30){
     print("Student Fails")
     }else{
        print("Out of range")
    }
    

     

    We can see addition of one else-if block now handles the condition in proper way. And we have an output Out of range for values -10 and 185.

    As conditions increase, number of else-if blocks will increase. And the code will become more complex.

    In this case, which involves multiple conditions, it is better to use switch statement.

    Switch statements have been designed to handle multiple conditions only. You might have seen them in Java or Python.

    The syntax of switch statements in Swift is generally like this:

     

    switch conditionalValue {
        case value 1:
            //execute this block
        case value 2:
            //execute this block
        case value 3, value 4:
            //execute this block
        case value5...value6:
            //execute this block
        default:
            otherwise, do something else

     

    Switch statement is followed by case statements which have a block of code associated with them.

    Switch compares the conditionalValue with the values given in case statement(value 1, value2, etc).  When a match is found, code associated with that case is executed.

    default case is used to handle values not covered in the case statements.

    Unlike other languages like java or python, swift allows compound cases and ranges and a lot of other options. Switch statements in Swift are very powerful and flexible.

    For example we can have same case catering to two values like value3 and value4 here. Or we can have a range of values like value5 to value6.

    Let’s see some examples to better understand these.

    First we will convert the above if-else code. into switch code

     

    var marksOfStudents = 85
    switch marksOfStudents {
    case 75...100:
        print("First Division")
    case 31...75:
        print("Second Division")
    case 0...30:
        print("Student Fails")
    default:
        print("Out of range")
    }
    

     

    Since we are checking the value of  marksOfStudents in the if-else block, we can use marksOfStudents as our conditional variable of switch statement.

    The first if-else condition covers marks between 75 and 100 (range of values between 75 and 100). This infers our first case statement will check for values between 75 and 100 using range operator.

    Similarly the second case will cater to range of 31 and 75. And the third case will take range of 0 and 30. For any values less than 0 or greater than 100 we will add a default case.

    With marksOfStudents = 85 we get the output of first division as expected.

     

     

    Let’s check the outputs when marksOfStudents equals 25 or 60 or 105.

     

     

    Now check with marksOfStudents equals 75.

     

     

    Although 75 is included in the second case too, we get the output first division. Because swift checks the conditions one by one and executes the code associated with the first match. So in our case, as soon as first case 75…100 matches, first division is printed. And the second case 31..75 is ignored.

    Let’s consider another example: To count the number of vowels in a sentence.

     

    var sentence = "I am learning swift"
    var countVowels = 0
    for letter in sentence.characters{
        switch letter {
        case "a","A","e","E","i","I","o","O","u","U":
            countVowels += 1
        default:
            countVowels += 0
        }
    }
    print("Number of vowels = \(countVowels)")
    

     

    Instead of writing separate cases for each vowel in upper or lowercase letter, we can compound all the values in one case itself as shown in example.

     

     

    In above example itself, we will find the number of spaces in the sentence. For this we will add a case ” ” and a counter to store number of spaces. The code will look like.

     

    var sentence = "I am learning swift"
    var countVowels = 0
    var countSpaces = 0
    for letter in sentence.characters{
        switch letter {
        case "a","A","e","E","i","I","o","O","u","U":
            countVowels += 1
        case " ":
            countSpaces += 1
        default:
            countVowels += 0
        }
    }
    print("Number of vowels = \(countVowels)")
    print("Number of spaces = \(countSpaces)")
    

     

    This completes switch statement. Next we will start with functions.

  • How to create new project in Android Studio

    February 23rd, 2017

    How to create new project in Android Studio

    In this video, we learn how to create a new project in android studio.

    Before starting, you will need to install Android Studio on your computers. If you have not installed the Android Studio on your computers and need help. Please visit this post.

    The version for Android Studio in this video is 2.2.3. If you have older version or a new version, some screens will differ in the way they look. But the whole process is almost the same.

    So open android studio.

     

     

    Click on “Start a New Android Studio Project”

    This window opens.

     

     

    Now add a project name of your choice. I am giving this project a name of “NewProjectDemo”

    Next is Company Domain. You can go with the default domain which appears here or write your own domain name. Like for example, I use letscodethemup.com i.e. the name of my site and also the channel.

    Next is the location at which you want to save the project. You can go with the default location specified here. Or you can choose your own location. For that, you can click on the icon next to Project Location. This opens the folder structure of your computer. You go to the place where you want to save your project and click ok. But for now, for this project, we will go with the default location.

    Click on Next.

     

     

    Now android studio is asking for you to select the target device for your app. Target device is the device on which your app will run. Now you have to decide which type of app you want to create. You want to create an app for a phone. Or you want to create an app for watch. Or you want to create an app for TV. Or you want to create an app for any other devices mentioned here. For our example we will create an app for phone. So we will select the first option.

    Next you see that the minimum sdk is set to API 15: Android 4.0.3 Icecream Sandwich.

    And how do you choose the minimum sdk level?

    For that you can click on “Help me choose” link.

     

     

    The graph here shows here the android version and percentage of devices covered if you select that version. So if you select Android 6 then your app will run only on devices with android version 6 and above  (just 4.7 percent of all the android devices currently available in the world). But if you choose android version 4 ie icecream sandwhich your app will be able to function on 97% of the devices world wide which is a significant amount. So you see that choosing android version 4 is better for us as our app will run on more number of devices.

    You can go back. By clicking on “OK”

    Now keep min SDK at API 15 and press next.

     

     

    These are all templates provided by Android Studio. By selecting any one of these templates, Android Studio will create a project with files having default data for you.

    You can have a basic activity which include a floating button if that is something you are looking for. Or You have Empty Acitvity which includes nothing. Or You can start with Maps Activity or Login Activity, if that is your purpose. But if you start from scratch and you don’t know which of these activities you might need, you can start with empty activity. And always add any of these activities later in the project as they are needed.

    So we will start with “Empty Activity” and click on “Next”.

     

     

    You can change the name of the main activity and the layout file here if you want to. If you don’t want, just click on finish.

     

     

    Now Android Studio is building your project. It might take few minutes. Have some patience.

     

     

    Android Studio opens the project successfully.

    Now the project is created and we can start building those apps!

  • How to Install Android Studio on Mac

    February 17th, 2017

    How to Install Android Studio on Mac

    Hello Friends,

    In this post we will install android studio on our Mac computers.

    We will install current version of Android Studio ie 2.2.3 on my Mac.

    Let’s begin the installation.

    First search for “Android Studio” in the search bar of the browser. I am using google chrome. Your results might differ. Find the link with title “Download Android Studio and SDK Tools | Android Studio”.

    The link opens the google developers page for downloading Android Studio.

    Click on the button showing “Download Android Studio 2.2.3 for Mac”

    Check the “I agree terms and conditions” checkbox and click on Download Android Studio Button. This begins the downloading.

    Click on the downloaded file. It will show a dialogue of opening the dmg file. And the file will open.

    Drop the Android Studio in Applications folder. A dialogue will appear “Copying Android Studio to Applications”

    After this is done, android studio is installed on your mac.

    Next go to the Launchpad and click on the icon of Android Studio.

    A warning will appear. Ignore and click “Open“.

    Now a choice dialog appears on screen. First choice is “I want to import my settings from a custom location“. This choice is for those who had any previous versions of Android Studio on their system and want to have the same settings. Since it is the first time we are installing Android Studio on our computer, we will go with the second choice.

    “Android Studio Setup Wizard” will open. Just click on Next.

    We will use the “Standard” install settings. If you want to choose what you want to install, go with custom settings. But I will advice to choose standard setting for now. You can always install additional packages later.

    Click on Next.

    Android Studio Wizard asks to verify the settings you want to install. If you want to change now, go back by clicking on “Previous” and choose custom, then choose your preferred settings.

    Else, click on Finish. Now the setup wizard will start installing the settings.

    If you want to see the details of packages installed, click on “Show Details”

    When all packages are installed. Click on “Finish“. Android Studio will open.

    Congratulations, you have installed “Android Studio”.

    Now go and start building awesome applications.

←Previous Page
1 … 18 19 20 21 22
Next Page→

Proudly powered by WordPress

 

Loading Comments...