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.
Related
This is my first post and hope I'm not doing anything wrong.
I am trying to write a program that find the first value of the vector that reach k-occurrences in it.
For example, given this vector and k=3:
1 1 2 3 4 4 2 2 1 3
I would see 2 as output, because 2 is the first number reaching the 3rd occurrence.
The following code is what I tried to run, but somehow output is not correct.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> vettore;
int k;
int a,b,i;
int occ_a;
int occ_b;
cout<< "Write values of vector (number 0 ends the input of values)\n";
int ins;
cin>>ins;
while(ins)
{
vettore.push_back(ins); //Elements insertion
cin>>ins;
}
cout<<"how many occurrences?\n"<<endl;;
cin>>k;
if(k>0)
{
int i=0;
b = vettore[0];
occ_b=0;
while(i< vettore.size())
{
int j=i;
occ_a = 0;
a = vettore[i];
while(occ_a < k && j<vettore.size())
{
if(vettore[j]== a)
{
occ_a++;
vettore.erase(vettore.begin() + j);
}
else
j++;
}
if(b!=a && occ_b < occ_a)
b = a;
i++;
}
cout << b; //b is the value that reached k-occurrences first
}
return 0;
}
Hours have passed but I have not been able to solve it.
Thank you for your help!
Your code is difficult to read because you are declaring variables where they are not used. So their meanings is difficult to understand.
Also there is no need to remove elements from the vector. To find a value that is the first that occurs k-times is not equivalent to to change the vector. They are two different tasks.
I can suggest the following solution shown in the demonstrative program below.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = { 1, 1, 2, 3, 4, 4, 2, 2, 1, 3 };
size_t least_last = v.size();
size_t k = 3;
for ( size_t i = 0; i + k <= least_last; i++ )
{
size_t count = 1;
size_t j = i;
while ( count < k && ++j < least_last )
{
if ( v[j] == v[i] ) ++count;
}
if ( count == k )
{
least_last = j;
}
}
if ( least_last != v.size() ) std::cout << v[least_last] << '\n';
return 0;
}.
The program output is
2
The idea is to find the last position of the first element that occurs k-times. As soon as it is found the upper limit of the traversed sequence is set to this value. So if there is another element that occurs k-times before this limit then it means that it occurs the first compared with already found element.
Im trying set an array to have always same value in first position, but idk how to do that. for example array[10] always array[0] = 100, then continue add ohters number like: array[100,1,2,3.....], loop array[100,1,2,3.....] etc.
int main() {
int arrayNumber[10];
while (true)
{
for (int i = 0; i < 10; i++)
{
arrayNumber[0] = 100;
printf("%d\n", arrayNumber[i]);
Sleep(100);
}
}
}
Set the first value outside the loop and start the loop at 1.
arrayNumber[0] = 100;
for (int i = 1; i < arraysize; i++)
{
arrayNumber[i] = i;
}
int main() {
int arrayNumber[10] = {100};
for (int i = 1; i < 10; i++) {
arrayNumber[i] = i;
}
}
The first operator above declares the array and initializes the first it's element with the value 100, then the loop fills other elements with 1, 2, 3, ..., 9.
Since your asked about C++ let introduce C++-like solution below.
#include <numeric>
int main() {
int arrayNumber[10] = {100};
std::iota(arrayNumber + 1, arrayNumber + 10, 1);
}
Here the function iota fills the passed range in the array with sequentially increasing values, starting with 1.
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.
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 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.