Finding position of maximum element in C, location instance - c

The maximum elements position in an array 'array[n]' has to be found, hence using the following code
int i, maximum; int location = 1;
//the array value and n value will be scanned in
maximum = array[0];
for( i=0; i<n; i++ ) {
if(array[i] > maximum){
maximum = array[i];
location = i+1;
}
}
return location;
this returns the output for example array below
(int[]) {1, 2, 3}, 3 -> location 3
(int[]) {5, 15, 4, 7}, 4 -> location 2
hence in the case of above array the code works well. when an array contains the two or more instance of the greater number, the code fails.
(int[]) {15, 15, 5, 7}, 4 -> location 1 (checks 1st location and stays)
(int[]) {45, 23, 55, 45}, 4 -> location 2 (checks 1st location and stays)
to solve the maximum instance location problem, how can the next instance location be found?

Firstly, in the examples you have given
(int[]) {1, 2, 3}, 3 -> location 3
(int[]) {5, 15, 4, 7}, 4 -> location 2
3 in the first example is in the same position as 4 in the second example, so they should technically have the same location. I'm not sure which code you've used to determine these locations, but it's inconsistent.
Your third and fourth examples are similarly inconsistent. This inconsistency puts doubt on your requirements, despite the clarity of the rest of the question.
A full minimal testcase is usually required for StackOverflow. The requirements are:
Your code must be minimal. Whatever the problem is, it should be easy for us to spot. As a guideline, if your code is greater than 50 lines you should try to trim any unnecessary logic away, filling in the gaps with static values where necessary.
If your problem is an error message, your code must produce the same error message.
If your problem is logical, your code must compile and run, producing the errant behaviour without us having to fill in the blanks or correct any errors, preferably without us even having to enter any input.
Your code doesn't compile, but it's easy enough to wrap it into a function and add a main entry point so it does. It would be best if, in the future, you were to take these steps in producing your minimal testcase.
size_t get_first_maximum_index(int *array, size_t array_size) {
int i, maximum; int location = 1;
//the array value and n value will be scanned in
maximum = array[0];
for( i=0; i<n; i++ ) {
if(array[i] > maximum){
maximum = array[i];
location = i+1;
}
}
return location;
}
I have taken the liberty to add the required interface to your code, but I've left your code unchanged. All you have to do is connect the logic to the interface:
Use array_size instead of n.
return actual array indexes, rather than array indexes + 1.
Suggestion: Use size_t instead of int for array indexes (i and location), since array indexes should never be negative.
Once you've done that, you should be able to use this function to gather the initial maximum index like so: size_t index = get_first_maximum_index(array, array_size);
... as for each instance of the same value, you'll need a different function, which I suggest be named get_next_maximum_index.
size_t get_next_maximum_index(int *array, size_t array_size, int current_maximum) {
/* XXX:
* Find the next value within array that contains current_maximum and return it,
* ... or array_size if none found
*/
}
I feel confident that, providing you were the one who wrote the code you posted in the OP, you should be able to finish that function off yourself. It would follow that an example of finding the first and subsequent indexes for maximum values would look something like this:
#include <stdio.h>
#include "maximum_int_search.h"
int main(void) {
int array[] = { 15, 15, 5, 7 };
size_t array_size = sizeof array / sizeof *array;
size_t index = get_first_maximum_index(array, array_size);
do {
printf("Maximum value at array[%zu]: %d\n", index, array[index]);
index = get_next_maximum_index(array + index + 1, array_size - index - 1);
} while (index != array_size);
}
If you have any problems with these tasks, feel free to ask further questions in the comments.

Related

Cout prints incorrect values of Bidimensional int array, while code appears to be correct

