Average of odd cells? - c++

For an exercise I am doing, I am supposed to find out the average of the items contained in odd numbered cells of an array and some other things. Finding the average of the odd numbered cells in the only thing I'm having a problem with. Here is my code, what am I doing wrong? The final function is the odd numbered cells average function. Thanks.
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE = 1000;
int randoms[SIZE];
int sum2 = 0;
int top = 0;
int maximum = 0;
int highest(int randoms[]);
int findsum(int randoms[]);
int average(int randoms[], int sum);
int oddavg(int randoms[]);
int main()
{
int sum = 0;
int top = 0;
int avg = 0;
int oddaverage = 0;
for (int i = 0; i < SIZE; i++)
{
randoms[i] = (rand() % 5000 + 1);
cout << randoms[i] << setw(10) << " ";
}
cout << endl << endl;
cout << "The sum of the values in the array is ";
sum = findsum(randoms);
cout << sum << endl;
cout << endl << endl;
cout << "The highest value in the array is ";
top = highest(randoms);
cout << top << endl;
cout << endl << endl;
cout << "The average of all of the numbers in the array is ";
avg = average(randoms, sum);
cout << avg << endl;
cout << endl << endl;
cout << "The average of all of the numbers in the odd cells is ";
oddaverage = oddavg(randoms);
}
int findsum(int randoms[])
{
for (int i = 0; i < SIZE; i++)
{
sum2 += randoms[i];
}
return sum2;
}
int highest(int randoms[])
{
for (int i = 0; i < SIZE; i++)
{
if (randoms[i] > maximum)
{
maximum = randoms[i];
}
}
top = maximum;
return top;
}
int average(int randoms[], int sum)
{
int avg = 0;
for (int i = 0; i < SIZE; i++)
{
avg = (sum / SIZE);
}
return avg;
}
int oddavg(int randoms[])
{
int avg = 0;
int sum = 0;
for (int i = 0; i < SIZE; i++)
{
if (randoms[i] / 2 == 1)
{
sum += randoms[i];
}
}
avg = sum / SIZE;
return avg;
}

Doing the odd/even test (using modulo as many have suggested) in this case is totally redundant, since the loop doesn't do anything else.
You can just use a stride of 2 and start at the first odd element:
for (int i = 1; i < SIZE; i += 2)
{
sum += randoms[i];
}
Then it's just a matter of dividing out by half of SIZE. If that number is even, then there are SIZE/2 odd numbers. If it's odd, then there are lbound(SIZE/2)+1 odd numbers. Fortunately, you can take advantage of integer truncation and just do:
double avg = double(sum) / double((SIZE+1) / 2);
And you don't even have to worry about divide-by-zero =)

should be if (randoms[i] % 2 == 1)
Also you need to count the number of odd numbers.

randoms[i] / 2 == 1, this will be true only when a cell value is 2 or 3, this is certainly not what you need to do.
If you need to sum values of cells with odds index then it should be if (i % 2 == 1). If instead you are looking for odd values (in any cell) it should be if (randoms[i] % 2 == 1).
Mind that % is the modulo operation which returns the integer remainder of the integer division.
And since you are calculating an average you should divide by the found amount of elements, not by the total.

int oddavg(int randoms[])
{
int cnt = 0;
int avg = 0;
for (int i = 0; i < SIZE; i++)
{
if ( randoms[i] % 2 != 0 )
{
++cnt;
avg += randoms[i];
}
}
return ( cnt == 0 ? avg : avg / cnt );
}

Related

Repeating digits in number C++

