Number sequences length, element first and last indexes in array - c

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.

Related

How can we iterate through an array of integers when we do not know the size of the array? [duplicate]

This question already has answers here:
How do I determine the size of my array in C?
(24 answers)
Closed 5 years ago.
This is a code from geeksforgeeks counting sort implementation:
The have used the below for loop to iterate through a string -
char arr[] = "geeksforgeeks";
for(i = 0; arr[i]; ++i)
++count[arr[i]];
From google search I could understand that this condition implicitly evaluates to arr[i]!='\0'. Have I understood it correctly ?
If I were to use a similar for loop to iterate through an array of integers, would it evaluate to arr[i]!=0 ?
Or is there any better way to iterate through an array of integers when we do not know its size. I am a beginner and please try to provide suggestions which do not involve advanced data structures in C.
Unless you know for sure that there is some sort of sentinel value at the end of the array, you cannot iterate over an array unless you know its size.
An example of a sentinel value is '\0' in the case of strings.
When you want to work with integer arrays you should keep around both the array and the size. This is why functions that take arrays as input parameters take a pointer and an int:
void example(int* array, int size) { /* ... */ }
Yes, an integer expression that evaluates to zero will be considered false by the for construct and end the loop.
Since strings are terminated by a '\0' character with the value 0, this works to detect the end of the string.
Yes, you can use this to iterate over an array of any integer (or pointer, where NULL is considered false) array, but of course terminating such arrays with zero is less common (since zero is a rather useful integer).
If you can use some other value to mark the end (this is called a "sentinel") you can course use that, rather than the length or zero. There's nothing magical about zero, except that for strings it's the convention and thus well supported.

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.

C programming: Delete specific value stored in Array

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.

changing the index of array

so far, i m working on the array with 0th location but m in need to change it from 0 to 1 such that if earlier it started for 0 to n-1 then now it should start form 1 to n. is there any way out to resolve this problem?
C arrays are zero-based and always will be. I strongly suggest sticking with that convention. If you really need to treat the first element as having index 1 instead of 0, you can wrap accesses to that array in a function that does the translation for you.
Why do you need to do this? What problem are you trying to solve?
Array indexing starts at zero in C; you cannot change that.
If you've specific requirements/design scenarios that makes sense to start indexes at one, declare the array to be of length n + 1, and just don't use the zeroth position.
Subtract 1 from the index every time you access the array to achieve "fake 1-based" indexing.
If you want to change the numbering while the program is running, you're asking for something more than just a regular array. If things only ever shift by one position, then allocate (n+1) slots and use a pointer into the array.
enum { array_size = 1000 };
int padded_array[ array_size + 1 ];
int *shiftable_array = padded_array; /* define pointer */
shiftable_array[3] = 5; /* pointer can be used as array */
some_function( shiftable_array );
/* now we want to renumber so element 1 is the new element 0 */
++ shiftable_array; /* accomplished by altering the pointer */
some_function( shiftable_array ); /* function uses new numbering */
If the shift-by-one operation is repeated indefinitely, you might need to implement a circular buffer.
You can't.
Well in fact you can, but you have to tweak a bit. Define an array, and then use a pointer to before the first element. Then you can use indexes 1 to n from this pointer.
int array[12];
int *array_starts_at_one = &array[-1]; // Don't use index 0 on this one
array_starts_at_one[1] = 1;
array_starts_at_one[12] = 12;
But I would advise against doing this.
Some more arguments why arrays are zero based can be found here. Infact its one of the very important and good features of the C programming language. However you can implement a array and start indexing from 1, but that will really take a lot of effort to keep track off.
Say you declare a integer array
int a[10];
for(i=1;i<10;i++)
a[i]=i*i;
You need to access all arrays with the index 1. Ofcourse you need to declare with the size (REQUIRED_SIZE_NORMALLY+1).
You should also note here that you can still access the a[0] element but you have to ignore it from your head and your code to achieve what you want to.
Another problem would be for the person reading your code. He would go nuts trying to figure out why did the numbering start from 1 and was the 0th index used for some hidden purpose which unfortunately he is unaware of.

Resources