<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mercy Jemosop on Medium]]></title>
        <description><![CDATA[Stories by Mercy Jemosop on Medium]]></description>
        <link>https://medium.com/@mercyjemosop?source=rss-23a78fb7b7f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ozgWtcTg6wijxVA6ht93vQ.jpeg</url>
            <title>Stories by Mercy Jemosop on Medium</title>
            <link>https://medium.com/@mercyjemosop?source=rss-23a78fb7b7f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 03:21:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mercyjemosop/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SPRING BOOT]]></title>
            <link>https://mercyjemosop.medium.com/spring-boot-2cbc9e187406?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cbc9e187406</guid>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 10:23:03 GMT</pubDate>
            <atom:updated>2026-04-27T10:23:03.354Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lesson 1: Get started with Spring Boot.</h3><p><strong>Introduction</strong><br>Hello, welcome to our first lesson on Spring Boot. To get started, you need to have the basic understanding of Java fundamentals. We will cover some topics with a simple project.</p><p>Let’s first learn how to create a Spring Boot project using Spring Initializr.<br><a href="https://start.spring.io/">https://start.spring.io/</a>. Navigate to the link below; you will see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hnVzGcMpb-Iew1THna2bg.png" /></figure><p>Let’s understand this page:</p><p><strong>Step 1: Select project</strong></p><p>Before selecting the project, check the table below to understand the difference between Gradle and Maven. This will help you make a better decision for your project.<br><strong>Gradle </strong>and <strong>Maven </strong>are build automation tools primarily used in Java development to manage the software development lifecycle:<br>- Compiling source code, managing external libraries, running tests, and packaging code into executable formats (jar/war—read on the difference between these two).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*Dw-R0mE63iByf9Y7s5NMeQ.png" /></figure><p>For my TODO list project I will select Maven.<br><strong><em>Step 2: Select language</em></strong><br>Java</p><p><strong><em>Step 3: Select Spring Boot version</em></strong><br>When selecting this, it&#39;s important to note the following:<br>Spring Boot 3.x requires a minimum of<strong> Java 17</strong>, while Spring Boot 2.x supports Java 8 and higher.<br>A <strong>snapshot </strong>version in Maven is one that has not been released and may be updated frequently.</p><p>I will go with the default Spring Boot version</p><p><strong>Step 4: Let’s name our project</strong><br>If you have a domain name, you can replace (com.example) if not, we can use the default<br><strong>Step 4: Packaging </strong>(select compression formats for the Java application).<strong> <br>Jar—</strong>(Java Archive)<br>It is used for packaging libraries (reusable code), plugins, or standalone desktop applications. It can have any directory structure. Deployment of a jar file is executed directly by the Java runtime environment (JRE) using java -jar filename.jar command<strong><br>WAR—</strong>(Web application archive)<br>It&#39;s designed for web applications intended to run on a web server or servlet container. It has a strict predefined structure, including a WEB-INF directory for private resources and a web.xml deployment descriptor.<br>Deployment must be to a web container (Apache Tomcat or Netty); it unpacks and manages web applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*wh7fZsXBug7Uq_nJAUCtEw.png" /></figure><p><a href="https://www.baeldung.com/java-jar-war-packaging#:~:text=Inside%2C%20it%20has%20a%20META,JAR%20without%20using%20additional%20software.">To learn more on this</a></p><p><strong>Step 5: Configurations</strong><br>Properties File: Properties files use a simple `key=value` syntax. Each property is defined on a new line, and you can add comments using `#`.</p><pre>application.properties- file name<br># Simple flat structure<br>server.port=8080<br>spring.datasource.url=jdbc:mysql://localhost:3306/mydb<br>spring.datasource.username=root<br>spring.datasource.password=secret<br># Lists require indexed keys<br>app.admins[0]=Alice<br>app.admins[1]=Bob</pre><p>YAML File: YAML uses a more human-readable and structured format. It uses indentation (whitespace) to represent hierarchy and colons to separate keys and values.</p><pre>application.yml -file name<br># Clean hierarchical structure<br>server:<br>  port: 8080<br>spring:<br>  datasource:<br>    url: jdbc:mysql://localhost:3306/mydb<br>    username: root<br>    password: secret<br># Native list support<br>app:<br>  admins:<br>    - Alice<br>    - Bob</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*TYv586JZ0cTp05msijuwmw.png" /></figure><p>Based on this, select the best format you will work with.</p><p><strong>Step 6: Select Java version</strong><br>You can use the default and change as we update the requirements or select a specific version based on your requirements.<br>Finally, click the Generate button at the bottom center to generate to project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnRQ3Blh2k_bdZegU0J3Sg.png" /></figure><p><strong>Step 7: Select dependencies</strong><br>You can select what you want to use and add other dependencies as we proceed with the project.</p><p>Yeeeeey!!!!!!!!</p><p><strong>Lesson 2: Targets</strong></p><p>We need to create a todo list project (give it any name)<br>- Create a GitHub account (if it does not exist)<br>- Unzip project locally<br>- Push project to GitHub<br>- Add dependencies<br>- Run code- without logic</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cbc9e187406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigation with compose]]></title>
            <link>https://mercyjemosop.medium.com/navigation-with-compose-068ae1edb5bb?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/068ae1edb5bb</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[arguments]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[deep-link-android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 18:38:16 GMT</pubDate>
            <atom:updated>2024-03-25T19:43:33.534Z</atom:updated>
            <content:encoded><![CDATA[<p>Handle navigation and redirection</p><p>Introduction</p><p>Hello, welcome to another session of learning kotlin. We are going to go over navigation in jetpack, we will handle navigation in the app and redirection from a web back to the application using deeplinks. Let’s goo!!!!</p><p><strong>App Navigation</strong> is moving from one screen to another inorder to complete a task.</p><p><strong>Deep link</strong> is a link that takes you to a specific destination within the application.</p><p>Setup android project</p><ol><li>Add a dependency to build.gradle.kts</li></ol><p>Check the official documentation for updated nav_version</p><pre>dependencies {<br>    val nav_version = &quot;2.7.7&quot;<br><br>    implementation(&quot;androidx.navigation:navigation-compose:$nav_version&quot;)<br>}</pre><p>2. Create two composable screens to be used to test navigation</p><pre>## Screen one<br><br>@Composable<br>fun ScreenOne(){<br>    Button(<br>        onClick={},<br>            modifier = Modifier.width(300.dp)<br>            ) {<br>                Text(text = &quot;Screen One&quot;)<br>            }<br><br>}<br><br>## Screen two<br>@Composable<br>fun ScreenTwo(){<br>    Button(<br>        onClick={},<br>            modifier = Modifier.width(300.dp)<br>            ) {<br>                Text(text = &quot;Screen One&quot;)<br>            }<br><br>}</pre><p>we now have two composable screens to test our navigation between two screens.</p><p>3. setup our navigation</p><p><em>NavController</em></p><p>This is a one of the key concepts in navigation. It stores the navigation graph and makes available methods for your application to navigate between the locations shown in the graph.<br>Its the central navigation API and tracks which destination a user has visited and allows the user to move between destinations.</p><p><em>NavHost</em> is used to create the navigation graph. Each NavHost you create has its own corresponding navController.</p><p><em>Navigation graph</em> is a data structure that contains each destination within your app and connections between them.</p><pre>val navController = rememberNavController()<br><br>NavHost(navController = navController, startDestination = &quot;screenone&quot;) {<br>    composable(&quot;screenone&quot;) { ScreenOne( ) }<br>    composable(&quot;ScreenTwo&quot;) { ScreenTwo( ) }<br>   <br>}</pre><p>we can refactor the above class by introducing a sealed class that contains the route and String resource id for the destinations.</p><pre>sealed class Screen(val route: String, @StringRes val resourceId: Int) {<br>    object ScreenOne : Screen(&quot;screen_one&quot;, R.string.screen_one)<br>    object ScreenTwo : Screen(&quot;screen_two&quot;, R.string.screen_two)<br>}<br><br>@Composable<br>fun AppRoute(navController: NavHostController) {<br><br><br>    NavHost(navController = navController, startDestination = Screen.ScreenOne.route) {<br>        composable(Screen.ScreenOne.route) { ScreenOne(navController) }<br>        composable(Screen.ScreenTwo.route) { ScreenTwo(navController) }<br>    }<br>}</pre><p>Inside res/values/String.xml folder</p><pre>&lt;resources&gt;<br>    &lt;string name=&quot;app_name&quot;&gt;NavigationExample&lt;/string&gt;<br>    &lt;string name=&quot;screen_one&quot;&gt;ScreenOne&lt;/string&gt;<br>    &lt;string name=&quot;screen_two&quot;&gt;ScreenTwo&lt;/string&gt;<br>&lt;/resources&gt;</pre><p>NavHost composable passes a NavController and a route string that corresponds to the start destination</p><pre>NavHost(navController = navController, startDestination = &quot;screenone&quot;)</pre><ul><li>The lambda passed to the NavHost ultimately calls the NavController.createGraph() and returns a NavGraph</li></ul><pre>val navGraph by remember(navController) {<br>  navController.createGraph(startDestination = &quot;profile&quot;) {<br>   composable(Screen.ScreenOne.route) { ScreenOne( ) }<br>    composable(Screen.ScreenTwo.route) { ScreenTwo( ) }<br>  }<br>}<br>NavHost(navController, navGraph)</pre><ul><li>NavGraphBuilder.composable() adds destination to the resulting NavGraph.</li><li>“screenone” and “screentwo” is the key that identify the two destination.</li></ul><p><strong>Route</strong> is a String that defines a path to your composable.</p><p>Update our code with the navigation above</p><pre>@Composable<br>fun ScreenOne(navController: NavController) {<br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Text(text = &quot;Screen One&quot;)<br>        Spacer(modifier = Modifier.height(60.dp))<br>        Button(<br>            onClick = {<br>                navController.navigate(&quot;screentwo&quot;)<br>            },<br>            modifier = Modifier.width(300.dp)<br>        ) {<br>            Text(text = &quot;Screen Two&quot;, fontSize = 10.sp)<br>        }<br>    }<br>}<br><br>@Composable<br>fun ScreenTwo(navController: NavController) {<br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Text(text = &quot;Screen Two&quot;)<br>        Spacer(modifier = Modifier.height(60.dp))<br>        Button(<br>            onClick = {<br>                navController.navigate(&quot;screenone&quot;)<br>            },<br>            modifier = Modifier.width(300.dp)<br>        ) {<br>            Text(text = &quot;Screen One&quot;, fontSize = 10.sp)<br>        }<br>    }<br>}<br><br>@Composable<br>fun AppRoute(navController: NavHostController,) {<br><br>    NavHost(navController = navController, startDestination = Screen.ScreenOne.route) {<br>        composable(Screen.ScreenOne.route) { ScreenOne( ) }<br>    composable(Screen.ScreenTwo.route) { ScreenTwo( ) }<br><br>    }<br>}<br><br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            val navController = rememberNavController()<br>            AppRoute(navController)<br>        }<br>    }<br>}</pre><p><strong>Passing arguments to another screen</strong></p><p>Compose supports passing arguments between composable destinations. To achieve this we need to add argument placeholders to our route which are passed as string by default.</p><p>The arguments parameter of a composable accepts a list of NamedNavArgument object, the NamedNavArgument can be created using navArgument() method and specify its exact type.</p><pre>    composable(<br>            &quot;screenthree/{userId}&quot;,<br>            arguments = listOf(navArgument(&quot;userId&quot;) { type = NavType.StringType })<br>        ) {backStackEntry -&gt;<br>            ScreenThreeArg(navController, backStackEntry.arguments?.getString(&quot;userId&quot;))<br>        }<br>    }</pre><p>Display argument(userId) Text(text = “Value passed $userId”)</p><pre>@Composable<br>fun ScreenThreeArg(navController: NavController, userId: String?) {<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Text(text = &quot;Screen Three&quot;)<br>        Text(text = &quot;Value passed $userId&quot;)<br>        Spacer(modifier = Modifier.height(60.dp))<br>        Button(<br>            onClick = {<br>                navController.navigate(&quot;screentwo&quot;)<br>            },<br>            modifier = Modifier.width(300.dp)<br>        ) {<br>            Text(text = &quot;Screen two&quot;, fontSize = 10.sp)<br>        }<br>    }</pre><p>pass argument to destination, you append it to the route when you make the navigate call.</p><pre> navController.navigate(&quot;screenthree/123 &quot;)</pre><p><strong>Optional arguments</strong></p><p>Navigation compose supports optional navigation arguments. This arguments differ from the required arguments in two ways:</p><ul><li><strong>They must be included using the query parameter</strong></li></ul><pre>##syntax<br>&quot;?argName={argName}&quot;)</pre><ul><li>They must have a default value or have nullable = true</li></ul><p>All optional arguments must be explicitly added to the composable() function as list:</p><pre>composable(<br>    &quot;profile?userId={userId}&quot;,<br>    arguments = listOf(navArgument(&quot;userId&quot;) { defaultValue = &quot;user1234&quot; })<br>) { backStackEntry -&gt;<br>    Profile(navController, backStackEntry.arguments?.getString(&quot;userId&quot;))<br>}</pre><p><strong>Note:</strong></p><ul><li>If there is no argument passed to the destination, the default value is used instead(user1234).</li><li>handling arguments through routes ensures means composables remain completely independent of navigation and make them more testeable.</li></ul><p><strong>Deeplinks with jetpack compose</strong></p><p>Compose supports implicit deep links that can be defined as part of the composable() function. <em>deeplinks</em> parameter accepts a list of NavDeepLink object which can be created using navDeepLink().</p><pre>   deepLinks = listOf(navDeepLink { uriPattern = &quot;$uri/{id}&quot; })</pre><p>This concept is similar passing argument above:</p><pre> val uri = &quot;https://stackoverflow.com&quot;    <br>composable(<br>            &quot;screendeeplink?id={id}&quot;,<br>            deepLinks = listOf(navDeepLink { uriPattern = &quot;$uri/{id}&quot; })<br>        ) { backStackEntry -&gt;<br>            ScreendeepLink(navController, backStackEntry.arguments?.getString(&quot;id&quot;))<br>        }</pre><p>Deeplinks allows you to associate a specific url, action or mime type with a composable.<br>To expose deeplinks to external apps, we must add the appropriate &lt;intent-filter&gt; elements to our AndroidManifest.xml</p><pre>       &lt;intent-filter android:autoVerify=&quot;true&quot;&gt;<br>                &lt;action android:name=&quot;android.intent.action.VIEW&quot;/&gt;<br>                &lt;category android:name=&quot;android.intent.category.DEFAULT&quot;/&gt;<br>                &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot;/&gt;<br>                &lt;data android:scheme=&quot;https&quot; android:host=&quot;stackoverflow.com&quot; /&gt;<br>            &lt;/intent-filter&gt;</pre><p>test it by printing the value in composable screen</p><pre>@Composable<br>fun ScreendeepLink(navController: NavController, value: String?) {<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Text(text = &quot;Screen Three&quot;)<br>        Text(text = &quot;Value passed using deeplink :: $value&quot;)<br>        Spacer(modifier = Modifier.height(60.dp))<br>        Button(<br>            onClick = {<br>                navController.navigate(&quot;screentwo&quot;)<br>            },<br>            modifier = Modifier.width(300.dp)<br>        ) {<br>            Text(text = &quot;Screen two&quot;, fontSize = 10.sp)<br>        }<br>    }</pre><p>Yeeh!!! We have covered most part of navigation in jetpack compose.</p><ul><li>use ViewModel</li><li>Refactor route</li></ul><p><a href="https://github.com/mercykip/navigation-compose">Github link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=068ae1edb5bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Property Delegation Kotlin]]></title>
            <link>https://mercyjemosop.medium.com/property-delegation-kotlin-787800f8bf47?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/787800f8bf47</guid>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 18:31:26 GMT</pubDate>
            <atom:updated>2024-03-05T18:31:26.139Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Welcome to another learning session, today we are covering property delegation in kotlin. To break down to topic lets understand the terminologies used in out title.</p><p><strong><em>Properties </em></strong>are ussually backed directly by corresponding fields. Normally, properties have associated fields directly backing them, however this isn’t always the case; properties can still exist as long as they are appropriately exposed to the outside world.</p><p><strong><em>What’s a delegate class ?</em></strong><br>This is a class that provides the property of a value and handles its changes. It will help us to assign or pass on(delegate), the getter-setter logic altogether to a different class so that it can help us in reusing the code.<br>This is an alternative for inheritance property.</p><p>Examples of built in delegate property</p><ul><li><strong>Lazy </strong>properties- value gets computed only upon first access</li><li><strong>Observable </strong>properties<strong>-</strong> listeners get notified about changes to this property.</li><li>Storing properties in a map instead of a separate field for each property.</li></ul><h3>Lazy properties</h3><p>Lazy() takes a lambda and returns an instance of Lazy&lt;T&gt;, which can serve as a delegate for implementing lazy property.</p><p>The first call to get() executes the lambda passed to get lazy() and remembers the result. Subsequent calls to get() simply returns the remembered results.</p><p>The evolution of lazy properties is synchronized by default meaning the value is computed only in one thread but all other threads will see the same value.</p><p>In situations where synchronization of the initialization delegate is not required to allow multiple threads to execute simultaniously. We need to pass LazyThreadSafetyMode.PUBLICATION as a parameter to lazy().</p><p>If you&#39;re sure that the initialization will always happen in the same thread as the one where you use the property, you can use LazyThreadSafetyMode.NONE. It doesn&#39;t incur any thread-safety guarantees and related overhead.</p><pre>val lazyValue: String by lazy {<br>    println(&quot;computed!&quot;)<br>    &quot;Hello&quot;<br>}<br><br>fun main() {<br>    println(lazyValue)<br>    println(lazyValue)<br>}<br>//output<br>computed!<br>Hello<br>Hello</pre><h3>Observable properties</h3><p>Delegate.observable() takes two arguments</p><ul><li>The initial value</li><li>A handler for modifications</li></ul><p>The handler is called everytime you assign a property. It has three parameters.</p><ul><li>The property being assigned to</li><li>The old value</li><li>The new value</li></ul><pre>import kotlin.properties.Delegates<br><br>class User {<br>    var name: String by Delegates.observable(&quot;&lt;no name&gt;&quot;) {<br>        prop, old, new -&gt;<br>        println(&quot;$old -&gt; $new&quot;)<br>    }<br>}<br><br>fun main() {<br>    val user = User()<br>    user.name = &quot;first&quot;<br>    user.name = &quot;second&quot;<br>}<br><br>/// output<br>&lt;no name&gt; -&gt; first<br>first -&gt; second</pre><p>If you want to intercept assignments and veto them, use <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.properties/-delegates/vetoable.html">vetoable()</a> instead of observable(). The handler passed to vetoable will be called before the assignment of a new property value.</p><pre><br>var max: Int by Delegates.vetoable(0) { property, oldValue, newValue -&gt;<br>    newValue &gt; oldValue<br>}<br><br>fun main() {<br>  println(max) // 0<br><br>max = 10<br>println(max) // 10<br><br>max = 5<br>println(max) // 10<br>}<br><br>/// output<br>0<br>10<br>10</pre><h3>Storing properties in a map</h3><p>This is useful in applications for things like: parsing Json or performing other dynamic tasks. <br>You can use the map instance itself as the delegate for a delegated property</p><pre><br>class User(val map: Map&lt;String, Any?&gt;) {<br>    val name: String by map<br>    val age: Int     by map<br>}<br>val user = User(mapOf(<br>    &quot;name&quot; to &quot;John Doe&quot;,<br>    &quot;age&quot;  to 25<br>))<br>fun main() {<br>println(user.name) // Prints &quot;John Doe&quot;<br>println(user.age)  // Prints 25<br>}<br><br>/// output<br>John Doe<br>25</pre><h3>Delegating to another property</h3><p>A property can delegate its getter and setter to another property. This delegation is available in both top-level and class properties(member and extension).</p><p>Delegate property can be:</p><ul><li>A top-level property</li><li>A member or an extension property of the same class</li><li>A member or an extension property of another class</li></ul><p>We use : : qualifier in the delegate name to delegate to another property</p><pre>var topLevelInt: Int = 0<br>class ClassWithDelegate(val anotherClassInt: Int)<br><br>class MyClass(var memberInt: Int, val anotherClassInstance: ClassWithDelegate) {<br>    var delegatedToMember: Int by this::memberInt<br>    var delegatedToTopLevel: Int by ::topLevelInt<br><br>    val delegatedToAnotherClass: Int by anotherClassInstance::anotherClassInt<br>}<br>var MyClass.extDelegated: Int by ::topLevelInt</pre><p>Usage:</p><ul><li>When you want to rename a property in a backward compatible way. introduce a new property, annotate the old one with the @Deprecated annotation, and delegate its implementation.</li></ul><pre>class MyClass {<br>   var newName: Int = 0<br>   @Deprecated(&quot;Use &#39;newName&#39; instead&quot;, ReplaceWith(&quot;newName&quot;))<br>   var oldName: Int by this::newName<br>}<br>fun main() {<br>   val myClass = MyClass()<br>   // Notification: &#39;oldName: Int&#39; is deprecated.<br>   // Use &#39;newName&#39; instead<br>   myClass.oldName = 42<br>   println(myClass.newName) // 42<br>}<br>/// output<br>42</pre><p>That’s the end. <a href="https://kotlinlang.org/docs/delegated-properties.html#local-delegated-properties">To learn more visit the official documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=787800f8bf47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Types of Functions in Kotlin]]></title>
            <link>https://mercyjemosop.medium.com/types-of-functions-in-kotlin-36e13f0dadb2?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/36e13f0dadb2</guid>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 18:13:16 GMT</pubDate>
            <atom:updated>2024-01-22T18:13:16.043Z</atom:updated>
            <content:encoded><![CDATA[<p>inline,infix,operator</p><h4>Introduction</h4><p>A <strong>Function</strong> is a block of code that performs a specific task. It can be called from anywhere in a program. Kotlin functions are declared using the keyword <strong>fun</strong>.</p><pre>fun double(x: Int): Int {<br>    return 2 * x<br>}</pre><p><strong>Method </strong>are functions used to perform certain action.</p><p>Calling a function</p><pre>val result = double(2)<br>print(result)<br>output<br>4</pre><p>What is a function <strong>parameter? </strong>this is a variable defined during function declaration or definition. It’s data passed into a function, it is specified after the function name inside the parentheses. It is defined using pascal notation <strong>name:type.<br></strong>Parameters are separated by commas.</p><pre>fun powerOf(number: Int, exponent: Int): Int { /*...*/ }</pre><p>Functional parameters can have default values. It is set by appending = to the type.</p><pre>fun calc(<br>    age: Int = 0,<br>    len: Int = b.size,<br>) { /*...*/ }</pre><p><em>Note: Overriding methods always use the base method’s default parameter. When ovveriding a method that has default parameter values, the default parameter values must be ommitted from the signature.</em></p><pre>open class A {<br>    open fun foo(i: Int = 10) { /*...*/ }<br>}<br><br> class B : A() {<br>    override fun foo(i: Int) { /*...*/ }  // No default value is allowed.<br>}<br></pre><p>The <a href="https://amitshekhar.me/blog/open-keyword-in-kotlin">open keyword</a> with the class means the class is open for the extension meaning that we can create a subclass of that open class.</p><p><strong>Return Values<br></strong>To return a value from a function we used the keyword <strong>return</strong> and specify the return type after the functionL parenthesis.</p><pre>fun myFunction(x: Int): Int {<br>  return (x + 5)<br>}<br><br>fun main() {<br>  var result = myFunction(3)<br>  println(result)<br>}</pre><p>You can use the = operator instead of return without specifying a type</p><pre>fun myFunction(x: Int, y: Int) = x + y<br><br>fun main() {<br>  var result = myFunction(3, 5)<br>  println(result)<br>}</pre><h4>Inline Function</h4><p>It instructs the compiler to insert the complete body of the function wherever that function gets used in the code.<br>Adv: Function overhead does not occur.<br>When to use:</p><ul><li>When the function code is very small</li></ul><p>When not to use inline</p><ul><li>when the function code is large and called from so many places. It will be a bad idea since the code will be repeated again and again.</li></ul><pre>fun guide(){<br>  print(&quot;guide start&quot;)<br>teach()<br>print(&quot;guide end&quot;)<br>}<br><br>inline fun teach(){<br>print(&quot;teach&quot;)<br>}</pre><h4>Infix Function</h4><p>This function is called without any dot or parenthesis .</p><p>What makes an infix function</p><ul><li>Member function</li><li>Has single parameter</li><li>Is marked with infix keyword</li></ul><p>Example</p><p>Or method</p><h4>Operator Function</h4><p>This is a function which is declared with a special keyword operator and are not different from regular functions when called via function calls.</p><p>It allows instance of a class to be called as if they were functions.</p><p>The invoke function is invoked when you use the parenthesis () syntax as the object of the class . <a href="https://kotlinlang.org/spec/operator-overloading.html#:~:text=Operator%20functions%20are%20function%20which,used%20in%20definition%20by%20convention.">Reference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36e13f0dadb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lists in Compose]]></title>
            <link>https://mercyjemosop.medium.com/lists-in-compose-7260c14c4ba2?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7260c14c4ba2</guid>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 18:33:13 GMT</pubDate>
            <atom:updated>2024-01-10T18:33:13.570Z</atom:updated>
            <content:encoded><![CDATA[<p>LazyColumn,LazyRow,FlowLayouts</p><h4>Introduction</h4><p>In this tutorial we will cover LazyColumn,LazyRow,FlowLayouts which are used to effectively display a collection of items.</p><h4>Lazy List</h4><p>They are used to display a large number of items or items whose length is undefined. Using layout like column to display such a list can cause <strong><em>performance issues</em></strong> because all <strong><em>items will be composed and laid out whether or not they are visible.</em></strong></p><p>Lazy componets differ from other components because it provides a <strong>LazyListScope()</strong> block. Which offer a DSL(Domain Specific Language) which allows apps to describe the item contents. The lazy component is then responsible for adding each item’s content as required by the layout and scroll position.</p><p>LazyListScope provides a number of functions for describing items in the layout.</p><ul><li>items() adds a single item.</li></ul><pre>LazyColumn {<br>    // Add a single item<br>    item {<br>        Text(text = &quot;One item&quot;)<br>    }<br>}</pre><ul><li>items(Int) adds multiple items.</li></ul><pre>LazyColumn {<br><br>    // Add 5 items<br>    items(5) { index -&gt;<br>        Text(text = &quot;multiple Items: $index&quot;)<br>    }<br>}</pre><ul><li>itemIndexed() which provides the index.</li></ul><p>The lazy list component include:</p><ul><li><strong>LazyColumns</strong> produce a vertically scrolling list.</li><li><strong>LazyRow</strong> produces horizontally scrolling list.</li></ul><h4>Flow Layout</h4><p><strong>FlowRows</strong> and <strong>FlowColums</strong> are composables similar to Column and Row. They are used to build responsive layouts (contents will not be cut off if items are too large for one dimention).</p><p>The difference is<strong> items flow into the next line when container runs out of space</strong> which creates multiple rows or columns.</p><p><strong>maxItemsInEachRow</strong> or <strong>maxItemsInEachColumn</strong> controlls the number of items.</p><pre>@Composable<br>private fun FlowRowSimpleUsageExample() {<br>    FlowRow(modifier = Modifier.padding(8.dp)) {<br>        ChipItem(&quot;Price: High to Low&quot;)<br>        ChipItem(&quot;Avg rating: 4+&quot;)<br>        ChipItem(&quot;Free breakfast&quot;)<br>        ChipItem(&quot;Free cancellation&quot;)<br>        ChipItem(&quot;£50 pn&quot;)<br>    }<br>}</pre><p>Items automatically flow to the next row when there is no more space in the first row.</p><p><a href="https://developer.android.com/jetpack/compose/layouts/flow">learn more</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7260c14c4ba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Conditions and Loops]]></title>
            <link>https://mercyjemosop.medium.com/kotlin-conditions-and-loops-e8c0f9b639fb?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c0f9b639fb</guid>
            <category><![CDATA[boolean]]></category>
            <category><![CDATA[if-else]]></category>
            <category><![CDATA[when]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[while-loop]]></category>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 17:49:30 GMT</pubDate>
            <atom:updated>2023-11-15T17:49:30.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Boolean, While loops, If…Else, when, while loop</p><h4>Introduction</h4><p>Hello, this tutorial will cover Boolean, while loops, if…else statements, when and while loops.</p><p>Terms used in this blog</p><p><strong><em>Operand </em></strong>is a term used to refer to a value or expression used to perform an operation.</p><p><strong>Expression</strong> is a combination of values, variables, operators and function calls that evaluates to a single result. It is used to :</p><ul><li>assign values to a variable</li><li>Passing arguments to functions</li><li>Performing calculations</li></ul><pre>// Expression<br>  val day = &quot;Tuesday&quot;<br>    val result = when (day) {<br>        &quot;Monday&quot; -&gt; println(&quot;Happy Monday!&quot;)<br>        &quot;Tuesday&quot; -&gt; println(&quot;It&#39;s Tuesday!&quot;)<br>        else -&gt; println(&quot;Have a great day!&quot;)<br>    }<br>    println(result)<br>//output<br>It&#39;s Tuesday!</pre><p><strong>Statement </strong>is a complete instruction that instructs the program to perform an action. It does not evaluate to a value and does not produce direct results. It is used to:</p><ul><li>Control the program flow</li><li>Alter data</li><li>Perform operations</li></ul><pre>val day = &quot;Monday&quot;<br>when (day) {<br>  &quot;Monday&quot; -&gt; println(&quot;Happy Monday!&quot;)<br>  &quot;Tuesday&quot; -&gt; println(&quot;Have a great day!&quot;)<br>  &quot;Wednesday&quot; -&gt; println(&quot;Hump day!&quot;)<br>  else -&gt; println(&quot;Have a nice weekend!&quot;)<br>}<br>//output<br>Happy Monday!<br></pre><p><strong>Boolean</strong></p><p>This is a data type which represents objects that have two values: <em>true or false</em>, <em>yes or no</em>, <em>on or off</em> . It’s nullable counterpart is represented using <strong><em>Boolean? </em></strong>which has a null value.</p><pre>//nullable boolean<br>val isTrue: Boolean? = null<br>//output<br>null</pre><p><em>Boolean built in operations</em>:</p><ul><li>| | which is disjunction (logical OR)</li></ul><p>It returns true if any of the given condition is true</p><pre>val isRaining: Boolean = true<br>val isCloudy: Boolean = false<br>print(isRaining || isCloudy)<br>//output<br>true</pre><ul><li>&amp;&amp; which is conjunction (logical AND)</li></ul><p>It returns true if both values are true otherwise false</p><pre>print(isRaining &amp;&amp; isCloudy)<br>//output<br>false</pre><ul><li>! which is negation ( logical Not)</li></ul><p>It reverses the value of a Boolean operand</p><pre>print(!isRaining) //true<br>print(!isCloudy)//false<br>// output<br>false<br>true</pre><p><strong>Kotlin If…Else</strong></p><p>This statements are used to execute both the true parts and false parts of a given condition.</p><p>If condition is <strong>true</strong>, the <strong><em>if</em></strong> block of code is executed and if condition is <strong>false</strong> the <strong><em>Else </em></strong>part is executed.</p><pre>if(condition){<br>  // block of code to be executed if the condition is true<br>}else {<br>  // block of code to be executed if the condition is false<br>}<br><br><br>if(2&gt; 3){<br>   print(&quot;True&quot;)<br> }else{<br>   print(&quot;false&quot;)<br> }<br>//output<br> false</pre><p><strong><em>Else if </em></strong>condition is used to specify a new condition. We use this when we need to perform multiple test or check multiple conditions.</p><pre>if (condition1) {<br>  // block of code to be executed if condition1 is true<br>} else if (condition2) {<br>  // block of code to be executed if the condition1 is false and condition2 is true<br>} else {<br>  // block of code to be executed if the condition1 is false and condition2 is false<br>}<br><br>example<br> if (2 &gt; 3) {<br>        print(&quot;Condition1 True&quot;)<br>    } else if (3 &gt; 2) {<br>        print(&quot;Condition2  True &quot;)<br>    } else {<br>        print(&quot;false&quot;)<br>    }<br>//output<br>Condition2  True </pre><p><strong><em>Note: </em></strong>You can omit the curly braces <strong>{}</strong> when if has only one statement</p><pre>if(2&lt;3) print(&quot;Condition  True &quot;) else print(&quot;Condition  false &quot;)<br>//output<br>Condition  True </pre><p><strong><em>Logical conditions supported by kotlin</em></strong></p><pre>Less than if(2 &lt; 3)<br>Less than  or equal to if(2 &lt;= 3)<br>Greater than if(2 &gt; 3)<br>Greater than or equal to if(2 &gt;= 3)<br>Equal to if(2 == 3)<br>Not Equal to if( 2 != 3)</pre><p><strong><em>Kotlin when</em></strong></p><p>Defines a conditional expression with <strong>multiple branches</strong>. It is used instead of if…else because it is easy to read. It selects on of many block of code to be executed. It is similar to switch statement in java.</p><p><strong>when </strong>matches its argument against all branches sequentially until some branch condition is satisfied. when can be used as an <strong><em>expression</em></strong> or a <strong><em>statement</em></strong>.</p><p>Each branch starts with a value followed by an arrow (-&gt;) and a result.</p><pre>1 -&gt; &quot;Condition is true&quot;</pre><p>If it used as an <strong>expression</strong>, the value of the first matching branch becomes the value of the overall expression.</p><pre>// Expression<br>val result = when (dayOfWeek) {<br>    &quot;Monday&quot; -&gt; println(&quot;Happy Monday!&quot;)<br>    &quot;Tuesday&quot; -&gt; println(&quot;It&#39;s Tuesday!&quot;)<br>    else -&gt; println(&quot;Have a great day!&quot;)<br>}<br>println(message) // Output: 2</pre><p>The <strong><em>else </em></strong>branch is evaluated if none of the other branch conditions are satisfied.</p><p>Note: if <strong>when</strong> is used as an expression the else branch is mandatory unless the compiler can prove that all possible cases are covered with branch conditions :</p><p><strong>enum </strong>class entries and <strong>sealed</strong> class subtypes</p><pre>enum class Bit {<br>    ZERO, ONE<br>}<br><br>val numericValue = when (getRandomBit()) {<br>    Bit.ZERO -&gt; 0<br>    Bit.ONE -&gt; 1<br>    // &#39;else&#39; is not required because all cases are covered<br>}</pre><p><strong>sealed</strong> class is a class that is marked with a <strong>sealed</strong> <strong>keyword. </strong>It is used to define a closed set of subclasses. They are used to <strong>restrict users</strong> from inheriting that class. It is similar to enum classes.</p><pre>sealed interface Error<br><br>sealed class IOError(): Error<br><br>class FileReadError(val file: File): IOError()<br>class DatabaseError(val source: DataSource): IOError()<br><br>object RuntimeError : Error<br><br>fun log(e: Error) = when(e) {<br>    is FileReadError -&gt; { println(&quot;Error while reading file ${e.file}&quot;) }<br>    is DatabaseError -&gt; { println(&quot;Error while reading from database ${e.source}&quot;) }<br>    is RuntimeError -&gt;  { println(&quot;Runtime error&quot;) }<br>    // the `else` clause is not required because all the cases are covered<br>}</pre><p>statement</p><pre>enum class Color {<br>    RED, GREEN, BLUE<br>}<br><br>when (getColor()) {<br>    Color.RED -&gt; println(&quot;red&quot;)<br>    Color.GREEN -&gt; println(&quot;green&quot;)<br>    Color.BLUE -&gt; println(&quot;blue&quot;)<br>    // &#39;else&#39; is not required because all cases are covered<br>}<br><br>when (getColor()) {<br>    Color.RED -&gt; println(&quot;red&quot;) // no branches for GREEN and BLUE<br>    else -&gt; println(&quot;not red&quot;) // &#39;else&#39; is required<br>}</pre><h4>Kotlin While Loop</h4><p><strong>While </strong>and <strong>do-while</strong> loops execute their body continuously while their condition is satisfied.</p><p><strong><em>while loop</em></strong><em> </em>checks the condition and if it’s satisfied, executes the body and then returns to the condition check.</p><pre>var x=4 <br>while (x &gt; 0) {<br>    x--<br>    print(x)<br>}<br>//output<br>3210</pre><p><strong><em>do-while loop</em></strong> executes the body and then checks the condition. if it’s satisfied, the loop repeats.</p><pre>    do {<br>        x--<br>        print(x)<br>    } while (x &gt; 0)<br>//output<br>3210</pre><p>Resources:</p><p><a href="https://kotlinlang.org/docs/control-flow.html#break-and-continue-in-loops">Kotlin documentation</a></p><p><a href="https://www.w3schools.com/kotlin/kotlin_while_loop.php">W3school</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c0f9b639fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Data Types]]></title>
            <link>https://mercyjemosop.medium.com/kotlin-data-types-576e668d939a?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/576e668d939a</guid>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[basics-of-programming]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 18:29:08 GMT</pubDate>
            <atom:updated>2023-11-01T18:29:08.155Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Types</p><h4>Introduction</h4><p><em>Data type</em> is a type of value a variable has.</p><p><em>Variable</em> is a container that stores a data value e.g val name =”Mercy’’, in this example name is a variable and “mercy” is a value.</p><p><em>Importance</em></p><ul><li>Ensures that the data collected is in the preferred format.</li><li>The value is as expected.</li><li>Gather clean and consistent data</li></ul><p><em>Kotlin Data Types</em></p><ol><li>Number :</li></ol><p><em>a. Integer types store</em> whole numbers without a decimal, they number can be negative or positive.</p><p>example:</p><p><em>Byte </em>stores whole numbers from -128 to 127, it can be used in place of int to save memory when you are certain of the value</p><pre>val myNum: Byte = 100</pre><p><em>Short </em>stores whole numbers from -32768 to 32767</p><pre>val myNum: Short = 5000</pre><p><em>Int </em>stores whole numbers between -2147483648 to 2147483647</p><pre>val myNum: Int = 100000</pre><p><em>Long </em>stores whole numbers between -9223372036854775807 to 9223372036854775807. You can optionally end the value with an “L”</p><pre>val myNum: Long = 15000000000L</pre><p><em>b. Floating point types,</em> these are numbers containing decimals.</p><p><em>Float </em>its precision is only six/seven decimal digits. it can be a scientific number with an “e” or “E” to indicate the power of 10. e.g val myNum1: Float = 35E3F</p><pre>val myNum: Float = 5.75F<br>val myNum1: Float = 35E3F<br>//is the same as<br>35000.0</pre><p><em>Double </em>has a precision of about 15 digits.</p><pre>val myNum2: Double = 12E4</pre><p>2. <em>Booleans</em></p><p>It only takes true or false value.</p><pre>val isValid: Boolean = true</pre><p>3. <em>Characters</em></p><p>It is used to store a single character. It is surrounded by single quotes like ‘A’.</p><pre>val grade: Char = &#39;B&#39;</pre><p>4. <em>Strings</em></p><p>It is used to store sequence of characters. It must be surrounded by double quotes.</p><pre>val hello: String = &quot;Hello World&quot;</pre><p><em>Multiline strings</em></p><pre>val text = &quot;&quot;&quot;<br>    for (c in &quot;foo&quot;)<br>        print(c)<br>&quot;&quot;&quot;</pre><p>5. <em>Arrays</em></p><p>They are used to store multiple values in a single character. It is a data structure that holds a fixed number of values of the same type or its subtype.</p><pre>var riversArray = arrayOf(&quot;Nile&quot;, &quot;Amazon&quot;, &quot;Yangtze&quot;)</pre><p>Access element in an array</p><pre>println(riversArray[0])</pre><p>Change an Array Element</p><pre>riversArray[0] = &quot;Opel&quot;</pre><p>Array Length / Size</p><pre>println(riversArray.size)</pre><p>Check if an Element Exists in an array, you can use the <strong><em>in </em></strong>operator to check if an element exist in an array.</p><pre>if (&quot;Opel&quot; in riversArray) {<br>  println(&quot;It exists!&quot;)<br>}</pre><p>Loop Through an Array</p><pre>val riversArray= arrayOf(&quot;Volvo&quot;, &quot;BMW&quot;, &quot;Ford&quot;, &quot;Mazda&quot;)<br>for (x in riversArray) {<br>  println(x)<br>}</pre><p>Sources:</p><ul><li><a href="https://www.w3schools.com/kotlin/kotlin_arrays.php">Kotlin Arrays</a></li><li><a href="https://kotlinlang.org/docs/basic-types.html">Basic types | Kotlin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=576e668d939a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHP Basics on Ubuntu]]></title>
            <link>https://mercyjemosop.medium.com/php-basics-8b3159fc60ae?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b3159fc60ae</guid>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[xampp]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 10:15:12 GMT</pubDate>
            <atom:updated>2023-01-16T10:28:30.655Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction to PHP</p><h4>Introduction</h4><p><strong>PHP</strong> stands for Hypertext Preprocessor. It is a general-purpose scripting language that is especially suited to web development.</p><p><strong>PHP tags, </strong>when PHP parses a file it looks for an opening and closing tags &lt;?php and ?&gt;. These tags will tell PHP to start and stop interpreting the code between them.</p><p><strong>Parsing</strong> in programming means analyzing and converting a program into an internal format that a runtime environment can actually run.</p><p><strong>N.B Install </strong><a href="https://www.w3schools.com/php/php_install.asp"><strong>PHP</strong></a><strong>, </strong><a href="https://phoenixnap.com/kb/how-to-install-xampp-on-ubuntu"><strong>Xampp</strong></a></p><p>Check the PHP version to verify it is installed on your computer.</p><pre>php --version</pre><p>Check if Xampp is installed</p><p>Open Xampp, start the server you need, in this case I started all. To check the server port. Click the configure button on the right, a pop up with the port will show.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*wp50YGB7pRm_2Npk4RNfZQ.png" /></figure><p>To open xampp, type the command below on your browser, 80 is my xampp port. You open Xampp dashboard on your browser using the command below. It will redirect to <a href="http://localhost/dashboard/">http://localhost/dashboard/</a> or you can just run <a href="http://localhost/dashboard/">localhost/dashboard/</a></p><pre>localhost:80</pre><p>If you have not given htdocs directory permission in Xampp. Run the command below to be able to create a project in htdocs. In Ubuntu, Xampp was installed in <strong>/opt/lampp/. </strong>Navigate to that path and run the command below to be able to create a project inside htdocs.</p><pre>sudo chmod 777 -R htdocs</pre><p><strong>Create a PHP Project</strong></p><p>In windows</p><p>1. Navigate to the C directory</p><p>2. Search for Xampp folder, navigate to htdocs inside xampp</p><p>3. Create your project inside htdocs</p><p>4. open your project using vscode, sublimetext or any editor</p><p>In Ubuntu</p><ol><li>Navigate to htdocs directory</li></ol><pre>cd opt/lampp/htdocs</pre><p>2. To open that directory type the command below on your path above. You will get a pop up of the contents of htdocs directory</p><pre>nautilus .</pre><p>3. Create a folder/ directory i.e hello_php</p><p>4. Open the project in vscode by right clicking on the folder you created and using open with option. You can also use any other method which will work for you.</p><p><strong>Let’s start by displaying “hello world”</strong></p><ol><li>Create a file e.g index.php, inside the folder you created above</li><li>From our intro, php code should have both closing and opening tags. We will use “echo” to display the text.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/777256fbe0c0422dd56a3b5657501a12/href">https://medium.com/media/777256fbe0c0422dd56a3b5657501a12/href</a></iframe><p>3. To check the changes on the browser</p><p><a href="http://localhost/php_crud/hello_world_php/index.php">http://localhost/hello_php/index.php</a></p><p>4. You will get the text above in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*5Sqh15vPYUbbBez_mp9tVQ.png" /></figure><p><strong>Congratulations!!!!!!!. If you have not reached this part, go over your steps and research on where you might have gone wrong.</strong></p><h4>Database Connection</h4><p>Navigate to the dashboard by typing <a href="http://localhost/dashboard/">http://localhost/dashboard/</a> on your browser. You should see the page below. Click phpMyAdmin or You can just search <a href="http://localhost/phpmyadmin/">http://localhost/phpmyadmin/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZ84FGMuuXNUI9sClhoDxg.png" /></figure><p>Database Structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWg_bdfhAhbyHY9OpBVgkw.png" /></figure><p>Create a database by clicking new and adding the database name. I created a database called <strong>school .</strong> You can give your database a different name.</p><p>Connect with database using PHP</p><pre>#Your database credentials, my username and password are the default<br>#You can change the username and password, change the database name to match<br>#the one you created<br><br>$servername = &quot;localhost&quot;;<br>$username = &quot;root&quot;;<br>$password = &quot;&quot;;<br>$dbname = &quot;school&quot;;</pre><p>Create a new connection to Database/MySQL server</p><pre>$conn = mysqli_connect($servername, $username, $password,$dbname);</pre><p>Check server connection and display error on success</p><pre>// Check connection<br>if (mysqli_connect_error()) {<br>      die(&quot;Database connection failed: &quot; . mysqli_connect_error());<br>}<br>echo &quot;Connected successfully&quot;;</pre><p>Complete code</p><p>Create a database_connection.php</p><pre>&lt;?php<br><br>$servername = &quot;localhost&quot;;<br>$username = &quot;root&quot;;<br>$password = &quot;&quot;;<br>$dbname = &quot;school&quot;;<br><br>// Create connection<br>$conn = mysqli_connect($servername, $username, $password,$dbname);<br><br>// Check connection<br>if (mysqli_connect_error()) {<br>      die(&quot;Database connection failed: &quot; . mysqli_connect_error());<br>}<br>echo &quot;Connected successfully \n&quot;;<br>    $conn-&gt;close();<br>?&gt; </pre><p>Include the file database_connection.php in index.php</p><pre>&lt;?php<br>include(&quot;database_connection.php&quot;);<br>echo &quot;Hello World&quot;;<br>?&gt; </pre><p>Restart your browser and you will get the text below</p><pre>Connected successfully Hello World </pre><h4>Insert Data into a table in the Database</h4><ol><li>Create a table inside the school(your DB ), my table name is “school”</li><li>I have two fields: id, auto-increment and name.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzfgdOq40J92XRbUTFHLjQ.png" /></figure><p><strong>Insert data into student table</strong></p><p>Create a file named save_student.php</p><ol><li>Add headers to the file</li></ol><p><strong>The header()</strong> function sends a raw HTTP header to a client. It is declared before any actual output is sent</p><p>syntax</p><p>header(<em>header</em>, <em>replace</em>, <em>http_response_code</em>)</p><pre>  header(&#39;Content-Type: application/json&#39;);<br>  header(&#39;Access-Control-Allow-Origin: *&#39;);<br>  header(&#39;Access-Control-Allow-Methods: POST&#39;);<br>  header(&#39;Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With&#39;);$data = json_decode(file_get_contents(&quot;php://input&quot;), true);</pre><p><strong>json_decode()</strong> function is used to decode or convert a JSON object to a PHP object.</p><p><strong>file_get_contents</strong> — Reads entire file into a string.</p><p>Insert the data into the student table, student_name field using the sql query.</p><pre>$data = json_decode(file_get_contents(&quot;php://input&quot;), true);    $sname = $data[&#39;student_name&#39;];<br>    include &#39;database_connection.php&#39;;<br> $sql = &quot;insert into student (student_name) values (&#39;$sname&#39;)&quot;;</pre><p><strong>The include</strong> or <strong>require </strong>statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.</p><pre>    $sname = $data[&#39;student_name&#39;];<br>    include &#39;database_connection.php&#39;;<br>    $sql = &quot;insert into student (student_name) values (&#39;$sname&#39;)&quot;;</pre><p>Complete save_student.php</p><pre>&lt;?php<br>    header(&#39;Content-Type: application/json&#39;);<br>    header(&#39;Access-Control-Allow-Origin: *&#39;);<br>    header(&#39;Access-Control-Allow-Methods: POST&#39;);<br>    header(&#39;Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With&#39;);<br><br>    $data = json_decode(file_get_contents(&quot;php://input&quot;), true);<br><br>    $sname = $data[&#39;student_name&#39;];<br><br>    include &#39;database_connection.php&#39;;<br><br>    $sql = &quot;insert into student (student_name) values (&#39;$sname&#39;)&quot;;<br><br>    if (mysqli_query($conn, $sql)) {<br>        echo json_encode([&#39;msg&#39; =&gt; &#39;Data Inserted Successfully!&#39;, &#39;status&#39; =&gt; true]);<br>      } else {<br>        echo json_encode([&#39;msg&#39; =&gt; &#39;Data Failed to be Inserted!&#39;, &#39;status&#39; =&gt; false]);<br>      }<br>?&gt;</pre><h4>Test the data using postman</h4><p>Postman is <strong>an API(application programming interface) development tool which helps to build, test and modify APIs</strong>. Almost any functionality that could be needed by any developer is encapsulated in this tool. It is used by over 5 million developers every month to make their API development easy and simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gl5hmmnpTDCZaCXT3V5QeA.png" /></figure><h4>Update Username</h4><p>Create a file named update_student.php</p><p>When updating data in the database, we use the update sql statement, find the id of the record you need to update and set the field you need to change to the new field.</p><pre>&lt;?php<br> header(&#39;Content-Type: application/json&#39;);<br> header(&#39;Access-Control-Allow-Origin: *&#39;);<br> header(&#39;Access-Control-Allow-Methods: PUT&#39;);<br> header(&#39;Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With&#39;);<br><br> $data = json_decode(file_get_contents(&quot;php://input&quot;), true);<br><br> $sname = $data[&#39;student_name&#39;];<br> $sid = $data[&#39;id&#39;];<br><br> include &#39;database_connection.php&#39;;<br> <br> $sql = &quot;update student set student_name = &#39;$sname&#39; where id = &#39;$sid&#39;&quot;;<br><br> if (mysqli_query($conn, $sql)) {<br>    echo json_encode([&#39;msg&#39; =&gt; &#39;Data Updated Successfully!&#39;, &#39;status&#39; =&gt; true]);<br>  } else {<br>    echo json_encode([&#39;msg&#39; =&gt; &#39;Data Failed to be Updated!&#39;, &#39;status&#39; =&gt; false]);<br>  }<br>?&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6Y5zzpqo3ifPs9B-6FDzg.png" /></figure><p><strong>Fetch Records from Database</strong></p><p>You can get a list of all students or search a student by name</p><pre>// header(&#39;Content-Type: application/json&#39;);<br>header(&#39;Access-Control-Allow-Origin: *&#39;);<br>header(&#39;Access-Control-Allow-Methods: GET&#39;);<br><br>$data = json_decode(file_get_contents(&quot;php://input&quot;), true);<br><br>$searchterm = $data[&#39;student_name&#39;];<br><br>include &#39;database_connection.php&#39;;<br><br>$sql = &quot;select * from student where student_name like &#39;%$searchterm%&#39;&quot;;<br><br>$result = mysqli_query($conn, $sql);<br><br>if (mysqli_num_rows($result) &gt; 0) {<br>  $data = mysqli_fetch_all($result, MYSQLI_ASSOC);<br>  echo json_encode($data);<br>} else {  <br>  echo json_encode([&#39;msg&#39; =&gt; &#39;No Data Found to search query!&#39;, &#39;status&#39; =&gt; false]);<br>}</pre><p>postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYt41KcaTMaJaoMQn2xltA.png" /></figure><p><strong>Delete Student</strong></p><pre>&lt;?php<br>header(&#39;Content-Type: application/json&#39;);<br>header(&#39;Access-Control-Allow-Origin: *&#39;);<br>header(&#39;Access-Control-Allow-Methods: DELETE&#39;);<br>header(&#39;Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With&#39;);<br><br>$data = json_decode(file_get_contents(&quot;php://input&quot;), true);<br><br>$sid = $data[&#39;id&#39;];<br><br>include &#39;database_connection.php&#39;;<br><br>$sql = &quot;delete from student where id = &#39;$sid&#39;&quot;;<br><br>if (mysqli_query($conn, $sql)) {<br>echo json_encode([&#39;msg&#39; =&gt; &#39;Data Deleted Successfully!&#39;, &#39;status&#39; =&gt; true]);<br>} else {<br>  echo json_encode([&#39;msg&#39; =&gt; &#39;Data Failed to be Deleted!&#39;, &#39;status&#39; =&gt; false]);<br>}<br>?&gt;</pre><p>I hope this article has helped you get a basic grasp of PHP and MySQL connection. You can pass the endpoint to react, vue or the UI you need to integrate and do more practice.</p><p>Happy coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1</p><p>Sources: <a href="https://www.w3schools.com/php/php_includes.asp">w3school</a>, <a href="https://beproblemsolver.com/develop-an-api-with-php-json-and-postman/">beproblemsolver</a>, <a href="https://www.youtube.com/watch?v=ExW0bYNMTlo">youtube</a></p><p>Github:<a href="https://github.com/mercykip/hello_world_php"> hello_php</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b3159fc60ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TREES DATA STRUCTURES]]></title>
            <link>https://mercyjemosop.medium.com/trees-data-structures-a2e900477695?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e900477695</guid>
            <category><![CDATA[binary-search-tree]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[binary-search-algorithm]]></category>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Mon, 26 Sep 2022 07:59:42 GMT</pubDate>
            <atom:updated>2022-09-26T08:00:21.470Z</atom:updated>
            <content:encoded><![CDATA[<p>Basic overview of trees in data structures</p><h4><strong>Introduction</strong></h4><p>A <strong>tree</strong> is a<strong> non-linear </strong>and <strong>hierarchical</strong> data structure consisting of a collection of nodes such that each node of the trees stores a value and a list of reference to other nodes. Data in a tree is stored in a hierarchical structure.</p><p><strong>Tree structure</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*fmZbybATXPKSzRIUsDM1uA.png" /></figure><p><strong>Node</strong> is an entity that contains a value/key and pointers to its <strong>child nodes</strong> (A, B, C, D, E, F, G), the last nodes of each path are called the <strong>leaf/external </strong>nodes(D, E, F, G). <strong>Edge</strong> of a tree is the link between two nodes.</p><p><strong>Parent node </strong>is a node which is the predecessor of a node(B,C) while a <strong>child node</strong> is the immediate successor of the node(D,E).</p><p><strong>Root node</strong> top most node of a tree which does not have any parent(A), a non-empty tree must contain exactly one root node.</p><p><strong>Sub-Tree</strong> is any node of a tree along with its descendants.</p><h4>Important properties of a tree</h4><ul><li>Traversing a tree is done by depth first search and breadth first search.</li><li>its hierarchical model.</li><li>it has no loop or circuit.</li></ul><h4>Basic tree operation</h4><p>Create a tree, insert data, search specific data in a tree, traveling a tree(pre-order, post-order, in-order).</p><p><strong>Types of tree data structures</strong></p><ul><li><strong>Binary Search Tree </strong>are used for various searching and sorting algorithms. It shows that the value of the left node is less that its parent while the value of the right node is greater than the parent.</li><li><strong>Binary tree </strong>node has a maximum of two child nodes.</li><li><strong>General tree</strong> has no restrictions in the number of nodes, parent nodes can have many child nodes.</li><li><strong>Balanced tree</strong> is one which the height of the left sub-tree and the right sub-tree is equal or differs by 1 .</li></ul><p><strong>Application of trees</strong></p><ul><li>It is the shortest path tree used in the routers to direct the packets to the destination(Spanning tree)</li><li>Binary search</li><li>Storing hierarchical data.</li></ul><h3>Tree Traversal</h3><p>There are three ways of traversing a binary tree.</p><ul><li>In-Order Traversal</li><li>Pre-Order Traversal</li><li>Post-Order Traversal</li></ul><h4>In-order Traversal (Left, Root, Right)</h4><p>In the In-order tree traversal, we traverse a binary tree by first visiting all the nodes in the left sub-tree and then the root node and finally the right sub-tree of the tree.(L, RT, R).</p><p>Left sub-tree -&gt;root -&gt;right sub-tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*dEDWlNA-b6WJPiRtJvQk8Q.png" /></figure><ul><li>Starting from the left -sub tree from the root, 1(L), 2(Rt),3(R)</li><li>Then go to the root 4(RT).</li><li>Finally Right sub-tree X(L), 5(RT),6(R). X means there is nothing on the left side of the right sub-tree</li></ul><p>After traversing all the elements in the tree we get the in order traversal as:</p><p>1 -&gt; 2 -&gt;3 -&gt;4 -&gt;5 -&gt;6</p><p>Representation in a <strong>stack</strong> which is a linear data structure that follows the principles of Last In first Out(LIFO). The last element inserted into the stack will be removed first. We don’t have to create the stack ourselves because recursion maintains the correct order for us.</p><pre>inorder(root-&gt;left)<br>display(root-&gt;data)<br>inorder(root-&gt;right)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*D_fY2Vl5ssjdwV9a8rOiEg.png" /></figure><p><a href="https://github.com/mercykip/JavaFundermentals/blob/main/src/main/java/com/example/JavaFundermentals/JavaFundermentals/traversal/InOrder.java">github link</a> for the inorder class and <a href="https://github.com/mercykip/JavaFundermentals/blob/main/src/main/java/com/example/JavaFundermentals/JavaFundermentals/trees/Node.java">node class</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*OIV8_hWd7F-0IxiS4C5WKA.png" /></figure><h4>Preorder traversal(RT, L, R)</h4><p>In the pre-order tree traversal, we first visit the root node, then the left sub tree from the root and finally right sub tree.</p><pre>display(root-&gt;data)<br>preorder(root-&gt;left)<br>preorder(root-&gt;right)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*dEDWlNA-b6WJPiRtJvQk8Q.png" /></figure><ul><li>Starting from the root 4(RT).</li><li>Move to the left sub tree, start again from the root 2(RT), 1(L), 3(R)</li><li>Move to the right sub tree, start from the root 5(RT), x(L),6(R). X means no element, you don’t need to insert the x, you can leave it out but I have added it to indicate there is no value in the left side of the right sub tree.</li></ul><p>4(RT), 2(RT),1(L),3(R),5(RT),6(R)</p><p>After traversing all the elements in the tree we get the pre-order traversal as:</p><p>4-&gt; 2-&gt; 1 -&gt;3 -&gt;5 -&gt;6</p><p><a href="https://github.com/mercykip/JavaFundermentals/blob/main/src/main/java/com/example/JavaFundermentals/JavaFundermentals/traversal/PreOrder.java">Pre- order github link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*cb17voAgpXCk0XbHx_fO0Q.png" /></figure><p><a href="https://github.com/mercykip/JavaFundermentals/blob/main/src/main/java/com/example/JavaFundermentals/JavaFundermentals/trees/Node.java">node class</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*OIV8_hWd7F-0IxiS4C5WKA.png" /></figure><h4><strong>Post Order Traversal(L,R,RT)</strong></h4><p>In the post-order tree traversal, we first visit all the nodes in the left sub-tree, then all the nodes in the right sub tree and finally the root node.</p><pre>postorder(root-&gt;left)<br>postorder(root-&gt;right)<br>display(root-&gt;data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*dEDWlNA-b6WJPiRtJvQk8Q.png" /></figure><ul><li>Starting from the left sub tree, traverse all the nodes (L, R, RT), 1(L), 3(R), 2(RT)</li><li>Move to the right sub tree x(L), 6(R), 5(RT)</li><li>Finally the root node 4(RT)</li></ul><p>1(L), 3(R), 2(RT),x(L), 6(R), 5(RT), 4(RT)</p><p>After traversing all the elements in the tree we get the post-order traversal as:</p><p>1-&gt;3 -&gt;2 -&gt;6 -&gt;5 -&gt;4</p><p><a href="https://github.com/mercykip/JavaFundermentals/blob/main/src/main/java/com/example/JavaFundermentals/JavaFundermentals/traversal/PostOrder.java">github code link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*CxGhsA9DD1PS8_O6iUiWcQ.png" /></figure><p><a href="https://github.com/mercykip/JavaFundermentals/blob/main/src/main/java/com/example/JavaFundermentals/JavaFundermentals/trees/Node.java">Node class link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*OIV8_hWd7F-0IxiS4C5WKA.png" /></figure><h4>Binary Search Tree(BST)</h4><p>A binary search tree is a data structure that quickly allows you to maintain a sorted list of numbers. It is used to search for the presence of a number in O(log(n)) time complexity. It is a binary tree because each tree node has a maximum of two children nodes.</p><p><strong>Properties</strong></p><ul><li>The left sub-tree of a node contains only nodes with keys lesser than the node’s key.</li><li>The right sub-tree of a node contains only nodes with keys greater than the node’s key.</li><li>The left and right sub-tree must also be a binary search tree.</li></ul><h4>Operation in a binary search tree</h4><ol><li>Insertion</li><li>Deletion</li><li>Search</li></ol><h4>Search Operation in BST BreakDown</h4><ul><li>Read the search element/item/number</li><li>Compare the search element with the value of the root node in the tree.</li><li>If the values are matched, display “Node is found” and terminate the function.</li><li>if both are not matched, then check whether search element is smaller or larger than that node value.</li><li>If the search is smaller, then continue with the search process in the left sub-tree.</li><li>If the search is larger, then continue with the search process in the right sub-tree.</li><li>Repeat until you find the exact same element or until the search element is compared to the leaf node.</li><li>If we reach to the node having the value equal to the search value then display “Element is found” and terminate the function.</li><li>If we reach to the leaf node and if it is also not matched with the search element, then display “Element is not found” and terminate the function.</li></ul><p>The algorithm depends on the property of BST that if each left sub tree has value less than root and each right sub-tree has greater than the root. We can only search the left sub-tree if the value is less than the root.</p><p>Algorithm</p><pre>If root == NULL <br>    return NULL;<br>If number == root-&gt;data <br>    return root-&gt;data;<br>If number &lt; root-&gt;data <br>    return search(root-&gt;left)<br>If number &gt; root-&gt;data <br>    return search(root-&gt;right)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*T-Q9sgpU6Kb9p8HHN14RgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*SqTG-I1Kp1YpL76ToT_ZHw.png" /></figure><p>WIP:….</p><p><a href="https://www.youtube.com/playlist?list=PLIY8eNdw5tW_zX3OCzX7NJ8bL1p6pWfgG">youtube series</a></p><p><a href="https://neetcode.io/practice">practice</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e900477695" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Big O notation]]></title>
            <link>https://mercyjemosop.medium.com/the-big-o-notation-90231d4df774?source=rss-23a78fb7b7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/90231d4df774</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[searching-algorithm]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <dc:creator><![CDATA[Mercy Jemosop]]></dc:creator>
            <pubDate>Sun, 31 Jul 2022 11:16:30 GMT</pubDate>
            <atom:updated>2022-07-31T11:16:30.007Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding big O notation in Data Structures and Algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0UxVx3hvAvRm58KO-zSjA.png" /></figure><h4>Introduction</h4><p>There are several ways to solve a problem, to choose the best algorithm to use, we need to compare the performance of the different algorithms. Comparing the performance of an algorithm is achieved by measuring it’s space and time complexity.</p><p>we need to be conversant with the big O notation to be able to approach problems with least time and resources.</p><p><strong>Big O notation</strong> is a way of measuring an algorithm’s efficiency in terms of the time it takes to run your function as in out grows. N.B it does not tell you the speed of an algorithm in seconds rather by the number of operation they take.<strong>Big O (O())</strong> describes the <strong>upper bound</strong> of the complexity.</p><p>Two parts of measuring algorithm’s efficiency</p><ul><li><strong>Time Complexity </strong>is the amount of time taken by an algorithm to run with the change in size input.</li><li><strong>Space Complexity</strong> finds out how much (extra)space/memory will be required by an algorithm with change in input.</li><li><strong>Order of growth</strong> is how the time of execution depends on the length of the input which helps us compute the running time with ease.</li></ul><p>Common algorithms and their run time in big O notation. The algorithms are categorized in two:</p><p><strong><em>Sequential algorithm</em></strong> a list or array is traversed sequentially and every element is checked. Example Linear search</p><p><strong><em>Interval Search algorithms</em></strong> are specifically designed for searching in sorted data-structures.They are more effective than linear algorithms because they divide the search space in half and repeatedly target the center of the search structure. Example Binary Search</p><ul><li>O(log n) — Binary search.</li><li>O(n) —Linear search.</li><li>O(n * log n) — Quick sort.</li><li>O(n2) — Selection sort.</li><li>O(n!) — Traveling salesperson</li></ul><ol><li><em>Linear search (O(n))</em></li></ol><p>Iterating through a list of elements until you find element that you looking for. Let’s take an example of an array.</p><pre>int[] myArray = {1, 3, 5, 7, 9, 11, 13, 14, 15};</pre><p>This algorithm takes O(n) times to execute. Let’s assume you are searching for number 11 in the array ,in the worst case you will have to search through every single number in the array(n times) where n is the number of elements in the list, the best case will be when the number 11 is the first element in the array O(1).</p><p>O(1) is the best scenario but big O notation focuses on the worst case O(n) for a linear search. The example above will take 6 iterations before number 6 is found.</p><p>Example</p><p>Given an array <strong>arr[] </strong>of <strong>N</strong> elements, the task is to write a function to search a given element <strong>x</strong> in<strong> arr[]</strong>. If <strong>x</strong> doesn’t match with any of the elements, return <strong>-1</strong>.</p><p>Steps to implement linear search</p><ul><li>Start from the leftmost element of <strong>arr[]</strong> and one by one compare <strong>x</strong> with each element of <strong>arr[]</strong></li><li>If <strong>x</strong> matches with an element, return the index.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def265f9122c9e3135db2f8a71627981/href">https://medium.com/media/def265f9122c9e3135db2f8a71627981/href</a></iframe><p>2. Binary Search (O(Log n))</p><p>This is a searching algorithm used in a sorted array by repeatedly dividing the search interval into half. It uses the information that the array is sorted and reduce the time complexity to O(Log n).</p><p>Steps to perform a binary search</p><ul><li>Begin with the mid element of the whole array as a search key.</li><li>If the value of the search key is equal to the item then return an index of the search key.</li><li>Or if the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.</li><li>Otherwise, narrow it to the upper half.</li><li>Repeatedly check from the second point until the value is found or the interval is empty.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AB663OnsIvz4MynUSW9PqQ.jpeg" /></figure><p>Given a sorted array <strong>arr[]</strong> of <strong>n</strong> elements, write a function to search a given element <strong>x</strong> in<strong> arr[] </strong>and return the index of x in the array</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5732c495ed87189119914eb9513b62f/href">https://medium.com/media/a5732c495ed87189119914eb9513b62f/href</a></iframe><p>3. Ternary Search (O(log3n))</p><p>This algorithm is similar to the binary search since it divides an array into sub-array. Ternary search splits/divide an array into three parts and determine which part has the search element. The array is divided into three parts using mid1 and mid2, where l=0 and r=n-1, n is the length of the array.</p><p>Ternary search time complexity:O(log3n) and space complexity is : O(1)</p><p><strong>N.B To perform a ternary search, you need a sorted array.</strong></p><p>To calculate mid1 and mid2 use the formula below:</p><p>mid1=l +(r-l)/3;</p><p>mid1=r -(r-l)/3;</p><p>Steps implement ternary search</p><ul><li>Compare the key with the element at mid1. If found equal, we return mid1.</li><li>If not found in step 1, then compare the key with the element at mid2. If found equal, we return mid2.</li><li>If not found in step 2, then check whether the key is less than the element at mid1. If yes, then recur to the first part.</li><li>If not, then we check whether the key is greater than the element at mid2. If yes, then recur to the third part.</li><li>If not, then we recur to the second (middle) part.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bp8mVfA3y5Qq076Afvk0Cg.jpeg" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dea10e2456810f32e22688f2da813a16/href">https://medium.com/media/dea10e2456810f32e22688f2da813a16/href</a></iframe><p>There are many other algorithms you can learn, checkout javatpoint, tutorialspoint, geekforgeeks etc for more resources.</p><p>Happy coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90231d4df774" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>