Learn JavaScript selection and loop structure with examples
Question 1.Make a JavaScript program which will take a student roll number (1 to 5) as a key and will print corresponding name (1 for “Jahid”, 2 for “Siful”, 3 for “Imran”, 4 for “Tarek”, 5 for “Shahad” ) otherwise will print “Unknown Roll” using switch-case structure.
Answer:
<script>
var roll=parseInt(prompt("Enter Roll number (1-5)"));
switch(roll){
case 1:
document.write("Jahid");
break;
case 2:
document.write("Siful");
break;
case 3:
document.write("Imran");
break;
case 4:
document.write("Tarek");
break;
case 5:
document.write("Shahad");
break;
default:
document.write("Unknown roll number");
break;
}
</script>
Question 2. Make a JavaScript program which will take a number and only print if the number is greater than 50.
Answer:
<script>
n= parseInt(prompt("Enter a number"));
If(n>50){
document.write(n);
}
</script>
Question 3. Make a JavaScript program which will print Male if n=0 otherwise will print Female.
Answer:
<script>
n= parseInt(prompt("Enter a number"));
if(n==0){
document.write(“Male”);
}else{
document.write(“Female”);
}
</script>
Question 4. Make a JavaScript program which will print n to m numbers according to input n, m using while, for and do-while loop.
Answer:
for-Loop
<script>
n= parseInt(prompt("Enter number(n)"));
m= parseInt(prompt("Enter number(m)"));
for(i=n;i<=m;i++){
document.write(i);
}
</script>
while loop
<script>
n= parseInt(prompt("Enter number(n)"));
m= parseInt(prompt("Enter number(m)"));
i=n;
while(i<=m){
document.write(i);
i++;
}
</script>
do-while loop
<script>
n= parseInt(prompt("Enter number(n)"));
m= parseInt(prompt("Enter number(m)"));
i=n;
do{
document.write(i);
i++;
}while(i<=m);
for-in loop
<script>
var data=[3,4,56,68,65,4,4,3];
for(var i in data){
document.write(data[i]);
}
Question 5. Make an array with five names and print the array with for-in loop.
Answer:
<script>
names=[“Jahid”,”Ridon”,”Dara”,”Mukti”,”Shahad”];
for(index in names){
document.write(names[index]);
}
</script>
Question 6. Make a JavaScript program which takes a score and will print the grade as the following criteria:
a.If score is greater or equal 90 and less or equal 100 than will print A
b.If score is greater or equal 80 and less or equal 89 than will print B
c.If score is greater or equal 70 and less or equal 79 than will print C
d.Otherwise will print F
Answer:
<script>
score= parseInt(prompt("Enter your score"));
if(score>=90 && score<=100){
document.write(“A”);
}else if(score>=80 && score<=89){
document.write(“B”);
} else if(score>=70 && score<=79){
document.write(“C”);
}else{
document.write(“F”);
}
</script>
Comments 0