The task is to write a function which takes a number and finds the digit that is repeated most times in that number. It should print the found digit and the times it is repeated.
I had a problem with the case when two digits were repeating a same number of times.
For example with given number 788995 it should return 8 -> 2 \\ 9 -> 2
How can I print that?
Here is the function:
void maxDigitInNumber (long long n)
{
if (n < MIN || n > MAX)
{
cout << -1;
return;
}
n = abs(n);
int numOfDigits = (int)log10(n)+1;
int digits[100];
int helper[100] = {0};
int counter = 0;
int maxSize = 0;
int number = 0;
for (int i = 0; i <= numOfDigits; i++)
{
digits[i] = n%10;
n /= 10;
}
for(int i = 0; i < numOfDigits; i++)
{
if(helper[i] == 0)
{
counter = 0;
for(int j = i; j < numOfDigits; j++)
{
if(digits[j] == digits[i])
{
counter++;
helper[j] = 1;
}
if(counter > maxSize)
{
maxSize = counter;
number = digits[i];
}
}
}
}
if (number == 0)
{
for (int i = 0; i < numOfDigits; i++)
{
cout << digits[i] << "->" << maxSize << endl;
}
}
else
{
cout << number << "->" << maxSize << endl;
}
}
You should store the count for each digit before picking the max. After that you can pick the max value among all counts, and print all entries matching that max:
int count[10] = {0};
do {
count[n%10]++;
n /= 10;
} while (n != 0);
int maxCount = 0;
for (int i = 0 ; i != 10 ; i++) {
maxCount = max(maxCount, count[i]);
}
bool first = true;
for (int i = 0 ; i != 10 ; i++) {
if (count[i] == maxCount) {
if (!first) {
cout << " \\\\ ";
} else {
first = false;
}
cout << i << "->" << maxCount;
}
}
There are only 10 digits, so an histogram of the digits in the number takes up only 10 words.
// ....
int hist[10] = {}; // Full tally available for further analysis
int max_count = 0; // result.
int max_digit = -1;
for (int i = 0; i <= numOfDigits; i++)
{
int digit = n % 10;
if (++hist[digit] > max_count)
{
max_count = hist[digit]; // could also be ++max_count ;)
max_digit = digit;
}
n /= 10;
}
Here are some algorithms you can use:
// prints digits with a certain score:
void print_if_score_is(const int hist[10], int score)
{
for (int i = 0; i < 10; ++i)
if (hist[i] == score)
std::cout << " digit: " << i << ", score: " << score << "\n";
}
int get_next_best_score(const int hist[10], int score)
{
int new_max = -1;
for (int i = 0; i < 10; ++i)
if (hist[i] > new_max && hist[i] < score)
new_max = i;
return new_max;
}
Usage:
// ....
std::cout << "Digit most frequently found: \n";
print_if_score_is(hist, max_count);
std:: cout << "next in list: \n";
int next_best = get_next_best_score(hist, max_count);
print_if_score_is(hist, next_best);
//...
Structure your program like this:
One function accepts the number to be analyzed and returns a std::multiset. multiset allows multiple entries for the same key. So for the number 788995 you would end up with a multiset { 1: [5, 7], 2: [8, 9] }
Another function analyzes the multiset and returns the numbers for the highest-ranking key in the set.

Getting wrong lowest value, if I separate the lowest and high (for) loop then I get the correct lowest value

