35.8k views
3 votes
Can someone please write aprogram in JAVASCRIPT that codes all the functions in this picture to get the output. Must use math logic in code.

Can someone please write aprogram in JAVASCRIPT that codes all the functions in this-example-1

1 Answer

5 votes

Answer:

// Declare variables to hold the number of people attending Thanksgiving dinner and the votes for each pie type

let numPeople;

let pieVotes = {};

// Ask the user for the number of people attending Thanksgiving dinner

numPeople = prompt("How many people are coming to Thanksgiving dinner?");

// Continually ask the user for the number of votes for each pie type until a viable value is found

while (true) {

// Ask the user for the number of votes for each pie type

pieVotes.apple = prompt("How many votes for apple pie?");

pieVotes.pumpkin = prompt("How many votes for pumpkin pie?");

pieVotes.pecan = prompt("How many votes for pecan pie?");

pieVotes.cherry = prompt("How many votes for cherry pie?");

// Check that the number of votes given is acceptable based on the number of people attending dinner

if (checkVotes(pieVotes, numPeople)) {

break;

} else {

console.log("Invalid vote count. Please try again.");

}

}

// Calculate the total number of votes and the number of people who did not vote

let totalVotes = 0;

for (let pie in pieVotes) {

totalVotes += pieVotes[pie];

}

let numNotVoted = numPeople - totalVotes;

// Print the votes for each pie type, the total vote count, and the number of people who did not vote

console.log(`Apple pie: ${pieVotes.apple} votes`);

console.log(`Pumpkin pie: ${pieVotes.pumpkin} votes`);

console.log(`Pecan pie: ${pieVotes.pecan} votes`);

console.log(`Cherry pie: ${pieVotes.cherry} votes`);

console.log(`Total vote count: ${totalVotes}`);

console.log(`Number of people who did not vote: ${numNotVoted}`);

// Check that the number of votes given is acceptable based on the number of people attending dinner

function checkVotes(votes, numPeople) {

let totalVotes = 0;

for (let pie in votes) {

totalVotes += votes[pie];

}

return totalVotes <= numPeople;

}

User Pieter Van Den Ham
by
7.1k points