1) If I enter an even number, I want next 10 even numbers to be printed. If I enter an odd number, I want next 10 odd numbers to be printed.
2)If I enter an even number, I want previous 5 even numbers to be printed. If I enter an odd number, I want previous 5 odd numbers to be printed.
i am newbie to programming and trying to learn java-script myself, the above is the question i am trying to solve. i am confused, i am not sure how to make the code to write the next 10 odd even number (i am referring to the first question).also the previous 5 (referring to second question).. below is my starting attempt. i am stuck
function isEven {
var value = prompt("");
if (value % 2 == 0) {
for (var i = 2; i <= ; i = i + 2;)
document.write(i + "<br>");
}
}
isEven();
Answer 1:
if(number>=0){
for(i=2;i<21;i+=2){
console.log(number+i);
}
}
Answer 2:
for(i=2;i<11;i+=2){
if((number-i)>=0){
console.log(number-i);
}
}
1) If I enter an even number, I want next 10 even numbers to be printed. If I enter an odd number, I want next 10 odd numbers to be printed.
function function1() {
var value = prompt("");
value = parseInt(value);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
document.write(value + "<br>");
}
}
2)If I enter an even number, I want previous 5 even numbers to be printed. If I enter an odd number, I want previous 5 odd numbers to be printed.
function function2() {
var value = prompt("");
value = parseInt(value);
for (var i = 1; i <= 5; i = i + 1){
value = value - 2;
document.write(value + "<br>");
}
}
Just to clarify. You want to print both the previous 5 numbers and next 10 numbers of same 'evenness' for any given number?
In which case, you should do just that... You dont need to care if the number is even or odd, because the next/previous is always 2 away. (What you do when you cross 0 is up to you)
for (var i = 1; i <= 5; i++)
document.write((INPUT - (i*2)) + "<br>");
for (var i = 1; i <= 10; i++)
document.write((INPUT + (i*2)) + "<br>");
refer this woking demo. hope this will help to you.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
Enter a number : <input type="number" id="num">
<button id="butp" class="chk">print previous five numbers</button>
|| <button id="butn" class="chk">print next ten numbers</button>
<ul id="print">
</ul>
<script type="text/javascript">
$(".chk").click(function(){
var the_id = $(this).attr('id');
//alert(the_id);
var theVal = parseInt($("#num").val());
if (the_id =="butp") //this means user asking for previous
{
if (theVal==0 || theVal < 10)
{
alert("cannot continue the operation, please enter a valid nubmer to continue");
}
else
{
for (var i=1;i<6;i++)
{
newVal = theVal - (i*2);
$("#print").append($("<li>"+newVal+"</li>"));
}
}
}
else // this means user asking for next
{
for (var i = 1;i<11;i++)
{
if (theVal==0)
{
alert("please enter a valid number to continue");
}
else
{
newVal = theVal + (i*2);
$("#print").append($("<li>"+newVal+"</li>"));
}
}
}
});
$("#num").on('change keyup keydown', function(){
theVal = $(this).val();
if (theVal == "")
{
$("#print li").css({"display":"none"})
}
})
</script>
</body>
</html>
function evenOdd(value) {
if(value%2==0){
console.log(`it's and even number ${value} next 3 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
console.log(value);
}
}else{
console.log(`it's and odd number ${value} next 3 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
console.log(value);
}
}
}
evenOdd(13)
Related
I have an input field where by default I will have $0.00.
when I enter a number, say 1, the input should show $0.01,
again if I enter 2, the input should show $0.12
simultaneously if I press 3, 4, 5, the final output should be $123.45.
Now, If I click delete, it should remove 5, so output will be $123.4
again if I click delete it should remove 4, so output will be $123
If I add a number 2 again here, it should show, $123.2
Is it possible? I am stuck at the last 3 steps.
I have this so far,
let previousTip = 0;
const addingFunction = (value) => {
if(Number(value) <= Number(previousTip)) return Number(value).toFixed(2);
const addNumberRightToLeft = (baseValue, updatedValue) => ((baseValue * 10) + (updatedValue / 100)).toFixed(2);
previousTip = addNumberRightToLeft((Number(previousTip) || 0), value.length > 1 ? value.slice(-1) : value);
return previousTip;
}
my onClick event has
const tipString = addingFunction(e?.target?.value?.trim()?.replace(/[^\d.]/g, '') || '');
Any help will be really appreciated
Here are two functions that should do what you need. You can call the correct one depending on which key is pressed on onKeyPressed
I'm currently not able to test this, but the logic is there.
function addValueToNumber(number,value){
count = 0;
while (number%10 != 0){
number *= 10;
count ++;
}
number += value/10;
for (i=0,i<count-1,i++){
number /= 10;
}
}
function remove(number){
count = 0;
while (number%10 != 0){
number *= 10;
count ++;
}
number = number//10;
for (i=0,i<count-1,i++){
number /= 10;
}
}
I am trying to complete the following code to achieve the sum of numbers from 1 to 100(user's entry must be 1-100), using whileloop or doloop. I am new to this so, any help is much appreciated!
In the following code, I used prompt method to get the user entry. Wrote the code, to sum numbers; from 1 through the user's entry. I displayed the result in an alert box. Now, my challenge is I want to display an error message if the user's entry outside the 1-100 range. And after that, I do not want to do any calculations if user clicks cancel and stop displaying the prompt box.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
}
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
} while (counter<=numOfLoops)
alert ("sum=" +sum);
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
Simply move the calculation logic inside the condition where the user enters the correct input. This will make sure that the prompt closes automatically when you click on the cancel button (Prompt returns null when the user clicks on cancel)
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers != null && (isNaN(parseInt(numbers)) || parseInt(numbers) > 100 || parseInt(numbers) < 1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers != null) {
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum += counter;
counter++;
} while (counter <= numOfLoops)
alert("sum=" + sum);
}
</script>
You could simply use a do…while to solve your problem, e.g.:
let n = null;
do {
n = parseInt(prompt('Enter an int number between 1 and 100'));
} while (isNaN(n) || (n < 1 || n > 100));
let sum = n * (n + 1) / 2;
alert('The sum of all int numbers from 1 to ' + n + ' is: ' + sum);
N.B. The sum of the first n integer numbers can be computed as n * (n + 1) / 2, with O(1) complexity - reducing the O(n) complexity of your for loop.
I'm trying to fill 9 boxes with numbers, these numbers could be number 1 or number 2, being that number 2 can only be 4 times and number 1 should fill the other 5 times left... i know it's a problem of simple logic but someway I can't reach my goal... look at the piece of code that I have...
<script type="text/javascript">
for (cicloTipo = 1; cicloTipo < 10; cicloTipo++) {
var tipo = Math.floor((Math.random() * 2) + 1);
document.write(tipo);
}
</script>
You can start with an array of the required values, then either shuffle the array or randomly select values from it. Some say Math.random isn't truely random, but it should be good enough.
The following uses splice to select values, so the loop iterates backwards since splicing shortens the source array each time.
function getRandoms(){
for (var seed=[1,1,1,1,1,2,2,2,2], result=[], i=seed.length; i; i--) {
result.push(seed.splice(Math.random() * i | 0, 1)[0]);
}
return result;
}
// Show randomness of result
(function() {
var s = new Array(30).fill('+');
var r;
for (var i=9; i; ){
document.getElementById(--i).textContent = s.join('');
}
var j = 300; // Number of runs
var delay = 20; // Default delay in ms
function display(lag) {
delay = lag || delay;
getRandoms().forEach(function(v, i, rand) {
var el = document.getElementById(i);
if (v == 1) {
el.textContent = el.textContent.slice(0,-1);
// If run out of "+", add some to every line
if (!el.textContent.length) {
for (var k=0; k < 9; k++) {
document.getElementById(k).textContent += '++++++++++';
}
}
} else {
el.textContent += '+';
}
if (i == 0) {
document.getElementById('msg').innerHTML = 'Remaining: ' + j +
'<br>' + 'Values: ' + rand.join('');
}
});
--j;
if (j > 0) {
setTimeout(display, delay);
}
}
display(50);
}());
// Single call
// console.log(getRandoms().join());
<span id="0"></span><br>
<span id="1"></span><br>
<span id="2"></span><br>
<span id="3"></span><br>
<span id="4"></span><br>
<span id="5"></span><br>
<span id="6"></span><br>
<span id="7"></span><br>
<span id="8"></span><br>
<span id="msg"></span>
For fun I've added a display of the distribution. Each line represents a value in the result array from 0 to 8 and starts with a set number of "+" symbols. Each time a 1 is in the related position, a "+" is removed. Each time a 2 is in the position, a "+" is added. Since there are more 1s than 2s, the lines slowly get shorter. When a line gets to zero length, 10 more "+" are added to every line.
The important part is that the lines stay about equivalent lengths and that the same lines aren't longest or shortest after each run. If you think you see a pattern emerging, it must be sustained for at least 100 runs to show a bias.
Here's a solution which ensures that no more than 4 2's are in the chain.
it means that the digits chain can contain from 0 2's to 4 2's and the rest is 1's
// 2s Counter
var c1 = c2 = 0;
for (var cicloTipo = 1; cicloTipo < 10; cicloTipo++) {
var tipo = Math.floor((Math.random() * 2) + 1);
// check if it's a 2 and 4 2s have been encountred
if (tipo == 2) {
if (c2 < 4) {
// increment counter
c2++;
} else {
tipo = 1;
c1++;
}
}
// check if it's a 1 and 5 1s have been encountred
else if (tipo == 1) {
if (c1 < 5) {
// increment counter
c1++;
} else {
tipo = 2;
c2++;
}
}
document.write(tipo);
}
it looks like your criteria forces 4 2's and 5 1's;
i fixed this code to fit this criteria but #Paul Rooney 's suggestion is the best.
I was having trouble with the OnClick method I was learning while creating a game. Every time I enter the value and click the button, it is stuck in a loop, I tried document.write and it works using that, but than it opens a new page instead of showing up on screen.
I am new to the programming community, so any help would be nice.
<body>
<p>Enter an integer between 1-100 here:
<input id="number" type="text" />
</p>
<p>
<button onclick="onclickFunction()" type="button">Enter</button>
</p>
<p id="result"></p>
<script type="text/javascript">
function onclickFunction() {
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
var intNumber;
var count = 0;
var bool = false;
do {
do {
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
if (intNumber > c) {
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
} else if (intNumber < c) {
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
} else if (intNumber == c) {
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
count = count + 1
} while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
</script>
</body>
Updated:
<script type="text/javascript">
// Declare all your functions first
// These functions expect no parameters and return values.
function onclickFunction()
{
var a = Math.random();
var b = a * 100;
var c = Math.floor(b);
// Input from text box.
var randomNumber = document.getElementById("number").value;
// Output to paragraph.
if (randomNumber < c && randomNumber != c)
{
document.getElementById("result").innerHTML = "Too Low " + "</br>";
}
else if (randomNumber > c && randomNumber != c )
{
document.getElementById("result").innerHTML = "Too High" + "</br>";
}
else if (randomNumber == c)
{
document.getElementById("result").innerHTML = "Win!";
}
// Clear text box for further input.
document.getElementById("name").value = "";
}
</script>
<p>Enter an integer between 1-100 here: <input id="number" type="text" /></p>
<p><button onclick="onclickFunction()" type="button">Enter</button></p>
<p id="result"></p>
</body>
First of all, it is always useful to create a fiddle.
That way people who are reading your question can run your code immediately.
Let's break down the code
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
This can be done in a single line, to save variables.
do
{
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
I'm not a big fan of using do/while loops this way, although it can come handy when you want to run the do code at least once, like now.
This loop keeps running when the number is bigger than 100, or smaller than 0. So if I pick an incorrect number that means my browser crashes.
if (intNumber>c){
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
}else if (intNumber<c){
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
}else if (intNumber == c){
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
First you are checking if the guess is bigger than the answer, than if it's smaller. That means that the last check if it's equal is unnecessary, since that is the only option left. You can just use an else here.
Also try to be consistent with your spacing and where you place your curly brackets.
do{
//Stuff
}
and
do
{
//Stuff
}
Are both valid ways to use brackets, but stick to one style or your code will get too confusing.
count = count + 1
A small oversight here is that the count starts at 0. So when you guess the number in a single try, it will say you have done it in 0 tries.
while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
All the previous code will be done until bool becomes true. The problem here is that if I entered a wrong number (or an invalid number). The program will keep running the if statement which requires a lot of computer power since it never stops. It is impossible to change your guess and the page crashes, because the browser is stuck in the while loop.
The simplest solution for this is to calculate if the new guess was correct when the player inputs a new number. So when onClickFunction is called again.
That way you never have to use a while loop. Although you have to calculate the random number somewhere else.
I hope that helped, if you have any question let me know!
Im a student currently studying from home and im seriously stuck on a Checksum problem. The script is supposed to validate the PESEL(Polish equivilant of a social security number i think), Anyway the checksum works as follows for
PESEL: 70051012347
PESEL:7,0,0,5,1,0,1,2,3,4 (7)
(Multiply each Pesel number by its corresponding check number)
CHECK:1,3,7,9,1,3,7,9,1,3
(Sum Each number)
SUM: + 7,0,0,45,1,0,7,18,3,12 =93
MOD: 93 MOD 10 = 3
10 - 3 = 7(last digit of pesel)
Where the MOD 10 doesn't equal 0, the result of sum%10 is subtracted from 10 and then matched with the final digit in the original number, if they match its good, if not its bad. All i need to have is a good or bad result.
I'm pretty sure I have all of this fine in my code and there's a simple solution i just cant see it. Any help at all would be massively appreciated.
<html>
<head>
<meta charset="utf-8">
<title>Pesel Checker</title>
<script type="text/javascript">
function peselgood(y)
{
//sample PESEL's
//type 1
//70051012347
//02070803628
//07020803628
//type 2
//83102570819
if (y.length == 11)
{
var arr = [1,3,7,9,1,3,7,9,1,3];
var sum = 0;
//hold original number
var a = parseInt(y);
//First 10 digits without check number and convert to array
y = y.substring(0,9);
y = parseInt(y);
var arr1 = new Array(10);
arr1 = y;
//muliply pesel digits by checksum digits
for (var i = 0; i < 10; i++)
{
sum += arr[i] * arr1[i];
}
sum = sum%10;
if (sum !== 0)
{
sum = 10-sum;
if(sum != a[10])
{
return false;
}
else
{
return true;
}
}
}
else
{
return false;
}
}
function checkpesel()
{
num = document.getElementById("peselfield").value
if (peselgood(num))
{
document.getElementById("peselfield").style.background="#00ff00";
}
else
{
document.getElementById("peselfield").style.background="#ff6666";
}
}
</script>
</head>
<body>
<div>
Check Sum Template
<br/><br/>
<form name="form">
PESEL:
<input type="text" id="peselfield" value="70051012347" /> <button type="button" onclick="checkpesel()">Check</button>
<br/><br/>
</form>
</div>
<br/><br/>
</body>
</html>
You have made a couple of mistakes. If you step through your code using a JavaScript debugger, you will find out exactly what goes wrong. The most important fact is, that you don't have to convert a string to an array of integers. JavaScript automatically understands when to convert a character to an integer.
This is my solution:
function peselgood(y)
{
if (y.length == 11)
{
var arr = [1,3,7,9,1,3,7,9,1,3];
var sum = 0;
//muliply pesel digits by checksum digits
for (var i = 0; i < 10; i++)
{
sum += arr[i] * y[i];
}
sum = sum%10 == 0 ? 0 : 10-sum%10;
return sum == y[10];
}
else
{
return false;
}
}
function checksum(p) { let i, s = +p[ i = 10 ]; while( i-- ) s += "1379"[ i % 4 ] * p[i]; return ! ( s % 10 ); }
<input id="pesel" placeholder="PESEL" autofocus>
<input type="button" value="check" onclick="alert( checksum(pesel.value) ? 'Ok' : 'Bad' )">