Reputation: 99
Expectation: I want to count number of element available in an int
type of array where 0
can be an element.
Following program output:
Total Element :6
Expected output:
Total Element :9
The code:
#include <stdio.h>
int main() {
int a[50] = { 1, 2, -3, 0, 0, 6, 7, -8, 0 };
int count = 0;
int i = 0;
for (i = 0; i < 50; i++) {
if (a[i]) {
count++;
}
}
printf("Total Element :%d ", count);
return 0;
}
NB: I want to count the total number of elements in the array. I do not want to count the size of the array.
Upvotes: 3
Views: 524
Reputation: 1988
Use a sentinel value, i.e. choose a magic number (like 0xDEADBEEF).
and change your code like this:
#define SENTINEL 0xDEADBEEF
int main() {
int a[50] = { 1, 2, -3, 0, 0, 6, 7, -8, 0, SENTINEL };
int count = 0;
int i = 0;
for (i = 0; i < 50; i++) {
if (a[i] == SENTINEL)
break;
if (a[i]) {
count++;
}
}
printf("Total Element :%d ", count);
return 0;
}
Hope that helps.
Upvotes: 1
Reputation: 70951
I want to count Total number of element in array
As it stands, you cannot.
In C an array does not know which elements ever had been used or not.
If it is not possible to define a sentinel, a stopper-value, but you know the initialiser you could do the following:
#include <stddef.h> /* for size_t */
#include <stdio.h>
#define ARRAY_INITIALISER {1, 2, -3, 0, 0, 6, 7, -8, 0}
int main()
{
int a[50] = ARRAY_INITIALISER;
size_t count;
{
int tmp[] = ARRAY_INITIALISER;
count = sizeof tmp / sizeof *tmp;
}
printf("Total number of elements 'used': %zu\n", count);
return 0;
}
Upvotes: 4
Reputation: 29126
If you want to have a fixed buffer of 50 elements, but the "active" array can have any length and you have no valid sentinel element (such as the null character in strings, or may eb a NULL
pointer or 0 or −1 or INT_MIN
in integer arrays), you must keep track of the active length count
from the start:
int a[50] = {1, 2, -3, 0, 0, 6, 7, -8, 0};
int count = 9;
If you want to build the array dynamically, start with an ampty array and a zero count, then "push" the elements to the array:
int a[50];
int count = 0;
a[count++] = 1;
a[count++] = 2;
a[count++] = -3;
a[count++] = 0;
Take care not to overflow the underlying fixed-size array.
Upvotes: 1