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
Related
I have a C++n insertion sort function template, and it works fine when I give the function an array of integers, but when I give the function an array of doubles, although the array is indeed sorted afterwards, for some reason it alters the numbers in the sorted array.
The code:
#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename T>
void insertionSort(T ary[10], int size)
{
// Printing unsorted array
cout << "Array before sorting: [";
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]" << endl;
// Beginning of sorting
int j, t;
for(int i = 1; i < size; i++)
{
for (int i = 0; i < size; i++)
{
j = i;
while(j > 0 && ary[j] < ary[j-1])
{
t = ary[j];
ary[j] = ary[j-1];
ary[j-1] = t;
j--;
}
}
}
// Printing sorted array
cout << "Array after sorting: [" ;
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]\n" << endl;
}
int main()
{
cout << "*** INTEGER ARRAY INSERTION SORT ***" << endl;
int intAry[10] = {0};
for (int i = 0; i<= 9; i++)
{
intAry[i] = rand() % 100;
}
insertionSort(intAry, 10);
cout << "*** DOUBLE ARRAY INSERTION SORT ***" << endl;
double dAry[10] = {0};
for(int i = 0; i<=9; i++)
{
dAry[i] = (double)rand() / RAND_MAX * 100;
}
insertionSort(dAry, 10);
return 0;
}
The output:
You can see here that it changes the number in the array of doubles, like 14.1603 to 14.
Thank you for any help!
The problem is, you want to compare the double numbers, but when you're going through the loop, you use the int i and int j variables. Result is incorrect due to incompatible data type.
if you covert "double" the "int" data types, your problem will be solved.
Also you must change your array type to double.
I have this code. and I have a problem with it. When I run it for these numbers "1,1,1,1,1" it answers me right but when I use these numbers "2,1,3,2,2" or any other numbers it answers me wrong. What is the problem?
#include <iostream>
using namespace std;
int main() {
int size = 5;
int array1[size];
int i, j, *p;
int sum = 0;
p = &array1[j];
for (int i = 0; i < size; i++) {
cout << "give next number";
cin >> array1[i];
cout << "\n";
}
cout << "the array is:"
<< "\n";
for (int j = 0; j < size; j++) {
cout << array1[j] << "\n";
sum = sum + *p;
}
cout << "the sum of array elements is: " << sum;
return 0;
}
So you have one problem
p = &array1[j];
What you are doing is taking the address of jth element of an array. In you case j is uninitialized which leads to UB since j might contain any variable.
To fix this you can initialize j to 0 (j = 0). Or to just get an address of first element in array you can do following:
p = array;
Than comes your loop, which is summit value at address of arr[j] which is UB as I stated above.
cout << "the array is:" << "\n";
for (j = 0; j < size; j++) {
cout << array1[j] << "\n";
sum = sum + *(p + j);
}
Your problem here was that you were adding array1[0] all the time. (That is if you initialized j to 0).
Other things to note is that you are re declaring i and j
int i, j, *p;
...
for (int i = 0; ...)
...
for (int j = 0; ...)
You could do just
for (i = 0; ...)
...
for (j = 0; ...)
to set already declared variables to 0.
Here is entire program:
#include <iostream>
int main() {
int size = 5;
int array1[size];
int i, j, *p;
int sum = 0;
// p = &array1[j]; // UB j not initialized but used
/* solution 1
j = 0;
p = &array1[j]
*/
// solution 2 which is same as solution 1
p = array1; // gets address of array[0]
for (i = 0; i < size; i++) { // no need for `int` in front of i
// i is already declared above
// my preference is to declare i here
// and remove declaration above
std::cout << "give next number";
std::cin >> array1[i];
std::cout << "\n";
}
std::cout << "the array is:"
<< "\n";
for (j = 0; j < size; j++) { // same as above
std::cout << array1[j] << "\n";
sum = sum + *(p + j);
}
std::cout << "the sum of array elements is: " << sum;
return 0;
}
input:
give next number5
give next number4
give next number3
give next number2
give next number1
output
the array is:
5
4
3
2
1
the sum of array elements is: 15
This code will take the elements of the array from the user and then sort it. The user input limit is 20. I have an issue with a specific line which is if (a[i]==0)break; if I use break here the result shows garbage values. Otherwise, it works fine but I want the user to be able to run the program with 20 or fewer numbers. I meant they can simply enter 0 whenever they feel they are done, and so the loop breaks. I am giving the code below. Please try to give simple solutions and don't be toxic and snooty. Thank you.
//Sorting with user input array elements
void print(float a[], int n)
{
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
}
void sort(float a[], int n)
{
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
}
}
}
}
int main()
{
float a[20];
int size;
court << "Enter Floats and terminate with 0 (Highest limit is 20)" << endl;
for (int i = 0; i <= 20; i++) {
cout << "a[" << i << "] : ";
cin >> a[i];
if (a[i] == 0)
break;
}
size = sizeof(a) / sizeof(int);
cout << "\nGiven Values :: ";
print(a, size);
cout << endl;
sort(a, size);
cout << "Sorted Result :: ";
print(a, size);
}
The array has size 20. The user sets values until 0 is entered. That means that the other elements are uninitialized. These are the garbage values. You can fix it by saving the number of entered elements.
//Sorting with user input array elements
void print(float a[], int n)
{
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
}
void sort(float a[], int n)
{
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
}
}
}
}
int main()
{
float a[20];
int size{0};
court << "Enter Floats and terminate with 0 (Highest limit is 20)" << endl;
for (int i = 0; i < 20; i++) {
cout << "a[" << i << "] : ";
cin >> a[i];
if (a[i] == 0)
break;
++size;
}
cout << "\nGiven Values :: ";
print(a, size);
cout << endl;
sort(a, size);
cout << "Sorted Result :: ";
print(a, size);
}
There is also a problem in the for loop. The array has size 20 but the for loop starts with 0 and iterates until 20 inclusive. That are 21 iterations. I fixed it in my answer.
I was wondering if it was possible in C++ to parse through an array and retrieve the amount of times an integer appears in the array. I'm trying to make a histogram of the values, but currently am stuck as to how to continue.
It is a one-dimensional array if that matters and I am using this function to print the array:
void print(int a[], int n)
{
int j = 1;
cout << endl;
for(int i=0; i < n; i++)
{
if(!(j%6))
{
j=1; cout << endl << endl;
}
cout << right << setw(2) << a[i] << " ";
++j;
}
}
Which is giving me correct output in this screenshot:
http://i.imgur.com/P8Jzj1V.png
However, once I go to my histogram function (which I know is coded incorrectly) I am getting the following output:
http://i.imgur.com/WJtBjoF.png
Because with my current code it is printing asterisks based on a value taken from the array:
for (int i = 0; i < size; i++)
{
cout << a[i] << ":" << bar(a[i-1]);
cout << endl;
}
P.S. - The "bar" function just returns a string with a specified amount of '*' based on the number given to it.
I know the last bit is incorrect, but that's what I'm trying to fix.
There are two easy ways to go:
sort+count
Sort the array
Iterate through them all, and print summaries on encountering a different element / the end.
unordered_map
Create an std::unordered_map<int,int>
Iterate through the array incrementing the count for each encountered element when you encounter it.
Print the summary.
An array of size 2**sizeof(int)*CHAR_BIT is prohibitively big.
Let's see. You can keep a map with the counts of each element, being each element a key to the map:
for (int i = 0; i < size; i++)
{
int current = a[i];
//if it doesn't find it it returns
if (countMap.find(current) != countMap.end())end()
{
countMap[current]++;
} else
{
countMap[current] = 1;
}
}
I don't know if the syntax is totally correct, but something like this will get you what you want.
Figured it out.
int tempVal = 0;
int tempTwo = 0;
int counter = 0;
for (int i = 0; i < size; i++) // Checks for histogram output
{
tempVal = a[i];
for (int j = 0; j < size; j++)
{
if(a[j] == tempVal)
{
counter += 1;
}
}
if(tempVal != tempTwo)
cout << setw(3) << tempVal << " : " << bar(counter) << endl;
tempTwo = tempVal;
counter = 0;
}
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 );
}