Following code appears to be correct, yet it will print incorrect numbers, which are random each time! I literally copied it from C++ site and cross checked it to confirm the code is correct! And it still doesn't work!
#include <iostream>
int main()
{
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
std::cout << a[3][4];
}
When you initialize arrays in c++, the number passed into each bracket is the size of the array, however this is the upper bound, which is not actually an index, its the limit. if your index starts at 0, and you have 3 items in the arrray, then your last row would be 2. This is why c++ loops over the array are always
for(int i =0; i < array_size; i++)
With an emphisis on < and not <=.
In your code, your indexing an item out of bounds; since a[3][4] is technically the 4th col 5th row.
C++ will let you index out of bounds, and your actually just indexing random values out in memory, which isn't good.
Try printing a[2][3] and that should be what your expecting.

How to insert an element starting the iteration from the beginning of the array in c?

I have seen insertion of element in array starting iteration from the rear end. But i wonder if it is possible to insert from the front
I finally figured out a way, Here goes the code
#include <stdio.h>
int main()
{
int number = 5; //element to be inserted
int array[10] = {1, 2, 3, 4, 6, 7, 8, 9};
int ele, temp;
int pos = 4; // position to insert
printf("Array before insertion:\n");
for (int i = 0; i < 10; i++)
{
printf("%d ", array[i]);
}
puts("");
for (int i = pos; i < 10; i++)
{
if (i == pos) // first element
{
ele = array[i + 1];
array[i + 1] = array[i];
}
else // rest of the elements
{
temp = array[i + 1];
array[i + 1] = ele;
ele = temp;
}
}
array[pos] = number; // element to be inserted
printf("Array after insertion:\n");
for (int i = 0; i < 10; i++)
{
printf("%d ", array[i]);
}
return 0;
}
The output looks like:
Array before insertion:
1 2 3 4 6 7 8 9 0 0
Array after insertion:
1 2 3 4 5 6 7 8 9 0
In C the arrays have a "native" built-in implementation based upon the address (aka pointer) to the first element and a the [] operator for element addressing.
Once an array has been allocated, its actual size is not automatically handled or checked: the code needs to make sure boundaries are not trespassed.
Moreover, in C there is no default (aka empty) value for any variable, there included arrays and array element.
Still, in C there's no such a thing like insertion, appending or removal of an array element. You can simply refer to the n-th (with n starting at 0) array element by using the [] operator.
So, if you have an array, you cannot insert a new item at its n-th position. You can only read or (over)write any of its items.
Any other operation, like inserting or removing, requires ad-hoc code which basically boils down to shifting the arrays elements forward (for making room for insertion) or backward (for removing one).
This is the C-language nature and should not be seen as a limitation: any other language allowing for those array operations must have a lower-level hidden implementation or a non-trivial data structure to implement the arrays.
This means, in C, that while keeping the memory usage to a bare minimum, those array operations require some time-consuming implementation, like the item-shifting one.
You can then trade-off the memory usage against the time usage and get some gains in overall efficiency by using, for example, single- and double-linked lists. You loose some memory for link pointer(s) in favor of faster insertion ad removal operations. This depends mostly upon the implementation goals.
Finally, to get to the original question, an actual answer requires some extra details about the memory vs time trade off that can be done to achieve the goal.
The solution depicted by #Krishna Acharya is a simple shift-based solution with no boundary check. A very simple and somehow naive implementation.
A final note. The 0s shown by Krishna's code at the end of the arrays should be considered merely random values. As I said earlier, there is no default value.
The code should have been instead:
int array[10] = {1, 2, 3, 4, 6, 7, 8, 9, 0, 0};
in order to make sure that any unused value was 0 for the last two array elements.

How to free the final element of a malloc'd array in C?

