Size of an array vs actual number of elements present - arrays

So im learning C and i've been working with arrays.One thing that I've learnt is that arrays start with index 0.So i keep thinking...if you want to create an array that holds 10 values..shoudn't you create it as say : int ar[9] , since it starts from 0-9 which is 10 elements? I keep seeing a lot of people initialising an array with 10 elements as such : int ar[10] and then while inserting data using for loops they write: for(int i=0;i<10;i++) which technically means the 11 element(ar[10]) has a garbage value right? or is this done on purpose ?

Related

Only print Filled Values in an Array C/ get number of filled values In array C

So i have an array of structures which is created at a fixed size
struct student studentArray[32]
At some point In my program I have to print the elements of the array, often times before it is full. Now typically If I wanted to the print the elements would do something like this
for(int i=0; i< sizeof(studentArray)/sizeof(studentArray[0]); i++){
printf('structure info here');
}
The problem I'm having is that this would Iterate 32 times, since the array size is 32 which I don't wanna do, I would just wanna iterate based on the number of times I've inserted a element into the array. Right now, I am just manually keeping track of number of elements added to array with an integer but I am wondering if there is just a line of code that could get only the number of elements i've inserted and ignore the empty/garbage values of the array.
There is no special way to tell if a variable is uninitialized. The best way to handle this is what you're currently doing: keeping track of how many elements are active in a separate variable.

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.

C Storing Matrix in Array of Chars and Printing

