I just started learning C++ in college and my task is to do the following: I have to write some code that will use iteration (i.e. looping) to calculate the cumulative sum of the items in an array of integers;
my code is:
int main() {
int myArray[] = {1,2,3,4,5};
int i;
int j;
j+= myArray[];
for(i=0;i<5;i++){
printf("%d\n",myArray[j]);
}
}
Although this code does not produce what I am looking for and I am confused as to what I should do next.
int main() {
int myArray[] = {1,2,3,4,5};
int sum = 0;
for(int i=0; i<5; i++)
sum += myArray[i] ;
std::cout << sum;
}
Here sum is initialized to 0 and each element in the array is added to the sum in a loop.
you can use std::accumulate to do the same, hence you dont worry about the size of the array.
#include <iostream>
#include <algorithm>
int main() {
int myArray[] = {1,2,3,4,5};
std::cout << std::accumulate(std::begin(myArray), std::end(myArray), 0);
}
Note that std::begin() and std::end() were introduced in C++11. For earlier versions, you will have to use pointers instead:
std::accumulate(myArray, myArray + 5, 0);
I've edited your code with comments and a line of code. please review them.
#include <cstdio>
int main() {
// Array and index into it.
int myArray[] = {1,2,3,4,5};
int i;
// Initialise sum to zero for starting.
int sum = 0;
// Adding whole array will not work (though it would be nice).
// Instead, go through array element by element.
// j += yArray[];
for (i = 0; i < 5; i++) {
// Add element to sum and output results.
sum += myArray[i];
printf ("Adding %d to get %d\n", myArray[i], sum);
}
// Output final result.
printf ("Final sum is: %d\n", sum);
}
Also note that I've used printf as per your question but you really should be using the C++ streams facilities for input and output.
The output of that code is:
Adding 1 to get 1
Adding 2 to get 3
Adding 3 to get 6
Adding 4 to get 10
Adding 5 to get 15
Final sum is: 15
Note that <algorithm> has a function for that:
const int myArray[] = {1,2,3,4,5};
const int sum = std::accumulate(std::begin(myArray), std::end(myArray), 0);
If you want to do the loop yourself, you may use the for-range (since c++11):
const int myArray[] = {1, 2, 3, 4, 5};
int sum = 0;
for (auto e : myArray) {
sum += e;
}
You need to put j+= myArray[] inside the loop and put i inside [] of myArray in order to perform the summation operation. Thereby, your code could be modified as follows to be matched to what you want to do. After summation of all the elements in the array, it exits for-loop, and print the final summation as in the second printf. Note that j was replaced by sum in order to be readable.
int main() {
int myArray[] = {1,2,3,4,5};
int sum=0; // sum
for(int i=0; i<5; i++){
sum += myArray[i];
printf("%d\n", myArray[i]);
}
printf ("Sum: %d \n", sum);
}
You can see a runnable code at this link. Hope this help.
int main() {
int yourArray[] = {1,2,3,4,5};
int sum = 0;
for(int i=0; i<5; i++) {
sum = sum + yourArray[i] ;
std::cout << sum;
}
}
In the above code, the for loop will iterate 5 times, each time a value in the array will be added to the sum variable.
In the first iteration, the value of sum will be 0, and the value at yourArray[0] will be 1, so sum = 0 + 1;.
In the second iteration, the value of sum will be 1, and the value at yourArray[1] will be 2, so sum = 1 + 2;.
And so on...
After each iteration is complete, we output the sum, which will be 1, 3, 6, 10, 15.
So 15 is the complete sum of all the values of the array.
Related
I have written a simple C++ program to find the minimum sum values of an array. I have arr[12] = {1, 2, 4, 8, 16,32, 64, 128, 256, 512, 1024, 2048}. I want to count how many minimum values from that array to fulfil int p. For example, p = 10, There's 2 index with minimum values that fulfill integer p, which is arr[1] = 2and arr[3] = 8. I solved this problem with some kind binary conversion method. I save these binaries into new array arr2[] and sum all of that binaries so I get the answer 2 in the example. But I encounter a problem, if the input is p = 1024, for some reason array values in second for loop not saving int m value from the first for loop. This only applies on 1024, not on other input (or not to be found yet).Can someone explain why this is happening?. Here is my code:
#include <stdio.h>
#include <conio.h>
int main()
{
int t, p, c=0;
int arr[12] = {1,2,4,8,16,32,64,128,256,512,1024,2048};
int arr2[c];
scanf("%d", &t);
while(t--)
{
int sum = 0, m = 0;
scanf("%d", &p);
for(int i = 11; i>=0; i--)
{
m = p/arr[i];
p = p - m*arr[i];
arr2[i] = m;
printf("%d ", m);
}
printf("\n");
for(int i = 11; i>=0; i--)
{
sum+=arr2[i];
printf("%d ", arr2[i]);
}
printf("\n SUM : %d \n", sum);
}
getch();
}
I think I have a simple mistake, but I couldn't find it.
change the value of c=0 to c=12, as I can see your arr2 array will be holding 12 values, one for each occurrences of values from arr array.
I want to have a function that returns the sum of different (non duplicate) values from an array: if I have {3, 3, 1, 5}, I want to have sum of 3 + 1 + 5 = 9.
My attempt was:
int sumdiff(int* t, int size){
int sum=0;
for (int i=0; i<=size;i++){
for(int j=i; j<=size;j++){
if(t[i]!=t[j])
sum=sum+t[i];
}
}
return sum;
}
int main()
{
int t[4]={3, 3, 1, 5};
cout << sumdiff(t, 4);
}
It returns 25 and I think I know why, but I do not know how to improve it. What should I change?
Put all the items in a set, then count them.
Sets are data structures that hold only one element of each value (i.e., each of their elements is unique; if you try to add the same value more than once, only one instance will be count).
You can take a look in this interesting question about the most elegant way of doing that for ints.
First of all, your loop should be for (int i=0; i<size;i++). Your actual code is accessing out of the bounds of the array.
Then, if you don't want to use STL containers and algorithms (but you should), you can modify your code as follows:
int sumdiff(int* t, int size){
int sum=0;
for (int i=0; i<size;i++){
// check if the value was previously added
bool should_sum = true;
for(int j=0; should_sum && j<i;j++){
if(t[i]==t[j])
should_sum = false;
}
if(should_sum)
sum=sum+t[i];
}
return sum;
}
int main()
{
int t[4]={3, 3, 1, 5};
cout << sumdiff(t, 4);
}
You could:
Store your array contents into an std::unordered_set first. By doing so, you'd essentially get rid of the duplicates automatically.
Then call std::accumulate to compute the sum
**wasthishelpful's answer was exactly what i was talking about. I saw his post after i posted mine.
So, you're trying to check the duplicate number using your inner loop.
However, your outer loop will loop 4 times no matter what which gives you wrong result.
Try,
Do only checking in inner loop. (use a flag to record if false)
Do your sum outside of inner loop. (do the sum when flag is true)
Here is another solution using std::accumulate, but it iterates over the original elements in the call to std::accumulate, and builds the set and keeps a running total as each number in the array is encountered:
#include <iostream>
#include <numeric>
#include <set>
int main()
{
int t[4] = { 3, 3, 1, 5 };
std::set<int> mySet;
int mySum = std::accumulate(std::begin(t), std::end(t), 0,
[&](int n, int n2){return n += mySet.insert(n2).second?n2:0;});
std::cout << "The sum is: " << mySum << std::endl;
return 0;
}
The way it works is that std::insert() will return a pair tbat determines if the item was inserted. The second of the pair is a bool that denotes whether the item was inserted in the set. We only add onto the total if the insertion is successful, otherwise we add 0.
Live Example
Insert array elements into a set and use the std::accumulate function:
#include <iostream>
#include <numeric>
#include <set>
int main()
{
int t[4] = { 3, 3, 1, 5 };
std::set<int> mySet(std::begin(t), std::end(t));
int mySum = std::accumulate(mySet.begin(), mySet.end(), 0);
std::cout << "The sum is: " << mySum << std::endl;
return 0;
}
My program have to sort an array in another array.
When I run the program it prints 1 2 3 -858993460 5 -858993460 7.
I can not understand where the mistake is in the code.
#include <iostream>
using namespace std;
int main()
{
const int N = 7;
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int max = arr[0];
for (int i = 1; i < N; i++)
{
if (max < arr[i])
max = arr[i];
}
int sort_arr[N];
for (int j = 0; j < N; j++)
{
sort_arr[arr[j] - 1] = arr[j];
}
for (int i = 0; i < N; i++)
{
cout << sort_arr[i] << " ";
}
return 0;
}
Okay lets face the problems in your code.
The "weird" numbers you see there, came from the uninitialzied array sort_arr. What do I mean by uninitialized? Well sort_arr is a little chunck somewhere in your memory. Since a program usually does not clear its memory and rather claims the memory it used as free, the chunk of sort_arr may contain bits and bytes set by another program. The numbers occure since these bytes are interpreted as an integer value. So the first thing to do would be to initialize the array before using it.
sort_arr[N] = { 0, 0, 0, 0, 0, 0, 0 };
Now why did these numbers occure? Well you're probably expecting your algorithm to set all values in sort_arr which would result in an sorted array, right? Well but your algorithm isn't working that well. See this line:
sort_arr[arr[j] - 1] = arr[j];
What happens when j is 1? arr[1] is then evaluated to 17 and 17 - 1 equals 16. So sort_arr[arr[1] - 1] is the same as sort_arr[16] which exceeds the bounds of your array.
If you want to program a sorting algorithm by your self than I would recommend to start with an simple bubble sort algorithm. Otherwise, if you only need to sort the array have a look at the algorithm header. It is fairly simple to use:
#include <iostream>
#include <algorithm>
#include <iterator> // << include this to use begin() and end()
using namespace std;
int main()
{
const int N = 7;
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int sort_arr[N] = { 0, 0, 0, 0, 0, 0, 0 };
copy(begin(arr), end(arr), begin(sort_arr));
sort(begin(sort_arr), end(sort_arr));
for (int i = 0; i < N; i++)
{
cout << sort_arr[i] << " ";
}
cout << endl;
}
By the way. You're looking for the biggest value in your array, right? After you have sorted the array sort_arr[N - 1] is the biggest value contained in your array.
If you want to sort a array into another array then one way is you make a copy of the array and then use the sort function in the standard library to sort the second array.
int arr[10];
int b[10];
for(int i=0;i<10;i++)
{
cin>>arr[i];
b[i]=arr[i];
}
sort(b,b+10);
// this sort function will sort the array elements in ascending order and if you want to change the order then just add a comparison function as third arguement to the sort function.
It seems that you think that sort_arr[arr[j] - 1] = arr[j] will sort arr into sort_arr. It won't.
Sorting is already written for you here: http://en.cppreference.com/w/cpp/algorithm/sort You can use that like this:
copy(cbegin(arr), cend(arr), begin(sort_arr));
sort(begin(sort_arr), end(sort_arr));
Live Example
My guess is this is an attempt to implement a type of counting sort. Note that variable length arrays aren't normally allowed in C++ or some versions of C. You could use _alloca() to allocate off the stack to get the equivalent of a variable length array: int * sort_arr = (int *)_alloca(max * sizeof(int)); .
#include <iostream>
using namespace std;
int main()
{
const int N = 7;
// assuming range of values is 1 to ...
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int max = arr[0];
for (int i = 1; i < N; i++)
{
if (max < arr[i])
max = arr[i];
}
int sort_arr[max];
for (int i = 0; i < max; i++)
{
sort_arr[i] = 0;
}
for (int j = 0; j < N; j++)
{
sort_arr[arr[j] - 1]++;
}
for (int i = 0; i < max; i++)
{
while(sort_arr[i])
{
cout << i+1 << " ";
sort_arr[i]--;
}
}
return 0;
}
I tried to calculate average and when I enter 1 2 3 0 , the average is 2.00 but when I enter 10 20 90 100 0,the average is 227871776.00. I am not able to identify what is going wrong here. I feel like my sum and count is not working properly but I can't figure out why.
double calculateAverage(int numbers[], int count )
{
int sum = 0;
double average;
while (count < arraysize && numbers[count] != 0)
{
count ++;
}
for (int i= 0 ; i < count; i++)
{
sum += numbers[i];
}
average = static_cast<double>(sum) /count;
return average;
}
Why bother even making your own count loop, when you have std:accumulate.
#include <numeric>
#include <iostream>
double calculateAverage(int numbers[], size_t count)
{
int sum = std::accumulate(numbers, numbers + count, 0);
return sum / count;
}
int main()
{
//int numbers[] = {1, 2, 3, 4, 5};
int numbers[] = {10, 20, 90, 100};
std::cout << "average is " <<
calculateAverage(numbers, sizeof(numbers) / sizeof(int)) << '\n';
}
Your code was quite confused. Why pass a count if you're going to count the array anyway? Also 0 is a valid value in the array and so it makes a flawed sentinel value.
#include<iostream>
using namespace std;
double calculateAverage(int numbers[], int count )
{
int sum = 0; //sum is used to add all the values in the array
double average;
for (int i= 0 ; i < count; i++)
sum += numbers[i];
average = static_cast<double>(sum) /count;
return average;
}
int main()
{
int lim; //size of the array
cout<<"Enter the number of elements in array\n";
cin>>lim;
cout<<"Enter the values \n";
int num[lim]; //the array is initialized to desired size
for(int i=0;i<lim;i++)
cin>>num[i]; //the values are taken from user
cout<<"\nAverage = "<<calculateAverage(num,lim)<<"\n"; //the array and the size of array is passed to calculate average function or you can even calculate size of array using (sizeof(array)/sizeof(array[firstelement])
return 0;
}
Recreate the code overall
It is hard to understand (your code).
Mine:
double calculateAverage(double numbers[], double count )
{
double sum = 0;
double average=0;
for(int counter=0;counter<count;counter++)
{
sum+=numbers[counter];
}
cout<<sum<<"\n";
average=sum/count;
return average;
}
Explaination:
First the function will take an array of double
and count is how many is there in the array (I tried to stick into your code)
The for loop runs based on the count variable.
the sum adds the value of the element in the array numbers.
Divide to get the average.
numbers[count] != 0 could produce errors when you have 0 appear earlier in the array. Also, where do you initialize arraysize? It could be null somehow or a very weird number. I recommend calling the numbers length instead. But there's no reason to use the while loop bc you have an array size already known
I am trying to write a simple program that create 2D array and then perform a task that add up the sum of element in that 2D array. Here is my code so far:
#include <iostream>
#include <stdio.h>
int main()
{
int array [20][20];
int i, j;
int num_elements;
float sum;
for (i=0; i<num_elements; i++)
{
sum = sum + array[i];
}
return(sum);
// output each array element's value
for ( i = 0; i < 20; i++ )
{
for ( j = 0; j < 20; j++ )
{
printf("a[%d][%d] = %d\n", i,j, array[i][j] );
}
}
system ("PAUSE");
return 0;
}
I need to create this program before I start my next question which is to modify the program so that it use functions to break it down.
I have an error that pop up which says the following:
error C2111: '+' : pointer addition requires integral operand
Also the following peice of code
sum = sum + array[i];
The problem here it says expression must have arithmetic or unscoped enum type.
Can anyone help me with this? Explaining where I'm going wrong. I have research the problem online but still can't fix it, as I try to fix it, I get more errors.
If someone can give me an example of code, much appreciated
New Code: Works. Just need to print out the sum
#include <iostream>
#include <stdio.h>
int main()
{
int array [3][5] =
{
{ 1, 2, 3, 4, 5, }, // row 0
{ 6, 7, 8, 9, 10, }, // row 1
{ 11, 12, 13, 14, 15 } // row 2
};
int i, j=0;
int num_elements=0;
float sum=0;
for (i=0; i<num_elements; i++)
{
sum = sum + array[i][j];
}
// output each array element's value
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 5; j++ )
{
printf("a[%d][%d] = %d\n", i,j, array[i][j] );
}
}
system("PAUSE");
return(sum);
}
You defined the array as two dimensional. However in the loop
for (i=0; i<num_elements; i++)
{
sum = sum + array[i];
}
you use it as one dimensional. But in fact you operate with pointers to one-dimensional arrays. And compiler reports about thsi error.
Moreover neither variable num_elements nor variable sum were initialized. And nobody sees where values for the array were entered.:)
Also this return statement has no sense
return(sum);
Your plan of actions is following:
1. Enter values for elements of the array
2. Print out the entered array
3. Calculate the sum of all elements
4. Print out the sum.