These solutions use the same array topics listed on the main C arrays tutorial. The examples emphasize correct bounds, initialized variables and reusable loops.
#include <stdio.h>
int main(void) {
int values[5];
for (int i = 0; i < 5; i++) {
printf("Enter value %d: ", i + 1);
if (scanf("%d", &values[i]) != 1) {
return 1;
}
}
return 0;
}
for (size_t i = 0; i < count; i++) {
printf("%d\n", values[i]);
}
for (size_t i = 0; i < count; i++) {
if (values[i] % 2 == 0) {
printf("%d\n", values[i]);
}
}
int sum = 0;
for (size_t i = 0; i < count; i++) {
sum += values[i];
}
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];
}
}
Correction: maximum and minimum checks are independent. Using a broad else for the minimum can assign a value that is not actually the lowest.
for (size_t i = count; i > 0; i--) {
printf("%d\n", values[i - 1]);
}
for (size_t i = 0; i < count; i++) {
for (size_t j = i + 1; j < count; j++) {
if (values[i] == values[j]) {
printf("Duplicate: %d\n", values[i]);
break;
}
}
}
int target = 11;
int frequency = 0;
for (size_t i = 0; i < count; i++) {
if (values[i] == target) {
frequency++;
}
}
int copy[6];
for (size_t i = 0; i < count; i++) {
copy[i] = values[i];
}
#include <stdio.h>
#include <stddef.h>
int main(void) {
int values[] = {0, 14, -11, 15, 11, -20};
size_t count = sizeof values / sizeof values[0];
for (size_t i = 0; i < count; i++) {
for (size_t j = i + 1; j < count; j++) {
if (values[i] < values[j]) {
int temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
for (size_t i = 0; i < count; i++) {
printf("%d ", values[i]);
}
printf("\n");
return 0;
}
For ascending order, change the comparison from values[i] < values[j] to values[i] > values[j].
for (size_t i = 0; i < count; i++) {
int occurrences = 0;
for (size_t j = 0; j < count; j++) {
if (values[i] == values[j]) {
occurrences++;
}
}
if (occurrences == 1) {
printf("%d\n", values[i]);
}
}
← Arrays in C Two-dimensional arrays
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.