Write a program to calculate the square of a number when it is imputed must accept multiples of 2 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Write a program to calculate the square of a number when it is imputed must accept multiples of 2

24th Oct 2018, 6:56 PM
Abigail Agu
Abigail Agu - avatar
3 Answers
0
there are so many ways to answer this but let's start by breaking down what you're saying. 1. you're saying there has to be some input from the user. 2. you want the input to then be squared. 3. you want the input to accept multiples of 2 (i.e. 2, 4, 6, 8, etc.) 3 is really a repetition of 1 and 2 because if the program accepts all numeric inputs, and provides you the square of the inputs, it by definition will accept all multiples of 2. this leaves us with requirements 1 and 2. 1. getting user input. I'm going to use javascript here because it's a language that I'm familiar with and achieving the above is pretty straightforward. see my code here with explanations commented using the multi- line comment format "/* this is a comment */". you should be able to insert this in the code playground and see it in action. /*first we need to ask for input from the user. In javascript, this can be done with the "prompt" function. Next, we need to somehow store this value so that we can use it in our calculation. To do this, we call prompt() and store the value from the user in a variable we declared called "number". You'll note I've also included the function "parseInt" to ensure that an input is parsed to a numeric value */ var number = parseInt(prompt("Please enter a number", "")); /* once prompted, the user inputs some value. Above we used "parseInt" to make sure the input was a number by parsing the input to a number but, let's just make sure that the user actually input something by using a conditional statement (here the "if" statement) to check the condition that the input wasn't "null". */ if (number != null) { /*execute code to square number */ } 2. squaring user's input. /*now we need to square the input in the conditional statement. to see the result, we'll use the alert() function to output the squared number to the screen. by using alert and inputting number * number, we can output the square calculation*/ if (number != null) { alert (number * number); }
26th Oct 2018, 8:07 AM
Panayiotis Spanos
Panayiotis Spanos - avatar
0
ol tnx
26th Oct 2018, 8:53 AM
Abigail Agu
Abigail Agu - avatar
0
no problem. if this was helpful, please feel free to upvote my comment, mark it as the accepted amswer and throw me a follow :)
26th Oct 2018, 9:02 AM
Panayiotis Spanos
Panayiotis Spanos - avatar