An array stores a fixed number of values of the same type in contiguous memory. Array indexing starts at 0, so an array of five elements uses indexes 0 through 4.
int numbers[5];
int values[] = {9, 8, 7, 6, 5};
int scores[5] = {19, 34, 21, 55, 41};
float percentages[4] = {12.4f, 13.2f, 15.6f, 8.3f};
#include <stdio.h>
#include <stddef.h>
int main(void) {
int values[] = {9, 8, 7, 6, 5};
size_t count = sizeof values / sizeof values[0];
for (size_t i = 0; i < count; i++) {
printf("Index %zu = %d\n", i, values[i]);
}
return 0;
}
A C string is a character array terminated by the null character '\0'.
char name[] = "plus2net";
size_t i = 0;
while (name[i] != '\0') {
printf("%c ", name[i]);
i++;
}
Output
p l u s 2 n e t
After the full program above, only the changed input logic is shown here.
int numbers[5];
for (size_t i = 0; i < 5; i++) {
printf("Enter number %zu: ", i + 1);
if (scanf("%d", &numbers[i]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
int target = 21;
int found = 0;
for (size_t i = 0; i < count; i++) {
if (values[i] == target) {
printf("Found at index %zu\n", i);
found = 1;
break;
}
}
if (!found) {
printf("Value not found.\n");
}
#include <stdio.h>
#include <stddef.h>
int main(void) {
float values[] = {3.0f, 6.0f, 2.0f, 8.0f, 10.0f};
size_t count = sizeof values / sizeof values[0];
float sum = 0.0f;
for (size_t i = 0; i < count; i++) {
sum += values[i];
}
printf("Sum = %.2f\n", sum);
printf("Average = %.2f\n", sum / (float)count);
return 0;
}
#include <stdio.h>
#include <stddef.h>
int main(void) {
int values[] = {12, 14, 11, 15, 11, 10};
size_t count = sizeof values / sizeof values[0];
int highest = values[0];
int lowest = values[0];
for (size_t i = 1; i < count; i++) {
if (values[i] > highest) {
highest = values[i];
}
if (values[i] < lowest) {
lowest = values[i];
}
}
printf("Highest = %d\n", highest);
printf("Lowest = %d\n", lowest);
return 0;
}
Array practice solutions → Two-dimensional arrays
#include <stdio.h>
int main(void) {
float percentages[] = {12.4f, 13.2f, 15.6f, 8.3f};
size_t count = sizeof percentages / sizeof percentages[0];
for (size_t i = 0; i < count; i++) {
printf("Index %zu = %.1f\n", i, percentages[i]);
}
return 0;
}
#include <stdio.h>
int main(void) {
char name[] = {'p','l','u','s','2','n','e','t','\\0'};
size_t i = 0;
while (name[i] != '\\0') {
printf("%c ", name[i]);
i++;
}
putchar('\\n');
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.