I need to get the following Pseudocode to run in C++ // Pseudocode PLD Chapter 6
ID: 670465 • Letter: I
Question
I need to get the following Pseudocode to run in C++
// Pseudocode PLD Chapter 6 #2a & 2b, pg. 267
// Start
// Declarations
// num SIZE = 12
// num numbers[SIZE]
// num value = 0
// num counter = 0
// num total = 0
// num average = 0
// num diffFromAvg = 0
// num SENTINEL = -1
//
// output "Please enter a positive number: "
// input value
// while ((counter < SIZE) AND (value <> SENTINEL) )
// total = total + value
// numbers[counter] = value
// counter = counter + 1
// if (counter <> SIZE)
// output "Please enter a positive number: "
// input value
// endif
// endwhile
//
// if (counter > 0) then
// average = total/counter
// for i = 0 to counter - 1
// diffFromAvg = numbers[i] - average
// output "Number[",i,"]: ",numbers[i]," Difference from Average is",diffFromAvg
// endfor
// else
// output "Processing incomplete. No values in the array."
// endif
// Stop
Explanation / Answer
#include<iostream>
using namespace std;
int main()
{
int SIZE=12;
int numbers[SIZE];
int value=0;
int counter=0;
int total=0;
int average=0;
int diffFromAvg=0;
int SENTINEL=-1;
cout<<"please enter a positive number: ";
cin>>value;
while((counter<SIZE)&&(value!=SENTINEL)){
total=total+value;
numbers[counter]=value;
counter++;
if(counter!=SIZE){
cout<<"please enter a positive number: ";
cin>>value;
}
}
if(counter>0){
average=total/counter;
cout<<average<<endl;
for(int i=0;i<counter;i++){
diffFromAvg=numbers[i]-average;
cout<<"Number["<<i<<"]: "<<numbers[i];
cout<<" Difference from Average is "<<diffFromAvg<<endl;
}
}
else{
cout<<"Processing incomplete.No values in the array"<<endl;
}
return 0;
}
here average is int
but convert to double to get decimal places and also replace the
average=sum/counter to average=(double)sum/(double)counter;