What am I doing wrong with this addition code? - javascript

var addition=function(num){
var sumSoFar=0;
for(var i=1;i<=num;i++)
{
sumSoFar+=num[i];
return sumSoFar;
}
};
console.log(addition(5));
I wrote this with a while loop a little bit ago. It supposed to take a random (num) and return the sum of all numbers from 1 to (num) Im just not figuring out what im doing wrong with the for loop

inside the for loop you are returning he sum, so you just return 1!
do
var addition=function(num){
var sumSoFar=0;
for(var i=1;i<=num;i++)
{
sumSoFar+=i;
}
return sumSoFar;
};
console.log(addition(5));
also if you just need the sum of i from 1 to n do:
var addition=function(num){
return (1+num) * num / 2;
};
and read on Arithmetic progression

Your return is inside the for loop - it should be outside.

You've put a return statement in the middle of the loop. That will cause the function to return on the first pass through there.
If num is a number, then num[i] doesn't mean anything. You just need to add i.

Do u want to do this:
var addition=function(num){
var sumSoFar=0;
for(var i=1;i<=num;i++)
{
sumSoFar+=i;//will add the loop varible to get sum
}
return sumSoFar;//also function can return a value only once and not in a loop
};

Related

'For loop' within a function

I hope everyone is having an amazing day so far.
I am asking for help on an exercise that I am stuck on. I have gone through and researched all over but still am not getting it right.
The task is:
Create a for loop in which an iterator starting from 0 up to the iteratorMax value (not included) (the second parameter to your function) is incremented by 1. Add the iterator to num(the first parameter to your function) for each incrementation. you must return the number at the end of your function.
I was given this code to start with:
function IncrementNumber(num, iteratorMax){
//Add For loop here
//return value here
}
I have tried coding it a number of different ways but still not correct.
for example:
function IncrementNumber(num, iteratorMax){
for (let i = 0; i < iteratorMax; i++) {
return(i);
}
}
I have tried to declare "i" but that seems to be incorrect also.
I really appreciate any help or hints to what I am missing or doing wrong in my code.
Thank you!
For the IncrementNumber(value, N) method, when value is 0, this algorithm returns the result of the equation:
Total = N x (N-1) / 2
function IncrementNumber(num, iteratorMax){
for(let i = 0 ; i < iteratorMax ; ++i){
num += i;
console.log(`i: ${i}\tnumber: ${num}`);
}
return num;
}
console.log(`Result: ${IncrementNumber(0, 10)}`);
If you call return within the loop, the loop will only be executed once.
You need to move the return statement outside of the loop.
Whenever calling return, this will cause the current function to exit.
function IncrementNumber(num, iteratorMax){
for (let i = 0; i < iteratorMax; i++) {
num += i;
}
return num;
}

Strange behaviour of for loop in Heap's algorithm in JavaScript

I'm trying to implement Heap's algorithm to find different permutations of a string and found a strange behaviour with a for loop, here's the code
function permAlone(str) {
var strArr = str.split(''),
permutations = [];
function swap(strArr, x, y) {
var tmp = strArr[x];
strArr[x] = strArr[y];
strArr[y] = tmp;
}
function generate(n) {
if (n === 1) {
permutations.push(strArr.join());
} else {
for (var i = 0; i != n; i++) {
generate(n - 1);
swap(n % 2 ? 0 : i, n - 1);
}
}
}
generate(strArr.length);
return permutations;
}
console.log(permAlone('aab'));
In the for loop within the generate function, if I put i = 0 the output of the script is ['a,a,b', 'a,a,b'] but if I put var i = 0 the output is ['a,a,b', 'a,a,b', 'a,a,b', 'a,a,b', 'a,a,b', 'a,a,b'].
I understand that var i would create a local variable for the loop, but don't understand in this case why it would change how the loop functions as there is no i variable declared anywhere else in the script.
Thanks any help appreciated.
The reason the behaviour changes if you have a global i variable is that you have multiple recursive calls to generate() all trying to control their own partially complete for loops with the same variable, and all setting i back to 0 when they start.
Picture what happens on the second iteration of the for loop: i is 1 because it has just been incremented, but then immediately a recursive call to generate() starts its own loop and sets i back to 0 again.
If you create a local variable with var then each for loop in each recursive call is independent of all the others.
Try stepping through the code with the debugger, or try adding the following as the first line inside the for loop and watch what happens to the variables when the code runs:
console.log('n:' + n + '; i: '+i);

