Multiplying Integers on a For Loop - javascript

Beginning JavaScript learner here...
I'm working through Adrian Neumann's Simple Programming Problems and my question is about number 6 in the elementary exercises.
Write a program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,…,n.
// var myArray = []; // for testing
var mySum = 0;
var userNum = prompt("What is your number? ");
var userChoice = prompt("Would you like to add up (+) or multiply (*) all the numbers from 1 to your number? Please enter (+) or (*): ");
if (userChoice == "+") {
for (var i = userNum; i > 0; i--) {
mySum += +i;
}
console.log("Your answer is " + mySum);
} else if (userChoice == "*") {
for (var i = userNum; i > 0; i--) {
mySum *= +i;
// myArray.push(i); // for testing
}
console.log("Your answer is " + mySum);
// console.log(myArray); // for testing
}
When entering values for multiplication, the answer is always 0. Obviously, I thought 0 was being included in the iteration, so I setup an empty array myArray, and pushed all the numbers to the array using myArray.push(i);... 0 was never included as a value in the array.
Other than some obvious form-validation considerations, can anyone tell me what I'm missing? Why is my answer always 0?
Note: The sum section of the code seems to work brilliantly.
Please note I'm a beginniner to JavaScript, so if you'd like to comment, let me know WHY you changed the code the way you do, rather than simply spitting back code to me. That's a big help, thanks.

Well, you initialize mySum to 0 so in every iteration of the loop you'll multiplying i by zero and save the result (again, zero) back into mySum. For multiplication you'd have to start at one.

You didn't set mySum to 1 before multiplication. 0*i = 0.

Related

A task in JavaScript

