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.
Related
I have a homework assignment where we're supposed to create a list of integers, and allow the user to INSERT an integer at a given position in the list. The list should essentially move all integers over one position in the array, then insert the integer that the user input at the index they chose.
So let's say I have an array of {1, 2, 3, 4, 5} and I want to put 9 in index 1, the array should then be {1, 9, 2, 3, 4, 5}.
I thought I figured out the solution with this function:
void *INSERT(int count, int userNum, int index, int array[]){ //Accepts count of array, users number, users index, and array
int tempIndex = index;
index--;
for(int counter = 0; counter < count; counter++)
{
array[tempIndex] = array[tempIndex-1];
tempIndex++;
}
array[index] = userNum;
}
Here is what I have in the main function:
int index = 0; //Hold users index selection
int userNum = 0; //Hold users number
int n = 10;
int a[n] = {1, 2, 3, 4, 5};
int *ptr = a;
cout << "Enter a number to insert: ";
cin >> userNum;
cout << "Enter an index: ";
cin >> index;
INSERT(n, userNum, index, ptr);//call insert function (Accepts count of array, users number, users index, and array)
int listNum = 1;
for(int i = 0; i < n; i++) {
cout << listNum << ". " << a[i] << "\n";
listNum++;
}
However, this is the output after printing the array:
1. 1
2. 9
3. 2
4. 2
5. 2
6. 2
7. 2
8. 2
9. 2
10. 2
I'm not sure where I'm going wrong here that could be causing this output. If I remove the -1 from the INSERT functions for loop like this(commented it out to make it more clear on what's being changed):
void *INSERT(int c, int n, int i, int a[]){ //Accepts count of array, users number, users index, and array
int x = i;
i--;
for(int r = 0; r < c; r++)
{
a[x] = a[x/*-1*/];
x++;
}
a[i] = n;
}
I get the following output with the above code, which is what I'd expect but not what I need. I can post the entire code if needed as well, but I think this explains where the problem is. Thanks in advance for the help
1. 1
2. 9
3. 3
4. 4
5. 5
6. 0
7. 0
8. 0
9. 0
10. 0
Based on your code, just change your insert function to this -
Here we first shift the values to next index in the array and then perform insertion of respective element
void *INSERT(int c, int n, int i, int a[]){ //Accepts count of array, users number, users index, and array
for(int r = c-1; r >= i; r--)
{
a[r+1] = a[r];
}
a[i] = n;
}
This answer may be somewhat controversial because instead of directly solving your assignment for you I'm just telling you how to debug it so you can solve it yourself.
So fixed your code for you:
//Accepts count of array, users number, users index, and array
void *INSERT(
int array_size,
int number_to_insert,
int insert_at,
int numbers[]){
int moving_index = insert_at;
insert_at--; // Why are you doing this?
for(int r = 0; r < array_size; r++)
{
// moving_index was initialized as insert_at
// What happens when insert_at is 0?
// What happens when moving_index >= array_size?
// Who knows...
numbers[moving_index] = numbers[moving_index-1];
// You're incrementing moving_index.
moving_index++;
// What would numbers[moving_index-1] be now?
}
numbers[insert_at] = number_to_insert;
}
Once you answer my questions, I'm sure you'll be able to figure it out.
I want from the program to add 3 to elements which are greater than 3 and print them. It takes so much time that I couldn't see the result. Also, when I change n to 8 in loops directly, it gives a result; however, it's not related with what I want. How can I correct this code and improve that?
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 3, 0, 5, -10};
int b[8];
int n= sizeof(a);
for( int i=1; i<=n; i++) {
if (a[i]>3) {
b[i] = a[i] + 3;
}
else {
b[i]= a[i];
}
}
for (int i = 1; i <= n; i++)
cout << b[i];
return 0;
}
The sizeof() function (int n = sizeof(a)) gives 32 because array 'a' contains 8 elements & each element is of 'int' type whose size is 4 byte in memory thats why it returns 32 in 'n' variable.so you must divide the value of 'n' with the size of integer.
Secondly the index of array starts with the zero '0' to one less than the length of array not with the 1 to length of array .
Try the below code ! I am also attach the output of the code .
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int a[8] = { -5, 7, 1, 0, 3, 0, 5, -10 };
int b[8];
int n = sizeof(a)/sizeof(int);
for (int i = 0; i < n; i++) {
if (a[i]>3) {
b[i] = a[i] + 3;
}
else {
b[i] = a[i];
}
}
for (int i = 0; i < n; i++)
cout << b[i]<<endl;
return 0;
}
The statement in your program int n=size(a) returns the total bytes occupied in memory for a. i.e int occupies 4 bytes and a is an array contains 8 elements so 8X4 = 32 .but while accessing the array elements using loop you are specifying i<=n meains i<=32 but there is only 8 elements but you are trying to access 32 elements which indicates that you are trying to access the elements more than 8.
exeutes the following code
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 3, 0, 5, -10};
int b[8];
int n=sizeof(a);
cout<<"\n Value of n is : "<<n;
return 0;
}
Output
Value of n is : 32
if you specify the exact number of array size your program will work properly.
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 6, 0, 8, -10};
int b[8];
for( int i=1; i<8; i++)
{
if (a[i]>3)
{
b[i] = a[i] + 3;
}
else
{
b[i]= a[i];
}
}
cout<<"\n Values in a array";
cout<<"\n -----------------\n";
for (int i = 1; i <8; i++)
cout << "\t"<<a[i];
cout<<"\n Values in b array";
cout<<"\n -----------------\n";
for (int i = 1; i <8; i++)
cout << "\t"<<b[i];
return 0;
}
OUTPUT
Values in a array
-----------------
7 1 0 6 0 8 -10
Values in b array
---------------
10 1 0 9 0 11 -10
I hope that you understand the concept.Thank you
Your int n = sizeof(a); doesn't works as you intend.
I think you want to get the size of array (i.e. 8).
But you gets the size in bytes of elements (e.g. 32, integer size or could be different depending of your system's architecture).
Change to int n = 8, will solve your problem.
Also note that for( int i=1; i<=n; i++) will get an "out of array" element.
Sizeof function gives the value of the total bits of memory the variable occupy
Here in array it stores 8 integer value that has 2bit size for each thus it returns 32
So I am trying to solve this question:
Data is fed in the following input format. The first line contains two space-separated integers denoting the number of variable-length arrays, n, and the number of queries, q. Each line of the subsequent lines contains a space-separated sequence in the format
k Ai[0] Ai[1] … Ai[k-1]
where k is the length of the array, Ai, and is followed by the k elements of Ai. Each of the subsequent lines contains two space-separated integers describing the respective values of array number (ranging from 0 to n-1) and index in that particular array (ranging from 0 to ki) for a query. i.e, Given the following input:
3 3
3 1 2 3
5 4 5 6 7 8
4 9 10 11 12
0 1
1 3
2 0
This output is expected
2
7
9
I am basically a beginner in C++. This is the code I have tried but I feel the address at which each subsequent array is stored is giving me some problems
int main(){
int n, q;
scanf("%d %d", &n, &q);
printf("n,q = %d, %d\n", n, q);
int* row[n];
for (int i = 0; i < n; i++){
int k;
scanf("%d", &k);
printf("k = %d\n", k);
int col[k];
row[i] = col;
for (int j = 0; j < k; j++){
int elem;
scanf("%d", &elem);
printf("i,j,elem = %d, %d, %d\n", i, j, elem);
col[j] = elem;
cout << "address is " << &(col[j]) << "\n";
}
}
for (int query = 1; query <= q; query++){
int i, j;
scanf("%d %d", &i, &j);
int answer;
answer = *(row[i] + j);
printf("row[%d][%d] is %d\n", i, j, answer);
cout << "address is " << &answer << "\n";
}
return 0;
}
And this is the output produced:
n,q = 3, 3
k = 3
i,j,elem = 0, 0, 1
address is 0x7ffe236edb70
i,j,elem = 0, 1, 2
address is 0x7ffe236edb74
i,j,elem = 0, 2, 3
address is 0x7ffe236edb78
k = 5
i,j,elem = 1, 0, 4
address is 0x7ffe236edb60
i,j,elem = 1, 1, 5
address is 0x7ffe236edb64
i,j,elem = 1, 2, 6
address is 0x7ffe236edb68
i,j,elem = 1, 3, 7
address is 0x7ffe236edb6c
i,j,elem = 1, 4, 8
address is 0x7ffe236edb70
k = 4
i,j,elem = 2, 0, 9
address is 0x7ffe236edb60
i,j,elem = 2, 1, 10
address is 0x7ffe236edb64
i,j,elem = 2, 2, 11
address is 0x7ffe236edb68
i,j,elem = 2, 3, 12
address is 0x7ffe236edb6c
row[0][1] is 32766
address is 0x7ffe236edbcc
row[1][3] is 32766
address is 0x7ffe236edbcc
row[2][0] is 3
address is 0x7ffe236edbcc
Basically, I find that the array addresses are overlapping. Also, The answer computation by dereferencing is resulting in unexpected outputs. Any explanation to the mistakes made here would be appreciated.
Here is a major problem:
for (int i = 0; i < n; i++){
...
int col[k];
row[i] = col;
...
}
The variable col has its scope only inside the loop. Once the loop iterates the variable cease to exist. Storing a pointer to it will lead to undefined behavior when you try to dereference the pointer.
The simple solution is probably to dynamically allocate memory for col using malloc.
Missed that the question was tagged C++, and confused because the source doesn't actually use any C++-specific code. This kind of makes it worse since variable-length arrays are not part of C++. Some compilers have it as an extension, but you should not use it when programming in C++.
Instead you should be using std::vector and then you can easily solve your problem without your own dynamic allocation. Then you can make row a vector of vectors of int and col a vector of int, and then the assignment will work fine (if row have been set to the correct size of course).
An easy way to use C++ without getting too many memory management bugs is to use standard library types. Leave the bare metal stuff to the poor C guys who do not have that ;)
So instead of meddling with new[] and delete[], use types like std::vector<> instead.
The "modern C++" version below uses iostream for no good reason. Old stdio.h is sometimes the preferred choice and so is sometimes iostream. And sometimes it is just a matter of style and taste.
#include <vector>
#include <iostream>
#include <fstream>
typedef struct Q
{
int iArray;
int iIndex;
} Q_t;
typedef std::vector<std::vector<int> > Data_t;
typedef std::vector<Q_t> Query_t;
bool Load(Data_t& data, Query_t &queries, std::istream& is)
{
size_t ndata = 0;
size_t nqueries = 0;
is >> ndata;
is >> nqueries;
data.resize(ndata);
queries.resize(nqueries);
for (size_t d = 0; d < ndata; d++)
{
size_t l = 0;
is >> l;
data[d].resize(l);
for (size_t i = 0; i < l; i++)
{
is >> data[d][i];
}
}
for (size_t q = 0; q < nqueries; q++)
{
is >> queries[q].iArray;
is >> queries[q].iIndex;
}
return true;
}
int main(int argc, const char * argv[])
{
std::ifstream input("E:\\temp\\input.txt");
Data_t data;
Query_t queries;
if (Load(data, queries, input))
{
for (auto &q : queries)
{
std::cout << data[q.iArray][q.iIndex] << std::endl;
}
}
return 0;
}
The mistake is, you have used 'col' array which loses its scope after completion of for loop. The way you can fix this is by either using dynamic memory allocation or by declaring it outside the for loop
Hope the below code will help you get an idea :)
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, q;
cin >> n;
cin >> q;
int* row[n];
int* col;
for(int i=0; i<n; i++)
{
int k;
cin >> k;
col = new int[k];
row[i] = col;
for(int j=0; j<k; j++)
{
cin >> col[j];
}
}
for(int query=0; query<q; query++)
{
int i,j;
cin >> i;
cin >> j;
cout << row[i][j] << endl;
}
delete[] col;
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.
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.