Site Title

Penguins JS Lessons

Download Homework
Submission Google Form for Homework

Mathematical Expressions Homework

In order to learn this subject of programming well, you have to practice:

Popcorn hack 1: operations with variables

Popcorn hack 2: Make 2 variables x, and y. Compute 3 different operations and log it into the console with console.log();

Final Task: Build a system of functions that represent different mathematical expressions. Each of these functions will perform a different mathematical operation(ex: add, subtract). Make at least 5 of these different functions.


Popcorn Hack 1 (Progress Check)

Part 1:
In the javascript node below, make 2 variables, num1 set to 6 and num2 set to 3, then write the equation (num1 * num2) + (num1 / 2).

The output should be 21.

Part 2:
Next, keeping the same variables, add a new variable called total that is equal to the equation num1 / num2 + 2 ** 3, and this time make the equation

(total + 15) - numb1 ** 2 / 4

Write this code below:

%%html

<div>
    <h3>Popcorn Hack 1 Output</h3>
    <div id="popcorn-hack-1-output">Output will appear here:</div>
</div>

<script>
  (() => {
    const output = document.getElementById('popcorn-hack-1-output');
    // put your popcorn hack 1 code here:

    // part uno
    let num1 = 6;
    let num2 = 3; 
    let result1 = (num1 * num2) + (num1/2);
    console.log(`Part 1 Result: ${result1}`);
    output.innerText += "\n" + `The first result is: ${result1}`;

    // part 2
    let total = num1 / num2 + 2 ** 3;
    let result2 = (total + 15) - num1 ** 2 / 4;
    console.log(`Part 2 Result: ${result2}`);
    output.innerText += "\n" + `The second result is: ${result2}`;

  })();
</script>

Popcorn Hack 1 Output

Output will appear here:

Popcorn Hack 2 (Progress check):

Create 2 variables x and y. With the output area below, provide 3 different operators used with the 2 variables
(ex: let sum = x + y;)
and fill in the output with a sentence that provides all three operators and their respective answer.

%%html

<h3>Popcorn Hack 2 Output</h3>
<button id="ph2button"><a>Click to Calculate Results</a></button>
<div id="homework2"></div>


<script>    
(() => {
    const button = document.getElementById("ph2button");
    button.addEventListener("click", () => {
      // Your variables go here
        let x = 6;
        let y = 7;

        // put your operations here:
        // feel free to do any operation and change the names of the variables
        let exponent = x ** y;
        let sum = x + y;
        let product = x*y;

        // Put the answer for the 3 operators in this DOM element
        document.getElementById("homework2").innerText = `x^y: ${exponent}\nx+y: ${sum}\nx*y: ${product}`;
    });
})();
</script>

Popcorn Hack 2 Output


Final Task:

  1. Make 5 different functions, each with different operators/expressions:
  1. Be able to use the functions as well as document.getElementById to make the buttons output the result.

  2. Have fun! Mess around with different variables with different values, and maybe see if you can make any complex equations like the ones you’re learning in your math class. The end objective is for you to be able to use and understand math expressions.

Example function:

function add(a, b)
{
	return a + b;
}

Some ideas you can use:


Now that you have seen the example, you will start writing your custom functions in the html code block below:
Make sure to follow each comment on where to write your code, don't modify any existing code.

%%html

<!-- This is where the outputs of your functions will go: -->
<h2>Homework</h2>


<!-- Modify each of the button onclick fields to call your functions: -->
<!-- Make sure when the function is called you input your parameters. -->
<!-- (Optional) You can also change the text each button displays if you want. -->

<!-- yea so I basically just made a calculator :) -->

<h4 id="selectedOperation">Selected Operation: None</h4>

<!--two number operations (normal ones plus the goofy ones)-->
<p>Binary Operations</p>
<button id="addButton" onclick="binaryOp('add')">Add</button>
<button id="subtractButton" onclick="binaryOp('subtract')">Subtract</button>
<button id="multButton" onclick="binaryOp('multiply')">Multiply</button>
<button id="divButton" onclick="binaryOp('divide')">Divide</button>
<button id="exponentButton" onclick="binaryOp('exponent')">Exponent</button>
<button id="modButton" onclick="binaryOp('modulo')">Remainder (modulo)</button>
<button id="avgButton" onclick="binaryOp('average')">Average</button>
<button id="lcmButton" onclick="binaryOp('lcm')">LCM</button>
<button id="gcfButton" onclick="binaryOp('gcf')">GCF</button>
<button id="nthrootButton" onclick="binaryOp('nthroot')">Nth root</button>

