C & C++ fundamentals / 11
Initializing arrays and counting values
Initialize an array, read values until a sentinel, and count their final decimal digits.
On this page
Let's continue with arrays, beginning with initial values. The declaration int arr[5] = {0}; initializes every element, from index zero through four, to zero. This avoids reading indeterminate values later.
When an initializer contains fewer values than the array's size, those values are assigned in order and the remaining elements are zero-initialized. With int arr[5] = {1, 2, 3, 4, 5};, each element receives the corresponding value.
Reading input with while
Today's main example combines an initialized array with a while loop:
#include <stdio.h>
int main()
{
int arr[10] = {0};
int i,num;
while(1)
{
scanf("%d", &num);
if(num == 0) break;
arr[num % 10]++;
}
for(int i=0;i<10;i++)
{
if(arr[i]>0)
{
printf("%d : %d\n",i,arr[i]);
}
}
return 0;
}
We create an array of ten counters and initialize them to zero. The while loop repeatedly reads a number. If the input is 0, break ends input collection and the program moves to the output stage.
For each other input, arr[num % 10]++ increments the counter for its last decimal digit. The for loop then prints only the counters greater than zero, using the array access pattern from the previous lesson.
Editorial note: this original example assumes valid nonnegative integer input. Negative values can produce a negative index, and failed input is not handled. Add input validation before adapting it for a real program.
Moved here from Tistory
I migrated this post from my Korean Tistory blog, I am Jason Lee, to this website and translated it into English. My writing and projects now live together in one place.
The original publication date, code examples, and screenshots are preserved. Editorial notes clarify known issues in the original material.
Original post on Tistory English edition · Aug 30, 2026