I need to create a sequence of numbers using while or for that consists of the sum of the symbols of the number.
For example, I have a sequence from 1 to 10. In console (if I've already written a code) will go just 1, 2,3,4,5,6,7,8,9,1. If I take it from 30 to 40 in the console would be 3,4,5,6,7,8,9,10,11,12,13.
I need to create a code that displays a sum that goes from 1 to 100. I don't know how to do it but in console I need to see:
1
2
3
4
5
5
6
7
8
9
1
2
3
4
etc.
I've got some code but I got only NaN. I don't know why. Could you explain this to me?
for (let i = '1'; i <= 99; i++) {
let a = Number(i[0]);
let b = Number(i[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log ('b false', a)
}
else {
console.log ('b true', a + b)
}
}
I hope you get what I was speaking about.
Although I like the accepted answer however from question I gather you were asking something else, that is;
30 become 3+0=3
31 become 3+1=4
37 becomes 3+7=10
Why are we checking for boolean is beyond the scope of the question
Here is simple snnipet does exactly what you ask for
for (let i = 30; i <= 40; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
what er are doing is exactly what Maskin stated begin with for loop then in each increment convert it to string so we can split it, this takes care of NAN issue.
you don't need to call to string just do it once as in let x then simply call the split as x[0] and so on.
within second number we have created a self computation (x[1])||0) that is if there is second value if not then zero. following would work like charm
for (let i = 1; i <= 10; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
Did you observe what happens to ten
here is my real question and solution what if you Don't know the length of the digits in number or for what ever reason you are to go about staring from 100 on wards. We need some form of AI into the code
for (let i = 110; i <= 120; i++) {
let x= Array.from(String(i), Number);
console.log(
x.reduce(function(a, b){ return a + b;})
);
};
You simply make an array with Array.from function then use simple Array.reduce function to run custom functions that adds up all the values as sum, finally run that in console.
Nice, simple and AI
You got NaN because of "i[0]". You need to add toString() call.
for (let i = '1'; i <= 99; i++) {
let a = Number(i.toString()[0]);
let b = Number(i.toString()[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log('b false', a)
} else {
console.log('b true', a + b)
}
}
So the way a for loop works is that you declare a variable to loop, then state the loop condition and then you ask what happens at the end of the loop, normally you increment (which means take the variable and add one to it).
When you say let i = '1', what you're actually doing, is creating a new string, which when you ask for i[0], it gives you the first character in the string.
You should look up the modulo operator. You want to add the number of units, which you can get by dividing by 10 and then casting to an int, to the number in the tens, which you get with the modulo.
As an aside, when you ask a question on StackOverflow, you should ask in a way that means people who have similar questions to you can find their answers.

JavaScript check if a random number has not been used already

I need to get random numbers but can't use the same number more than once.
I wrote the following functions to create a random number and to check if it has not been used yet.
function randomRecep(){
return Math.floor((Math.random() * 3));
}
function assignTemp(tempArr){
console.log("Started assign function, tempArr has: "+tempArr);
var num = randomRecep();
for (var i = 0; i < tempArr.length; i++) {
console.log("num is: " + num + ". check for doubles. tampArr["+i+"] is: "+tempArr[i]);
if (num == tempArr[i]){
console.log("FOUND DOUBLE! random num = "+num+" IS ALREADY IN array:"+tempArr)
assignTemp(tempArr);
break;
}
}
tempArr.push(num);
console.log("pushed " + num + "into array. now is:" + tempArr);
return num;
}
following is a console output. it seems that the check is working but for some reason at the end of the check instead of just pushing the unique random number and returning its value, it seems that the program pushes also all the previous duplicate numbers and returns the first random number instead of the last one that passed the check. why is that?
Started assign function, tempArr has: -1,2,1
code.js:104 num is: 1. check for doubles. tampArr[0] is: -1
code.js:104 num is: 1. check for doubles. tampArr[1] is: 2
code.js:104 num is: 1. check for doubles. tampArr[2] is: 1
code.js:106 FOUND DOUBLE! random num = 1 IS ALREADY IN array:-1,2,1
code.js:101 Started assign function, tempArr has: -1,2,1
code.js:104 num is: 1. check for doubles. tampArr[0] is: -1
code.js:104 num is: 1. check for doubles. tampArr[1] is: 2
code.js:104 num is: 1. check for doubles. tampArr[2] is: 1
code.js:106 FOUND DOUBLE! random num = 1 IS ALREADY IN array:-1,2,1
code.js:101 Started assign function, tempArr has: -1,2,1
code.js:104 num is: 0. check for doubles. tampArr[0] is: -1
code.js:104 num is: 0. check for doubles. tampArr[1] is: 2
code.js:104 num is: 0. check for doubles. tampArr[2] is: 1
code.js:113 pushed 0into array. now is:-1,2,1,0
this result is good and the idea is that it would stop here. but the process continues on:
code.js:113 pushed 1into array. now is:-1,2,1,0,1
code.js:113 pushed 1into array. now is:-1,2,1,0,1,1
I found code which is much simpler that achieves the above goal. However I am trying to learn and I don't yet understand what went wrong at the end of my method. where is the flaw in the logic?
So the problem with your current code is that you use break, where return should be used here
if (num == tempArr[i]){
console.log("FOUND DOUBLE! random num = "+num+" IS ALREADY IN array:"+tempArr)
assignTemp(tempArr);
break; // <-- should be return instead
}
The reason for this is, that once a non-unique number is found, you restart searching the next numbers, but the break will exit the loop, and directly after the for loop, you add num to your array. So, it would first add a potentially new unique number, and then exit that loop, and return to exit your first loop and then add the non-unique number ;)
You could also rewrite your code in the following way (I do not know if you have any requirements to a certain JavaScript versions, or you are only allowed to use a for loop)
function randomRecep(){
return Math.floor((Math.random() * 3));
}
function assignTemp(tempArr){
const number = randomRecep();
if (tempArr.includes( number ) ) {
console.warn( `${number} exists in [${tempArr.join(', ')}]` );
return assignTemp(tempArr);
}
console.warn( `adding ${number} to [${tempArr.join(', ')}]` );
tempArr.push( number );
return tempArr;
}
const output = [];
// shouldn't call this more than the nr of output possibilities (and the pool here has 3 options)
assignTemp( output );
assignTemp( output );
assignTemp( output );
// we will always expect 0, 1, 2 in the output in some manner
console.log( output );

JavaScript Beginner Syntax Errors

I wrote this program out in plain code but I don't know Javascript well enough to get all the syntax right. I am a beginning programming please help me with corrections to my code. It is currently not running at all. We are still going over loops and it's really giving me trouble. This is for a college class. (I know this isn't formatted properly that's why i'm asking for help)
function main() {
alert("Welcome to the program");
var fatGrams = getFatGrams(fatGrams);
var calories = getCalories(fatGrams,calories);
var percentage = caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
Errors in your code :
The function keyword is not needed to call a function. Remove the keyword function before calling a function and simply call the function as getFatGrams(fatGrams);
You are not passing parameters to function caloriesPercentage. Change it to caloriesPercentage(fatGrams,calories);
The expression for a while loop should be enclosed in paranthesis as while(fatGrams < 0).
The OR should be written as ||.
Use + to concatenate 2 string (Or a string and a variable)
"The amount of calories that come from fat is, " + percentage
The expression for an while should also be enclosed in paranthesis as if(percentage < 0.3) and no then is needed. The curly brackets of if should be closed before else.
if(percentage < 0.3){
alert("The food is low in fat.");
}
else {
alert("The food is not too low in fat.");
}
assign value from prompt to variable as
fatGrams = prompt("Enter the new number of fat grams.");
Your final code should look like this :
function main() {
alert("Welcome to the program");
var fatGrams;
var calories;
var percentage;
getFatGrams(fatGrams);
getCalories(fatGrams,calories);
caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
welcome to the wonderful world of programming!
It looks like you are getting the basics down, let me explain some of the issues you are having with JavaScript. I'm going to use some big words (as will many other experienced developers so get used to them!).
Function Declaration vs Function Invocation
The very first issue I see with your main() function is a confusion about when to use the function keyword in JavaScript. You only need to use function when you are declaring a function, or in other words when you want to "create a new function." When you declare something, you are creating it, and in JavaScript the function keyword is how you declare (aka create) a Function. Here is an example of creating a "named function" in javascript.
function addTwo( number ) {
return number + 2;
}
That right there is a "named function" declaration. On a side note, you can also create functions as "expressions" (which would be called a "function expression"). That would look like this
var addThree = function( number ) {
return number + 3;
};
Note that in both cases we are creating a function with the function keyword.
When you want to use a function, you "invoke" it. This is also referred to as "calling" a function. To call (aka invoke) a function you simply write the function name with parenthesis behind it, passing in any arguments. Function invocation works the same for both named functions and function expressions. So we could invoke the two functions above like so
var four = addTwo( 2 );
var five = addThree( 2 );
Simply put, only use the function keyword to make functions. To call or use a function just put ( argument, otherArg ) at the end of the function name.
Branching Statements
The next thing I see is that you're missing some parenthesis! JavaScript has a C style syntax so that means you need to put parenthesis around expressions for if, else if, and switch statements. Those keywords I listed are what we call Branching Statements. They allow you to conditionally execute code based on some true or false value, as opposed to Looping Statements that allow you to repeat code based on a true or false value. The structure for an if .. else branching statement in JavaScript is as follows.
if ( number % 2 === 0 ) {
number *= 2;
} else if ( number % 3 === 0 ) {
number *= 3;
} else {
number += 5;
}
For both if and else if you need to provide an "expression" to branch around. An else statement is always executed if none of the if or else if expressions evaluated to true. The else clause is not required so if you don't have any code in your else block you can just remove it! It is perfectly fine to have a single if statement like this in your code
if ( needsCleanup ) {
doCleanup();
}
Of course it would be ok to have an else if clause and no else clause, the else is always optional. But remember the else clause never has an expression so you should never write () after a simple else.
Looping Statements
Looping is a big concept that takes a while to master so don't get frustrated or discouraged! In JavaScript we have for, while and do while loops. Just like if statements looping statements need an expression, but in this case they need it to know when to stop looping. I'm not going to cover do while loops because they are rarely used and can be confusing when just starting out. Simply put, looping statements say: "keep executing this code block until the expression is false." I find it easiest to illustrate this with a for loop. For loops are a great way to run a code block a specific number of times. Let's look at an example that adds all the numbers from 1 to 10 with a for loop.
var sum = 0;
for ( var i = 1 ; i <= 10 ; i++ ) {
sum += i;
}
// sum will be 55
// i will be 11
A for loop has three expression separated by ;. The first is for initialization and is only executed before the loop starts (the var i = 1 part). The second is the condition that is checked before each iteration. The last is an increment operation that is executed at the end of every loop execution. If we were to re-write this for loop as a while look it would look like this...
var sum = 0;
var i = 1;
while ( i <= 10 ) {
sum += i;
i++;
}
So you can see the var i = 1 happens before the loop starts. The i <= 10 happens before each time the loop runs its body (the part in the {}). And the i++ happens at the end of the loop before it checks i <= 10 to see if it should keep looping.
String Concatenation
String concatenation is the process of putting two strings together. In JavaScript the + operator does double duty as addition 1 + 1 and string concatenation 'hello' + ' world'. So when you want to put two strings together you simply add them! If the strings are in variables then you can just "add" them together...
var salutation = 'Hello';
var name = 'Kylie';
var greeting = salutation + ', ' + name;
// greeting will be "Hello, Kylie"
I hope that clears some things up, if you have any questions please let me know!
Because this IS for a class I am NOT going to give you the answers but instead point out the issues.
Calling a function in Javascript and return a value:
var myvalue = myFunction();
You have function... in your main and need to fix that.
Some functions just return values and thus calling them needs no parameter (like above) others need parameters for the inputs which you have done.
Prompt returns a value and you need to capture that value:
var myinputvalue = prompt("enter value");
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Conditionls need to be wrapped in parenthesis when using while, if etc.
while (mything < 0){ Reference; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
" OR " in a conditional is represented by || and an AND by &&
NOTE: You can use some on-line tools to work out some of the issues for example paste your code into http://jshint.com/ and it will tell you many of the syntax issues.

Convert simple javascript program into C

Hello I have some experience with javascript but I would really like to learn how to program in C and one of the ways I am trying to learn is by converting some simple javascript code into C. My current attempt at converting a simple program compiles without any errors however doesn`t produce the answer I want it to. The javscript code produces the correct answer and I wrote it to solve project euler problem number 5 which can be found here: https://projecteuler.net/problem=5
Here is the working js code:
var number = 2520;
var count = 1;
var solved = false;
while (!solved) {
if (number % count === 0) {
if (count === 20) {
solved = true;
console.log(number);
} else {
count++;
}
} else {
number++;
count = 1;
}
}
Here is the C conversion which does not work:
#include <stdio.h>
int main () {
unsigned int number = 2520;
unsigned int count = 1;
unsigned int solved = 0;
while ((solved = 0)) {
if (number % count == 0) {
if (count == 20) {
solved = 1;
printf("%number");
} else {
count++;
}
} else {
number++;
count = 1;
}
}
return 0;
}
while ((solved = 0)) {
You can use the same syntax you would use in js here, namely, while (!solved), or ==, but just = is an assignment.
printf("%number");
Doesn't mean what you think it means, which is why it's not an actual error (%n is a distinct specifier, and with no corresponding input, you'd get umber as the output). To reproduce console.log() you'd want:
printf("%d\n", (int)number);
Or
printf("%u\n", number);
Notice the explicit \n, since printf() does not add a newline otherwise.
Replace
while (solved = 0)
with
while (!solved)
and
print("%number")
with
print("%u\n",number)
I know its already answered, but you should know why.
while ((solved = 0))
Will actually set solved to 0 AND return 0 (which is interpreted as false). So the while loop is exited right away.
printf also takes a pretty strictly formatted string for the first one (just typeing what makes sense is guarenteed to be wrong). The compiler has know way to know what is inside the string is anything other than a string (C++ has (almost) NO reflection, unlike javascript: your written code dissapears into ones and zeros). printf needs to take number in as the second argument. Try printf("%i\n",number);. That says "Print an integer followed by a newline. The integer's value is number."
Welcome to C! Your biggest problem going into is is going to be my biggest problem with Java Script: C is strictly typed with no reflection, while javascript has no types with almost everything relying on some sort of reflection.

ignoring empty strings when looping through an array in JavaScript

I am attempting to go through an array and add up all the numbers. I used console.log to show me what values the script was using as shown below. I keep trying different variations of things in the if() but nothing seems to be working properly.
var billycount = 0;
var billyTotalScore = billyScoreList.reduce(function(score, total) {
if(score === " ") {
billycount += 1;
}
return +total + +score;
});
console.log(billycount); //0
console.log(billyTotalScore); //30
console.log(billyScoreList); // ["12", " ", "18"]
console.log(billyAverageScore) //10
var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);
The answer to billyAverageScore should equal 15 (30/2).
I tried if(score === "0") which gives me the same answers as above and if (score !== true) which gives me a count of 2 and an average of 30. I think reduce() is treating the empty string as a 0. I want to be able to count all the empty strings so I can discount them from the length when finding the average.
I have been wrestling this forever and feel like I'm missing one key concept behind it. Any help would be great! Thanks!
UPDATE:
For anyone who stumbles across this, here is the code I got to work.
var billycount = 0;
var billyTotalScore = billyScoreList.reduce(function(total, score) {
if (score === " " || total === " ") {
billycount++;
}
return +total + +score;
});
var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);
When I was just checking if (score === " ") I was forgetting that score will never be equal to the first term in the array. I just added || total === " ". the only time this would break down would be if the first element was " " and the second element was 0. I would want to billycount++ for the first element but not for the second. I'll have to give that some more thought.
The callback function of reduce should be function(total, score) instead of function(score, total).
see MDN:
previousValue
The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
currentValue
The current element being processed in the array.

Categories

Resources