Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Benford’s law states that positive integers exhibit a certain behavior, if the n

ID: 671432 • Letter: B

Question

Benford’s law states that positive integers exhibit a certain behavior, if the numbers are truly random. For example, suppose the following numbers are collected at random (the -1 at the end denotes the end of the input):

Benford's law states that approximately 31% of the numbers will start with the digit '1'. In the example above, there are a total of 9 inputs, and 3 start with a '1' --- so 33% start with a 1. You can read more about Benford's law on Wikipedia. A practical application of Benford's law is the detection offraud.

Write a complete C++ program that inputs a collection of positive integers, followed by a -1, and then outputs the percentages of numbers that start with '1', '2', '3', ..., '9'. For example, given the following input:

your program should produce the following output:

Hint: input each integer as a string, not as an integer. Then access the first character of the string (remember a string is an array of characters) and see if that character is a '1', or a '2', or a '3', etc. Count each starting digit.

Explanation / Answer

#include<iostream>
#include<string>

using namespace std;


int main() {
int count[9],sum=0;
for(int i=0;i<9;i++){
count[i]=0;
}
string input;
while(input!="-1"){
cout<<"enter the integers: ";
cin>>input;
if(input[0]=='1'){
count[0]++;
}else if(input[0]=='2'){
count[1]++;
}else if(input[0]=='3'){
count[2]++;
}else if(input[0]=='4'){
count[3]++;
}else if(input[0]=='5'){
count[4]++;
}else if(input[0]=='6'){
count[5]++;
}else if(input[0]=='7'){
count[6]++;
}else if(input[0]=='8'){
count[7]++;
}else if(input[0]=='9'){
count[8]++;
}else{
continue;
}
sum=sum+1;


}
double percent;

for(int i=0;i<9;i++){

percent=((double)count[i]/(double)(sum))*100;
cout<<(i+1)<<"'s "<<count[i]<<", "<<percent<<"%"<<endl;
}
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote