Take static array with 10 random 2 digit numbers like
<!DOCTYPE html>
<html>
<head>
<title>Array Operations</title>
</head>
<body>
<button onclick="performOperations()">Perform Operations</button>
<script>
let A = [12, 87, 34, 56, 34, 24, 56, 24, 65, 22];
function getMax() {
let max = A[0];
for (let i = 1; i < A.length; i++) {
if (A[i] > max) {
max = A[i];
}
}
return max;
}
function sortAscending() {
let sortedArray = A.slice();
for (let i = 0; i < sortedArray.length; i++) {
for (let j = 0; j < sortedArray.length - 1 - i; j++) {
if (sortedArray[j] > sortedArray[j + 1]) {
let temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
}
}
}
return sortedArray;
}
function sortDescending() {
let sortedArray = A.slice();
for (let i = 0; i < sortedArray.length; i++) {
for (let j = 0; j < sortedArray.length - 1 - i; j++) {
if (sortedArray[j] < sortedArray[j + 1]) {
let temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
}
}
}
return sortedArray;
}
function getSum() {
let sum = 0;
for (let i = 0; i < A.length; i++) {
sum += A[i];
}
return sum;
}
function getIndex() {
for (let i = 0; i < A.length; i++) {
if (A[i] === 34) {
return i;
}
}
return -1;
}
function performOperations() {
console.log("Maximum from the array:", getMax());
console.log("Sorted in ascending order:", sortAscending());
console.log("Sorted in descending order:", sortDescending());
console.log("Sum of the whole array:", getSum());
console.log("Index of value 34:", getIndex());
}
</script>
</body>
</html>
Comments
Post a Comment