In 3rd for loop comparison is made for smallest and largest element, I get the wrong value for smallest element. but why I don't understand.
If I divide 3rd loop into 2 for loop, one for lowest element and one for highest element, then I get the correct answer.
#include <iostream>
using namespace std;
int main()
{
float rainfall[12];
float total = 0.0;
float avg = 0.0;
float high, lowest;
for (int i = 0; i < 12; i++) {
cin >> rainfall[i];
}
high = rainfall[0];
lowest = rainfall[0];
for (int i = 0; i < 12; i++) {
total = total + rainfall[i];
avg = total / 12;
}
for (int i = 0; i < 12; i++) {
if (rainfall[i + 1] < lowest) {
lowest = rainfall[i + 1];
}
if (rainfall[i + 1] > high) {
high = rainfall[i + 1];
}
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << total << endl;
cout << avg << endl;
cout << high << endl;
cout << lowest << endl;
return 0;
}
Your code has undefined behaviour, as you're accessing rainfall[i+1] for i = 11.You should have started at i = 1, and left it as rainfall[i].
Notes:
declare variables at the point where you first need them
the calculation of avg should be performed just once

How to throw out a value in an array

I'm creating a diving calculator program. Asks for the level of difficulty. the program then asks for the 7 scores from judges 1-7, stores them in an array, throws out the smallest and largest values then finds the sum of the the remaining. The remaining is then multiplied by the level of difficulty and 0.6. My issue is with my findLargest function, it's as if i'm not calling it all. CODE:
#include <iostream>
using namespace std;
int judgesScore[7]; //array name
float difficulty; //between 1.2 & 3.8
float finalScore;
void collectInput() {
int input;
for (int i=0; i < 7; i++){
input = -1;
while (input < 0 || input > 10) {
cout << "Enter the score of judge " << i+1 << ": ";
cin >> input;
}
judgesScore[i]=input;
}
}//end collectInput
int findsmallest () {
int smallest = 0;
for (int i = 1; i < 7; i++){
if (judgesScore[i] < judgesScore[smallest]){
smallest = i;
}
}
return smallest;
}//end smallest
int findlargest () {
int largest = 0;
for (int i = 1; i < 7; i++){
if (judgesScore[i] < judgesScore[largest]){
largest = i;
cout << "the largest is: "<<largest;
}
}
return largest;
}//end largest
int sumOfScore(){
int smallest = findsmallest();
int largest = findlargest();
int sum = 0;
for(int i =0; i <7; i++){
if( i !=smallest && i !=largest){
sum+= judgesScore[i];
}
}
return sum;
}
int main(int argc, char *argv[]){
while (!(difficulty >= 1.2 && difficulty <= 3.8) ){
cout << "Please enter the level of difficulty from 1.2 - 3.8: ";
cin >> difficulty;
}//end of while
collectInput();
cout << "the sum of scores is "<<sumOfScore() << endl;
finalScore = (sumOfScore() * difficulty) * 0.6;
cout
<< "at a difficulty level of " << difficulty << "\n"
<< "Final Score: " << finalScore << "\n";
Try this! Your printing the index for the largest should be outside the for loop, and some modifications in comparison.
int findlargest () {
int j = 0, largest = judgesScore[0];
for (int i = 1; i < 7; i++){
if (judgesScore[i] < largest){
largest = judgesScore[i];
j = i;
}
}
cout << "the largest is: "<< j;
return j;
}//end largest
your findlargest function is the same with findsmallest function, so the result is smallest == largest.Please careful~ ^_^
int findlargest () {
int largest = 0;
for (int i = 1; i < 7; i++){
if (judgesScore[i] > judgesScore[largest]){
largest = i;
cout << "the largest is: "<<largest;
}
}
return largest;
}//end largest

How to add up a certain group of number in an array?

Hey so I have function that needs to add up a certain number of even numbers in an array based off user input. Here's my approach so far:
function call:
cout << "The sum of the first " << userSum << " even numbers is: " <<
SumEvens(list, SIZE, userSum);
function definition:
int SumEvens(int arr[], const int size, int evensAdd)
{
int sum = 0;
for (int i = 0; i <= size; i++){
for (int j = 0; j <= evensAdd; j++){
if (arr[i] % 2 == 0)
sum += arr[i];
}
}
return sum;
}
I'm Not sure if i need the double for loop here, but it seems necessary so that i can go through every number and then only select the ones that i need.
Now whenever I run this program and tell it to add up the numbers it spits out garbage, so I was seeing if you guys could point out any glaring flaws in the code. Thanks!
Your implementation is incorrect:
int SumEvens(int arr[], const int size, int evensAdd)
{
for(int i= 0; i < size; i++){
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << size << " " << evensAdd << std::endl;
int sum = 0;
for (int i = 0; i <= size; i++){
if(evensAdd==0) return sum
if (arr[i] % 2 == 0){
sum += arr[i];
evensAdd--;
}
}
}
return sum;
}
This doesn't break on evenAdd > size

(c++) Function calculating average returns (first score / total number of scores)?

So the program gathers a number of scores specified, then displays them in ascending order, then is supposed to show the average score. But right now, it only takes the first score displayed, and is divided by the number of scores. How can I make it display correctly?
#include <iostream>
#include <iomanip>
using namespace std;
void sortArray(int*, int);
double getAverage(int*, int);
int main()
{
int *scores;
int num_Tests;
cout << "How many test scores would you like to enter?" << endl;
cin >> num_Tests;
scores = new int[num_Tests];
cout << "\nEnter score number (do not use negative numbers):\n";
for (int count = 0; count < num_Tests; count++)
{
cout << count + 1 << ". ";
cin >> scores[count];
}
sortArray(scores, num_Tests);
cout << "\n\n";
cout << "\n\n________________________________________________________________________________" << endl;
cout << "Test Score List (in ascending order)" << endl;
cout << "________________________________________________________________________________" << endl;
for (int count = 0; count < num_Tests; count++)
{
cout << count + 1 << ". ";
cout << scores[count] << endl;
}
cout << "\nAverage test score: " << getAverage(scores, num_Tests) << endl;
return 0;
}
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
double avgScore = 0.0;
ttlScore += *scores;
avgScore = ttlScore / size;
return avgScore;
}
void sortArray(int *scores, int size)
{
int temp;
bool swap;
do
{ swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (scores[count] < scores[count + 1])
{
temp = scores[count];
scores[count] = scores[count + 1];
scores[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
You need to loop through your scores array to add them, you cannot just do ttlScore += *scores, it needs to be ttlScore += scores[index]
Example:
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
for (int i = 0; i < size; i++)
{
ttlScore += scores[i];
}
return ttlScore / size;
}
getAverage logic is not correct. You are adding just first number. Add is as below:
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
double avgScore = 0.0;
for(int i=0;i<size;i++)
{
ttlScore += *(scores+i);
}
avgScore = ttlScore / size;
return avgScore;
}
*scores references the start of the array. You need to sum over all of the values of the array pointed to:
for (int i=0; i < size; i++)
{
ttlScore += scores[i];
}
avgScore = ttlScore / size;
return avgScore;
I think these will help you,
double getAverage(int *scores, int size){
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{
sum += scores[i];
}
avg = (double)sum / size;
return avg;
}
Try and let me know if any problem?
I'm new to programming but here is what I have.
//average function
double average(int* pnData)
{
double result;
int sum = 0; //declare and initialize our variables
int count = 0;
for (int i = 0; i < pnData[i]; i++)
{
sum += pnData[i]; //sum = sum + elements of our array
count++; //increment count
}//end of for loop
result = sum/(double)count;
return result;
}//end of function average
This way you do not have to know the length or count of the array.