C programming: Delete specific value stored in Array - c

Let us consider an array (say, int a[25];).
Later with the help of some loop I start storing the user input in this array.
At some point of time if user choose to delete the value he just entered from the array.
How can I do that for the user of my program.
I can make that 0, but 0 is also a value he could enter; so I simply want to make it NULL or with some garbage value, as it was when I initialized the array.

You can't delete an element from an array. In C arrays are stored as a contiguous block of memory, so you can't just remove an element. You can use any of the following options:
Use some unused value like -1 to mark the element as deleted.
Use separate array to keep track of deleted elements.
Use linked list to store your elements(Recommend option).

You can't.
If you define
int a[25];
then a consists of 25 int elements. Each element, once you assign a value to it, retains that value until it's reassigned, or until the array ceases to exist. You can't "delete" a value from an array. There is no special NULL value for integers as there is for pointers.
You can pick a special value that denotes an "empty" element (perhaps INT_MIN) -- but then you won't be able to store that value as data. Or you can use another data structure, perhaps an array of bool, to keep track of whether the current value of each element of a is valid or not.

Related

What is the default value of an element of an uninitialized character array?

here's a code I wrote
int main(){
char arr[50][*];
arr[0][0]=1;
if(arr[0][1]){
printf("%d",arr[0][0]);}
If I am putting 1 as *, there is no output.
but anything greater than 1 in the array size would result in 1 output.that means when I am declaring array size the elements are occupied by some value.
now, my actual need is to write a condition if loop (example)
if(arr[0][1]!='null') // or '0',false,undefined, etc
but I am confused what is there in that empty but declared element, because the above is not working.
There is no default value.
For an object defined inside a function without the static keyword, the initial value is garbage.
You can't test an object to determine whether it's been initialized or not. You have to write your code to avoid reading any object's value before it's been set.
doing(while declaring),
char arr[50][2]={0} //or whatever the size of 2nd dimension other than 2
this will replace all elements(100 in this case) with 0.
So, according to my necessity,I can do
if(arr[0][1] != 0)
for checking if that element is undefined by me.
this example works when your input doesn't contain 0, if it does replcae all elements with something else and also the condition too

Number of declared elements in an array c

I have created a static array in c
int array[15];
For example, I "filled in" the first 5 elements of my array.
This means that I still have 10 free elements, right?
What should I do to know that I have already "used" five elements of my array?
How would I know the number of elements that I have used?
What should I do to know that I have already "used" five elements of my array? How would I know the number of elements that I have used?
There are couple of options.
Use a sentinel value that indicates the elements that have been filled up.
Let's say you use 99999 for the sentinel value. If the n-th element of the array has the value 99999, you know that you have filled up n-1 elements.
Use another variable to keep track of that.
size_t numFilledElements = 0;
for ( ... )
{
// Fill up an element
// Increment the counter.
++numFilledElements;
}
My personal preference would be to use the second approach. Then, you won't have to worry about a sentinel value.

How to re-arrange elements of Array after Deleting

Recently I was reading a Programming book and found this question:
I have an array :
array = [2,3,6,7,8,9,33,22];
Now, Suppose I have deleted the element at 4th position i.e. 8 .
Now I have to rearrange the array as:
Newarray = [2,3,6,7,9,33,22];
How Can I do this. And I have to also minimize the complexity.
Edit I have no choice to make another copy of it.I have to only modify it.
You can "remove" a value from an array by simply copy over the element by the next elements, that's easy to do with memmove:
int array[8] = {2,3,6,7,8,9,33,22};
memmove(&array[4], &array[5], sizeof(int) * 3);
The resulting array will be {2,3,6,7,9,33,22,22}.
And from that you can see the big problem with attempting to "remove" an element from a compile-time array: You can't!
You can overwrite the element, but the size of the array is fixed at time of compilation and can't actually be changed at run-time.
One common solution is to keep track of the actual number of valid elements in the array manually, and make sure you update that size as you add or remove elements. Either that or set unused elements to a value that's not going to be used otherwise (for example if your array can only contain positive numbers, then you could set unused elements to -1 and check for that).
If you don't want to use a library function (why not?) then loop and set e.g.
array[4] = array[5];
array[5] = array[6];
and so on.
Do this, just use these two functions and it will work fine
index=4;//You wanted to delete it from the array.
memcpy(newarray,array,sizeof(array));
memmove(&newarray[index], &newarray[index + 1], sizeof(newarray)-1);
now the newarray contains your exact replica without the character that you wished to remove
You can simply displace each element from the delIdx(deletion index) one step forward.
for(int i=delIdx; i<(arr_size-1);i++)
{
arr[i]= arr[i+1];
}
If required you can either set the last element to a non-attainable value or decrease the size of the array.

Prevent array to writing to nonexistent index

I have array of numbers like:
int a[10]={1,1,1,1,1,1,1,1,2,1};
I find position of 2 and then change the value of indexof(2)+4 and -4 to 2 too.
Problem is that indexof(2)+4 does not exist which mean c will overwrite some memory that does not belong to array. How can I stop c to writing into indexes that exceed length of the array?
In C, there is no built-in checking (i.e. that happens without programmer involvement) to ensure array indexing keeps within bounds.
If you want to access (read or write) a[i] then you need to write code check that i is a valid index before doing so, and don't access a[i] if i is invalid. That means ensuring the value is between 0 and n-1, where n is known to be the number of elements in the array.
There are various options to obtain or set the value of n. Each have limits on applicability.
You can use sizeof() operator to get the size of the array. Using it you can check whether the value indexof(2)+4 is greater than the array size before changing the value.

Number sequences length, element first and last indexes in array

Im beginner in programming. My question is how to count number sequences in input array? For example:
input array = [0,0,1,1,1,1,1,1,0,1,0,1,1,1]
output integer = 3 (count one-sequences)
And how to calculate number sequences first and last indexes in input array? For example:
input array = [0,0,1,1,1,1,1,1,0,1,0,1,1,1]
output array = [3-8,10-10,12-14] (one first and last place in a sequence)
I tried to solve this problem in C with arrays. Thank you!
Your task is a good exercise to familiarize you with the 0-based array indexes used in C, iterating arrays, and adjusting the array indexes to 1-based when the output requires.
Taking the first two together, 0-based arrays in C, and iterating over the elements, you must first determine how many elements are in your array. This is something that gives new C programmers trouble. The reason being is for general arrays (as opposed to null-terminated strings), you must either know the number of elements in the array, or determine the number of elements within the scope where the array was declared.
What does that mean? It means, the only time you can use the sizeof operator to determine the size of an array is inside the same scope (i.e. inside the same block of code {...} where the array is declared. If the array is passed to a function, the parameter passing the array is converted (you may see it referred to as decays) to a pointer. When that occurs, the sizeof operator simply returns the size of a pointer (generally 8-bytes on x86_64 and 4-bytes on x86), not the size of the array.
So now you know the first part of your task. (1) declare the array; and (2) save the size of the array to use in iterating over the elements. The first you can do with int array[] = {0,0,1,1,1,1,1,1,0,1,0,1,1,1}; and the second with sizeof array;
Your next job is to iterate over each element in the array and test whether it is '0' or '1' and respond appropriately. To iterate over each element in the array (as opposed to a string), you will typically use a for loop coupled with an index variable ( 'i' below) that will allow you to access each element of the array. You may have something similar to:
size_t i = 0;
...
for (i = 0; i< sizeof array; i++) {
... /* elements accessed as array[i] */
}
(note: you are free to use int as the type for 'i' as well, but for your choice of type, you generally want to ask can 'i' ever be negative here? If not, a choice of a type that handles only positive number will help the compiler warn if you are misusing the variable later in your code)
To build the complete logic you will need to test for all changes from '0' to '1' you may have to use nested if ... else ... statements. (You may have to check if you are dealing with array[0] specifically as part of your test logic) You have 2 tasks here. (1) determine if the last element was '0' and the current element '1', then update your sequence_count++; and (2) test if the current element is '1', then store the adjusted index in a second array and update the count or index for the second array so you can keep track of where to store the next adjusted index value. I will let you work on the test logic and will help if you get stuck.
Finally, you need only print out your final sequence_count and then iterate over your second array (where you stored the adjusted index values for each time array was '1'.
This will get you started. Edit your question and add your current code when you get stuck and people can help further.

Resources