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
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 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.
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;
}
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 want to locate a specific item from an array and then shift the array to remove that item. I have a list of integers {1, 2, 3, 4, 5, 6, 7, 8, 9} and want to remove the integer 2.
Currently I am getting an error: storage size of ‘new_ints’ isn’t known on the line:
int new_ints[];
Not sure what this means or how can I fix this?
Here is my code:
int main() {
int tmp = 2;
int valid_ints[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int new_ints[];
new_ints = stripList(tmp, valid_ints);
for (int i = 0; i < sizeof(new_ints); i++)
cout << new_ints[i] << endl;
return 0;
}
int *stripList (int tmp, int valid_ints[]){
for (int i = 0; i < sizeof(valid_ints); i++){
for (int j = tmp; j < sizeof(valid_ints); j++){
valid_ints[j] = valid_ints[j+1];
}
}
return valid_ints;
}
Like what Ben said, it is highly recommended to use an vector if you would like to resize your array to fit in new elements.
http://www.cplusplus.com/reference/vector/vector/vector/
Here's my example: (note alternatively you can use vector::erase to erase undesired elements)
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> valid_ints;
vector<int> new_ints;
int tmp = 2;
//read in elements
for(int i = 1; i <= 9; i++)
{
valid_ints.push_back(i);
}
//valid_ints will hold {1,2,3,4,5,6,7,8,9}
for(int i = 0; i < valid_ints.size(); i++)
{
//We will add an element to new_ints from valid_ints everytime the valid_ints[i] is NOT tmp. (or 2.)
if(valid_ints[i] != tmp)
{
new_ints.push_back(valid_ints[i]);
}
}
//Print out the new ints
for(int i = 0; i < new_ints.size(); i++)
{
cout << new_ints[i] << ' ';
}
return 0;
}
The resulting vector will be filled in this order:
{1}
{1,3} (skip 2!)
{1,3,4}
{1,3,4,5}
so on... until
{1,3,4,5,6,7,8,9}
So, the output would be:
1 3 4 5 6 7 8 9
In c++ size of an array must be known at compile time. Ie int new_ints[] is illegal. You will need to have a defined size ie new_ints[10]. (See here for more details) Or better yet, utilize the fantastic advantages of c++ and use a std::vector.