Say I initialize an array of 5 integer elements like this:
int *Q = malloc(sizeof(int) * 5);
for (int i = 0; i < 5; i++) {
Q[i] = i;
}
The array looks like: {0, 1, 2, 3, 4}.
Now if I shift everything along by 1 position:
Q++;
The array looks like: {1, 2, 3, 4, #}, where # is some garbage value.
Is there a way to free the final element so it's not stored in the array?
I tried this:
free(Q[4]);
But I know this won't work because free() can only operate of the whole chunk of memory allocated for Q.
Is there a better way to shift everything along? The resulting array should look like: {1, 2, 3, 4}.
Would it be a good idea to realloc() Q after every shift?
realloc() can change the size of an allocated chunk of memory, which will do the job for you. Note that this cannot be used to "free" arbitrary elements of an array, but only one(s) on the end.
How good an idea it is to do this depends on a number of factors, none of which you have provided.
When you do Q++ the array has not changed, it still contains the five values 0,1,2,3,4 it is just that Q is pointing to the second element in the array.
If you want to change the size of allocated memory then do as Scott said and realloc the block - but it is a costly way of handling heap memory.
If you just want to keep track of the number of elements in the array let Q remain pointing on the first element and have a size variable indicating how many integers there are.
Alternatively use another data structure to hold your integers e.g. a linked list of integers, then you can add and remove integers easier.
Taliking about last elements of array you can surely use realloc
BTW take note that when you say
The array looks like: {1, 2, 3, 4, #}, where # is some garbage value.
You are wrong and you are invoking undefined behavior as well explained by this SO answer.
So the loop that left shift value have not to do Q[4] = Q[5];
To shift around elements inside an array one can use memmove().
#include <stdio.h>
#include <string.h>
int main(void)
{
int d_init[] = {0, 1, 2, 3, 4};
size_t s = sizeof d_init/sizeof *d_init;
int d[s];
/* Fill d */
memcpy(d, d_init, s * sizeof *d);
for (size_t i = 0; i < s; ++i)
printf("%d ", d[i]);
puts("\n");
/* shift one to the left */
memmove(d, d + 1, (s - 1) * sizeof *d);
for (size_t i = 0; i < s; ++i)
printf("%d ", d[i]);
puts("\n");
/* shift two to the right */
memmove(d + 2, d, (s - 2) * sizeof *d);
for (size_t i = 0; i < s; ++i)
printf("%d ", d[i]);
puts("\n");
}
The snippet above would print:
0 1 2 3 4
1 2 3 4 4
1 2 1 2 3
If you're doing a Q++ you've not shifted the elements of the array, your array is simply pointing to the second element (index 1). Thus, Q[4] is reading something that doesn't belong to the array: C is permissive enough to let you do that (in most cases), but it is a mistake.
To shift elements you should either do
for (int i=0; i<4; i++)
Q[i] = Q[i+1];
or (smarter)
memmove(Q, Q+1, 4*sizeof(int));
but indeed, to have an array of size 4 you'll have to realloc.
BUT if you need to do that, maybe an array is not the data structure you should use: a linked list seems to be a better choice.

Can someone explain how to append an element to an array in C programming?

If I want to append a number to an array initialized to int, how can I do that?
int arr[10] = {0, 5, 3, 64};
arr[] += 5; //Is this it?, it's not working for me...
I want {0,5, 3, 64, 5} in the end.
I'm used to Python, and in Python there is a function called list.append that appends an element to the list automatically for you. Does such function exist in C?
int arr[10] = {0, 5, 3, 64};
arr[4] = 5;
EDIT:
So I was asked to explain what's happening when you do:
int arr[10] = {0, 5, 3, 64};
you create an array with 10 elements and you allocate values for the first 4 elements of the array.
Also keep in mind that arr starts at index arr[0] and ends at index arr[9] - 10 elements
arr[0] has value 0;
arr[1] has value 5;
arr[2] has value 3;
arr[3] has value 64;
after that the array contains garbage values / zeroes because you didn't allocated any other values
But you could still allocate 6 more values so when you do
arr[4] = 5;
you allocate the value 5 to the fifth element of the array.
You could do this until you allocate values for the last index of the arr that is arr[9];
Sorry if my explanation is choppy, but I have never been good at explaining things.
There are only two ways to put a value into an array, and one is just syntactic sugar for the other:
a[i] = v;
*(a+i) = v;
Thus, to put something as the element at index 4, you don't have any choice but arr[4] = 5.
For some people which might still see this question, there is another way on how to append another array element(s) in C. You can refer to this blog which shows a C code on how to append another element in your array.
But you can also use memcpy() function, to append element(s) of another array. You can use memcpy()like this:
#include <stdio.h>
#include <string.h>
int main(void)
{
int first_array[10] = {45, 2, 48, 3, 6};
int scnd_array[] = {8, 14, 69, 23, 5};
int i;
// 5 is the number of the elements which are going to be appended
memcpy(first_array + 5, scnd_array, 5 * sizeof(int));
// loop through and print all the array
for (i = 0; i < 10; i++) {
printf("%d\n", a[i]);
}
}
You can have a counter (freePosition), which will track the next free place in an array of size n.
If you have a code like
int arr[10] = {0, 5, 3, 64}; , and you want to append or add a value to next index, you can simply add it by typing a[5] = 5.
The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8 to index 9, I can do it by the above concept prior to filling up before indices.
But in python by using list.append() you can do it by continued indices.
Short answer is: You don't have any choice other than:
arr[4] = 5;
void Append(int arr[],int n,int ele){
int size = n+1; // increasing the size
int arrnew[size]; // Creating the new array:
for(int i = 0; i<size;i++){
arrnew[i] = arr[i]; // copy the element old array to new array:
}
arrnew[n] = ele; // Appending the element:
}
by above simple method you can append the value

In c: Can I copy a whole portion of an array at once, by refering to the pointer to the location of a slot in the array I want to copy from?

Hope my question is clear and relavent, new to Pointers... - Can I copy a whole portion of an array at once, by refering to the pointer to the location of the first slot in the array I want to begin copying from?
For example -
Given an array : A [ 1,2,3,4,5,7,8,3,2,5,1,0,9]
- I want to copy only the part of the array from the n'th slot on, into the beginning of the array B [0 0 0 ..... ] (B is of the same length of A).
Can I do it at once, using pointers instead of a loop? Something like - switching the pointer to the 1'st slot in B with the pointer to the n'th slot of A, and the n'th slot in B with the last one in A?
Thanks a lot on advance!
That's what memcpy is for.
memcpy(B, A + n, (N - n) * sizeof(A[0]));
where N is the number of elements in A. If A is really an array (not just a pointer to one), then N can be computed as sizeof(A) / sizeof(A[0]), so the call simplifies to
memcpy(B, A + n, sizeof(A) - n * sizeof(A[0]));
memcpy lives in <string.h>; its first argument is the destination of the copy, its second the source.
(I'm sorry, I don't really follow what kind of pointer trick you have in mind, so I can't comment on that.)
I think I understand what you're asking. You can use pointers to set up your second array, but here is the problem with doing it that way:
int [] primary = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int * secondary = primary + 5;
At this point, primary is { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }, and secondary is { 6, 7, 8, 9, 0 }, but the problem is they both point to the same array in memory. So instead of having two independent copies, if you edit any of the elements of 'secondary', they are edited in 'primary' also.
secondary[2] = 10;
for(int i = 0; i < 10; ++i)
cout << primary[i] << ' ';
This portion of code would now yield:
1 2 3 4 5 6 7 10 9 0
The correct way to do it would to either be setting up the new array, and looping through copying over the values, or using memcpy().
Edit:
//Rotate an array such that the index value is moved to the front of the array
null rotateArray( &int original[], int size, int index)
{
int * secondary = new int[size]; //dynamically allocated array
for(int i = 0; i < size; ++i)
{
secondary[i] = original[(i+index)%size];
}
original = secondary; //Move the original array's pointer to the new memory location
}
Some notes:
secondary[i] = original[(i+index)%size];
this is how I rotated the array. Say you had an original array of size 5, and you wanted the fourth element to be the new start (remember, elements are numbered 0-(size-1)):
i = 0;
secondary[0] = original[(0 + 3)%5]// = original[3]
i = 1;
secondary[1] = original[(1 + 3)%5]// = original[4]
i = 2;
secondary[2] = original[(2 + 3)%5]// = original[0]
...
The last part of the code:
original = secondary;
is a little bit questionable, as I don't remember whether or not c++ will try and clean up the used memory once the function is exited. A safer and 100% sure way to do it would be to loop through and copy the secondary array's elements into the original array:
for(int i = 0; i < size; ++i)
original[i] = secondary[i];

Resources