Get Familiar with solving Labs, Data Structures and Algorithms

Begin to get acquainted with JavaScript algorithm and data structures.3 min


Many new programmers encounter difficulties when trying to solve their first algorithm problem or creating programs that pass certain tests. Here is a detailed guide on how to crack the code and begin creating good programs.

Advertisements

IDEA

The idea behind creating functions and labs is such that the function would be used to achieve the same result for different cases of what you are asked to do. For instance, you are to create a program that greets the user, your program should be able to greet every user that is passed to it and not hardcoded.

HARDCODING AND WHY IT IS BAD

Hardcoding is usually when a programmer tries to code to pass a particular test using the cases from the example alone. This is usually done by beginners but we will attempt to deal with that today.

Example: Write a program that returns “Hello, User”, the user being the name of the person passed as an argument.

E.g: greet_user(“benjamin”); // hello, benjamin.

The new programmer would be aiming towards writing a code that returns benjamin and that is what hardcoding entails.

function greet_user(name){
   console.log("hello, "+ "benjamin");
}

This will print benjamin alright despite the name passed into it and yay! you will pass the test given in the example but this is a very bad way to code because we will keep getting benjamin despite the name passed into the function.

HOW TO SOLVE THE CODE

The programmer should be concerned with passing a parameter that would act as a placeholder for anything that might be passed into the function. Whatever happens to that placeholder is what we are expecting to happen to whatever we pass into the function.

function greet_user(name){
   console.log("hello, "+name);
}

The above code is replacing every potential name with a placeholder or parameter called name which actually could be anything even a single letter but for the sake of readability, a good placeholder is used. Now we consoled hello + the name which means that anything we keyed in with the function will be consoled.

Functions that take more than one parameter?

Yes, functions can take more than one parameter. In computer programming, a parameter or “argument” is a value that is passed into a function to be used as a placeholder for the actual items that the functions will use later.

Take a look at a program that uses a function that has more than 2 parameters or arguments.

function names(firstName, SecondName, thirdName){
 console.log("Your first name is "+firstName+" and Your middle name is "+secondName+" finally, your surname is "+ thirdName)
};

Wherever that firstName is used, any name you put at first will be placed anywhere firstName appears in the code and looking at the above code, the output will look like this

names(“John”, “Vincent”, “Nnaji”);
//Output will be:

Your first name is John and Your middle name is Vincent finally, your surname is Nnaji

Functions that return a value

This is one of the most popular functions that you would come across. Functions that take arguments, work with them and return a value.

Let’s take a look at an example of such a function.

 function SumNumbers(number1, number2){
  let total = 0;
  total = number1 + number2;
  return total;
}

This function as the name implies sums the numbers passed into it as an argument.

SumNumbers(2,4); // 6
SumNumbers(10,4); // 14
SumNumbers(10, 10); // 20

This function can even be simplified by returning the sum immediately without declaring the variables as thus

Advertisements
function SumNumbers(number1, number2){
  return number1 + number2;
}

Now with the returned function, you can use it further in your program as needed.

A function that doesn’t take any parameter

There are functions that take no parameters and can be called just like that e.g myFunction(). Let’s take a look at an example.

function myfunction(){
 return "hello world!";
}

myfunction(); //'hello world!'

Let us solve some labs to solidify what we have learnt so far.

LAB1

//create a function named highestNum that takes an array of numbers and return the highest number among them.

//eg highestNum([1,2,3,4,5]) should return 5;
//highestNum([2,5,1,7,3,4]) should return 7;

LAB1 SOLUTION

function highestNum(arr){
  let highest = 0;
  for(let i = 0; i< arr.length; i++){
    if(arr[i] > highest){
      highest = arr[i];
    }
  }
  return highest;
}

Explanation of the code

The function is taking an array as an argument as stated in the question which is rightly represented as “arr”. This could be any name but we will be sticking with “arr”.

we declare a variable named highest to hold the value of our highest number at the global scope so we can be able to access it anywhere in the code. So far, it is 0. Now, since we have an array, we need to loop through it to be able to access the array elements.

We do this using the for loops. We use an if statement to check if the current value is greater than highest which is 0 initially. If that number is greater than 0, we give the value of that number as highest using highest = arr[i]; Now, the value of arr[i] becomes the highest. It goes on and on like this till it gets to the end of the loop.

highestNum([4,4,7,8,4,5,6, 12, 1]); //this will return 12

LAB2

//write a function that true if a number is even or false if the number is odd
function isEven(num){
  if(num % 2 == 0){
    return true;
  }else{
    return false;
  }
}

The code takes a number and checks if the number is even. An even number is a number divisible by 2 completely without remainder.

The modulus operator (%) checks the remainder of a number and returns it. If it returns 0, then the number could divide completely.

3 % 2 is 1 because 1 is the remainder when 2 divides 3.

Advertisements
isEven(6); //true
isEven(3); // false;

Study more examples to get yourself familiar with solving algorithms and data structures in Javascript. Take a look at the Strings and the Strings method to learn more about methods you can use to manipulate through strings


Like it? Share with your friends!

Nnaji Victor

Legend

DecaDev, Full-stack developer in training, Gamer, Techie and weirdly cool. I love writing new stuffs that I just discovered and playing around on the net. Check my socials or email me.

What's Your Reaction?

Wow Wow
0
Wow
love love
1
love
hate hate
0
hate
geeky geeky
0
geeky
win win
0
win

0 Comments

Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Countdown
The Classic Internet Countdowns
Open List
Submit your own item and vote up for the best submission
Ranked List
Upvote or downvote to decide the best list item

Send this to a friend