<br>
<!--one number operations (all of them are goofy)-->
<p>Unary Operations:</p>
<button id="absButton" onclick="unaryOp('abs')">Absolute Value</button>
<button id="sqrtButton" onclick="unaryOp('sqrt')">Square Root</button>
<button id="cbrtButton" onclick="unaryOp('cbrt')">Cube Root</button>
<button id="roundButton" onclick="unaryOp('round')">Round</button>
<button id="ceilButton" onclick="unaryOp('ceil')">Ceiling</button>
<button id="floorButton" onclick="unaryOp('floor')">Floor</button>
<button id="sqrButton" onclick="unaryOp('square')">Square</button>
<button id="cubeButton" onclick="unaryOp('cube')">Cube</button>

<!--i needed a div for inputs because I need to create 1 OR 2 input fields depending on the operation-->
<div id="inpRegion"></div>

<h4><div id="hwOutput"></div><h4>
<br>


<!-- You will write the code for your functions in this script area  -->
<script>
	function binaryOp(op){
		document.getElementById("selectedOperation").innerText = `Selected Operation: ${op.toUpperCase()}`;
		const inpRegion = document.getElementById("inpRegion");
		// create 2  input html fieldds
		inpRegion.innerHTML = `
		<p>Enter two numbers:</p>
		<input type="number" id="num1" placeholder="First number">
		<input type="number" id="num2" placeholder="Second number">
		<button onclick="calculateBinary('${op}')">Calculate</button>
		`;

		if (op=="nthroot"){
			inpRegion.innerHTML += `
				<i><p>The first input is the number to get the Nth root of. The second input is N.</p></i>
			`
		}
  	}

	function unaryOp(op){
		document.getElementById("selectedOperation").innerText = `Selected Operation: ${op.toUpperCase()}`;
		const inpRegion = document.getElementById("inpRegion");
		// create ONLY ONE input html field
		inpRegion.innerHTML = `
		<p>Enter a number:</p>
		<input type="number" id="num1" placeholder="Number">
		<button onclick="calculateUnary('${op}')">Calculate</button>
		`;
	}

	// function that acc does the math and calculates the result
	function calculateUnary(op){
		// the exception handling just makes sure that it tells the user that there
		// was an error if they enter something like "pranay!!hs025"
		const output = document.getElementById("hwOutput");

		try{ 
			const num = Number(document.getElementById("num1").value);

			// map operation name to corresponding func (dictionary is a better name tho)
			const unaryOpsMap = {
				"ceil": Math.ceil,
				"floor": Math.floor,
				"abs": Math.abs,
				"sqrt": Math.sqrt,
				"cbrt": Math.cbrt,
				"round": Math.round,
				"square": x => x ** 2, // functions needed because there isnt a square func
				"cube": x => x ** 3, // same thing for this arrow function, like python lambdas
			};

			let ans = unaryOpsMap[op](num);
			output.innerText = `Result: ${ans}`;

		} catch (error) {
			output.innerText = "An error occured."
			console.log(error);
		}
	}

	// same thing but for 2 num operations
	function calculateBinary(op){

		const output = document.getElementById("hwOutput");

		const num1 = Number(document.getElementById("num1").value);
		const num2 = Number(document.getElementById("num2").value);

		function findGCF(a, b){
			// according to google this uses the "euclidean algorithm"
			
			// make sure inputs are positive integers
			if (a != Math.abs(Math.floor(a)) || b != Math.abs(Math.floor(b))){
				throw new Error("GCF neds positive integers");
			}


			while (b !== 0) {
				let temp = b;
				b = a % b;
				a = temp;
			}
			return a;
		}

		function findLCM(a, b){
			// edge case: either number is 0
			if (a === 0 || b === 0) {
				return 0;
			}

			// same input val as findGCF
			if (a != Math.abs(Math.floor(a)) || b != Math.abs(Math.floor(b))){
				throw new Error("LCM neds positive integers");
			}

			return (a * b) / findGCF(a, b);
		}

		try {
			const binaryOpsMap = {
				"add": (x, y) => x + y,
				"subtract": (x, y) => x - y,
				"multiply": (x, y) => x * y,
				"divide": (x, y) => x / y,
				"exponent": (x, y) => x ** y,
				"modulo": (x, y) => x % y,
				"average": (x, y) => (x + y) / 2,
				"nthroot": (x, y) => x ** (1 / y),
				"lcm": findLCM,
				"gcf": findGCF,
			};

			let ans = binaryOpsMap[op](num1, num2);
			output.innerText = `Result: ${ans}`;
			console.log(`Result: ${ans}`);
		} catch (error) {
			output.innerText = "An error occured."
			console.log(error);
		}
	}

</script>


Homework

Selected Operation: None

Binary Operations


Unary Operations:


--- Grading Popcorn Hack 1: Completion gives 0.2 points.

Popcorn Hack 2: Completion gives 0.3 points.

Final Task: Completion gives 0.5 points. Max of 0.02 extra points from extra work relevant to the subject or finishing assignment in a way that shows exceptional comprehension of the lesson.
Make sure to submit your homework deployed link onto the global homework submission google sheet Submission Google Form for Homework