Getting the total of multiple functions outputs in Javascript, node.js

I have this function called numFunc(), which produces a numeric output.
I want to run this function 5 times and get the sum of all 5 outputs.
Here's what I've tried
function total(){
for (itr=1; itr<=5; itr++) //run the function 5 times
{
var numF = numFunc(); //store the output from the function in a variable
var sum = sum+numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();
But, what I get is the following output
3
3
3
3
3
NaN
What I want is the sum as a single value. How do I achieve this?
You need to declare your variabble outside of the loop and set it to a number value otherwise you are adding an undefined to an integer. Thanks #jfriend00 for the clarification
function total(){
var sum = 0;
for (itr=1; itr<=5; itr++) //run the function 5 times
{
var numF = numFunc(); //store the output from the function in a variable
sum = sum + numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();
In the statement:
var sum = sum + numF;
You are trying to add something that does not yet exist, because you just declared it there with the var
With your statement, you should be declaring the vars above the loop:
function total(){
// declaring the variables before you use them.
// I will set them to 0 so I know they're supposed to be numbers, and 0 wont affect the outcome of the function
var numF = 0;
var sum = 0;
for (itr=1; itr<=5; itr++) //run the function 5 times
{
numF = numFunc(); //store the output from the function in a variable
sum = sum+numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();
What about trying an array, and then adding that array values externally after the function fires like this?
EDIT: Used the repl.it code editor to test this theory out. I had to change the code a bit but remained under the same premise. Used separate the functions and then fed the array builder function into the calculator function to properly calculate the array variables. Repl link here: (https://repl.it/B128/1)
function numFunc(){
return 3;
};
function total(){
var toBeSummed = []; //set up an array to put your sum variables into as a more versatile variable type to perform this in.
for (var itr=0; itr<5; itr++){ //runs the function 5 times
var numF = numFunc(); //store the output from the function
var arrayItr = itr; //uses "itr" variable to iterate a 0 based index 5 times
toBeSummed[arrayItr] = numF; //for each arrayItr 0-5 makes the array value equal to the numF value.
};
return toBeSummed;
};
var sum = 0;
function counter(totals){
for(sums in totals){ //iterates the x array elements(5 in this case)
sum = sum + totals[sums]; // Adds the current value of sum, plus the values at each existing array point(at this point values in array index 0-5)
//console.log(sum); //Should now log the correct set of sums "browser"
};
console.log(sum);
};
counter(total());
Thank you all for your help.
I think I found the issue. The original numFunc() function seemed to have a console.log() statement that's why I kept on getting the list of 3's all the time, replacing that with a return resolved that.
And as you guys suggested declaring the sum variable outside the loop prevented the display of 'NaN'

Trouble pushing to an array in JS

Below is just a section of my code but I know it's problematic because I can't get it to return any value except 'undefined'. I have been over this for hours and cannot figure it out.
I want to be able to input a number and have its factors pushed to an array. I have tested it by alerting the first item in the array and I get nothing. I'm sure this is a pretty easy but I just can't figure it out. Here is the code:
var numberInQuestion = prompt("Of what number are you wanting to find the largest prime factor?");
//determine factors and push to array for later use
var factorsArray = [];
function factors(numberInQuestion){
for(var i = 2; i < numberInQuestion-1; i++){
if(numberInQuestion % i === 0){
return factorsArray.push[i];
} else {
continue;
}
}
};
factors(numberInQuestion);
alert(factorsArray[0]);
Thanks for any help!
you can only return one value
you must use (), not [] for calling push
factorsArray should be local to factors (put the definition inside the function)
the else { continue; } is useless
Here is the fully corrected code:
var numberInQuestion = prompt("Of what number are you wanting to find the factors of?");
//determine factors
function factors(numberInQuestion){
var factorsArray = []; // make it local
for (var i = 2; i < numberInQuestion-1; i++){
if(numberInQuestion % i === 0){
factorsArray.push(i); // use (), and don't return here
} // no need for else { continue; } because it's a loop anyway
}
return factorsArray; // return at the end
};
var result = factors(numberInQuestion); // assign the result to a variable
alert(result);
Here's a JSFiddle.
You have an error in your pushing syntax. Correct syntax for pushing is -
factorsArray.push(i);
Also returning immediately from the function after finding the first divisor will not give you the full list. You probably want to return after you've found out all the divisors.
Taking all of the above into consideration, you should rewrite your function as follow -
function factors(numberInQuestion){
for(var i = 2; i < numberInQuestion - 1; i++){
if(numberInQuestion % i === 0) {
factorsArray.push(i);
}
}
}
and you will be OK.
You've coded this so that when you find the first factor your function returns immediately. Just get rid of the return keyword in that statement. (What "return" means in JavaScript and other similar languages is to immediately exit the function and resume from where the function was called.)
Oh, also, you call functions (like .push()) with parentheses, not square brackets.
The function should not return when pushing to the array. Return the array after executing the loop. The else clause is also unnecessary.
var numberInQuestion = prompt("Of what number are you wanting to find the largest prime factor?");
function factors(numberInQuestion){
var factorsArray = [];
for(var i = 2; i < numberInQuestion-1; i++){
if(numberInQuestion % i === 0 && isPrime(i)){
factorsArray.push(i);
}
}
return factorsArray;
};
var factors = factors(numberInQuestion);
alert(factors[factors.length-1]);
//From: http://stackoverflow.com/questions/11966520/how-to-find-prime-numbers
function isPrime (n)
{
if (n < 2) return false;
var q = Math.sqrt (n);
for (var i = 2; i <= q; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
Given the purpose of the example two items must be considered
The code does not determine if the number is actually prime. The code will return the smallest factor possible since the loop starts at two and increments, then returns the first element in the array. The largest factor would actually be the last element in the array. I have corrected the example to find the greatest prime factor. You can test it via this fiddle: http://jsfiddle.net/whKGB/1/

how to create a loop in a function with another function?

I'm new to Java and I'm doing a uni course. I've been asked to design three functions.I have to find the difference between each adjacent numbers in an array, another to total the array and the last one to calculate the difference using the other functions then write a programme. I'm totally lost on the last function and my tutor has gone away on hols. Here is the code I have done so far. I don't want people doing the code for me but if anyone can advice me what I need to do I would appreciate your advice. I'm not sure how to loop the difference function into the array and store it into the new array I have made. If anyone could explain where I am going wrong I would love to hear from you!
var numberArray = [10,9,3,12];
// function difference will find the highest value of the two numbers,find the difference between them and return the value.
function difference(firstNumber, secondNumber)
{
if (firstNumber > secondNumber)
{
return (firstNumber - secondNumber);
}
else
{
return (secondNumber - firstNumber);
}
}
// function sum will add the total numbers in the array and return the sum of numbers.
function sum(numberArray)
{
numberTotal = 0
for (var total = 0; total < numberArray.length; total = total + 1)
{
numberTotal = numberTotal + numberArray[total]
}
{
return numberTotal
}
/*code the process that calculates a new array containing the differences between all the pairs
of adjacent numbers, using the difference() function you have already written.
This function should be named calculateDifferences() and should accept an array numberArray.
The function should first create a new empty array of the same size as numberArray
It should then calculate the differences between the pairs of adjacent numbers,
using the difference() function, and store them in the new array. Finally, the function should return the new array.
The calculation of the differences should be done in a loop, at each step finding the difference between each
array element and the next one along in the array, all except for the last difference,
which must be dealt with as a special case, because after the last element we have to wrap round to the start again.
So the final difference is between the last and first elements in the array.*/
function calculateDifferences()
var createArray = new Array (numberArray.length);
{
createArray = 0;
for (var c = 0; c < numberArray.length; c = c + 1)
{
createArray = difference(numberArray[c]);
}
{
return createArray
}
}
your implementation of function "calculateDifferences" is not correct.
this function should look like this:
function calculateDifferences()
{
var createArray = new Array (numberArray.length);
for (var c = 0; c < numberArray.length - 1 ; c = c + 1)
{
/*
because of the function "difference" has two parameters (firstNumber, secondNumber) in its declaration, we should give two arguments. (that are adjacent elements in array)
*/
createArray[c] = difference(numberArray[c],numberArray[c+1]);
}
/ *
calculating difference of first and last element of array and
assign it to returning array's last element.
*/
createArray[numberArray.length - 1] = difference(numberArray[0],numberArray[numberArray.length - 1]);
return createArray;
}
You should index createArray the same way you already do with numberArray[c].

Categories

Resources