Hey all I am trying to store a matrix in an array of chars and then print it out.
My code that I have written:
#include<stdio.h>
#include<stdlib.h>
int main() {
int i;
int j;
int row=0;
int col=0;
int temp=0;
char c;
int array[3][2] = {{}};
while((c=getchar()) !=EOF && c!=10){
if((c==getchar()) == '\n'){
array[col++][row];
break;
}
array[col][row++]=c;
}
for(i=0; i<=2; i++){
for(j=0; j<=3; j++){
printf("%c ", array[i][j]);
}
printf("\n");
}
}
Using a text file such as:
1 2 3 4
5 6 7 8
9 1 2 3
I would like to be able to print that back out to the user, however what my code outputs is:
1 2 3 4
3 4 5 6
5 6 7 8
I cannot figure out what is wrong with my code, some how I am off an iteration in one of my loops, or it has something to do with not handling new lines properly. Thanks!
A few problems that I can see are:
As user3386109 mentioned in the comments, your array should be array[3][4] to match the input file.
The line array[col++][row]; does nothing but increment col, and then uselessly indexes the array and throws away the value. You can do the same thing with just col++;. However, you're not even using col at any later point in the code, so really you don't even need that. The break; all by itself does what you need. Which leads me to...
You're not populating the array like you think you are. You're incrementing col and then immediately breaking out of the loop. So how does the entire array ever get populated? Just by pure luck. As it turns out with your array declared as array[3][4], the array access array[0][4] (which isn't even technically supposed to exist) is equivalent to array[1][0]. This is because all multidimensional arrays (in C and just about any other language) are laid out in memory as flat arrays, because memory itself uses linear addressing. In C, this flattening of multidimensional arrays is done in so-called Row-major order, meaning that as you traverse the raw memory from first address to last, the corresponding multidimensional indices (i,j,k,...z, or in your case just i,j) increment in such a way that the last index will change the fastest. So, not only does col never get incremented except for right before you break out of the loop, but row never gets reset to 0, which means you're storing values in array[0][0], array[0][1], ... array[0][11], not array[0][0] .. array[0][3], array[1][0] .. array[1][3], array[2][0] .. array[2][3] as you were expecting. It was just luck that, thanks to row-major ordering, these two sets of indices were actually equivalent (and C doesn't do array bounds checking for you because it assumes you're doing it yourself).
This is just personal preference, but you will usually see arrays referenced as array[row][col], not array[col][row]. But like I said, that's just preference. If it's easier for you to visualize it as [col][row], then by all means do it that way. Just make sure you do it consistently and don't accidentally switch gears midway through your code to doing [row][col].
Your code will break and only print out part of the matrix if you accidentally put a trailing space at the end of one of your rows of numbers, because of the weird way you're checking for the end of input (doing a second getchar after each initial getchar and checking to see if the second character is \n). This method isn't wrong per se, in the sense that it will work, but it's not very robust and relies on your input data being precisely formatted and containing no trailing spaces. Anyone who has ever spent hours trying to figure out why their Makefile didn't work, only to find out that it was because they had leading spaces instead of tabs can attest to the fact that those kinds of errors can be extremely time-consuming and frustrating to track down. Precisely formatted input data is always a good thing, but your code shouldn't break in unexpected an non-obvious ways (such as only printing out half of a matrix) when it doesn't get perfect input. Edit: It only occurred to me later on that you were actually intending to do two mutually exclusive things here: increment col for the next line of input, and break out of the loop after having (presumably) detected the end of input. You need to figure out which thing you're doing here, although thanks to item #3, your code actually (and oddly) works just by taking user3386109's advice and changing array[3][2] to array[3][4].
I can only assume you used <= 2 and <= 3 in your for loops instead of < 3 and < 4, respectively, because you prefer doing it that way. That's fine, but it generally makes for easier-to-read code if your for loop conditions match up with your array dimensions. Just speculating here, but perhaps that's why you had array[3][2] when you really meant array[3][4].

An array of length 4-20?

I'd like for my array to be of a set length using a simple format. Please, let me know how this is done.
What I already have:
arr[100]
Pseudocode: what I would like to have:
arr[4-20] or arr[$min_int THROUGH $max_int]
Additional detail edit: The int should be within the range array = (4, 20). The input may contain leading zeros. I'd like to keep the length of the array restricted (i.e., to 9 or 10 characters).
Arrays simply do not work this way in C. You will need to implement it yourself by only looping through valid indices (and wasting memory in the process) or by using a data structure better suited to the job, like a map (which you will have to find in a library or write yourself as it does not exist in the language).
#define ARRMINIDX 4
#define ARRMAXIDX 20
int arrmem[ARRMAXIDX+1-ARRMINIDX];
#define arr(x) arrmem[ARRMINIDX+(x)]
// process elements of arr
for( i = ARRMINIDX; i <= ARRMAXIDX; i++ )
dosomething(arr(i));
OTOH, this make not be what you want at all, given your comment
I want an array with 0-1 elements: a limited int or limited "numeric
int"--string mimicking an int.
which I can't make heads or tails of in this context. Are you saying that you want a string of 4-20 chars that represents an integer?

Trying to put a unique number code in all of my arrays

Say I have 3 arrays of arrays and when I write in any of them my counter goes up by one every insertion I do.How can I show on screen the data I inserted the same order I inserted them with that unique code it was printed when I was inserting them?
array ar1=new array[3];
array2 ar2=new array2[3];
array3 ar3=new array3[3];
I'm working on C# with 6 files. My main calls methods from the other 3 files. My base abstract class calls a counter (named code) from a constructor, which is being inserted on every array.My main is without Heredity, but calls the variables from the 3 files that are connected with heredity to the abstract base class.
This is my main and how I fill my first array.Same with different variables on the other two arrays.
i ++;
ar1[i] = new array();
{
Console.WriteLine("Inserting on first array");
Console.WriteLine("\n\nCode :{0}",code);
ar1[i].Inserting_data(); // this is the method where I fill my arrays
}
And this is how I try to call my previous insertions using a method again.
for (int x = 0; x <= i; x++)
{
Console.WriteLine("code :{0}",code); //trying to print the unique code but it prints total.
ar1[x].Print_data(); //the method for printing my insertions
}
If I leave the program like this when I insert data(up to 3 on every array) My counter is working fine and when I print them on screen, it prints them on the correct order but in the Console.WriteLine that there should be the unique code I want for every insertion (from 1 to 9 on that example, if I fill them all),my counter shows me the total insertions I have.
If I try rather than printing my counter, printing each variable from the For command,I get numbers from 0 to 2 max since that's what I put on my For. I can't unite my 3 arrays since each of them holds different variables and is on 3 different files.
Hope that helped.
I found the problem at last..
I had to add another variable on the base abstract class.Inside the constructor I had to write that the new variable (say s)was (s=+1+count++) and add it with a property(set,get) on my main.It worked fine.
Thanks for the time it took you to see this topic and ask some questions to help me.

Resources