0
Array operation in C
please I need help with learning array operations in c
1 ответ
+ 5
A few array operations are taught in "Looping over arrays" lesson in the Introduction to C course. Mainly you loop over an array's each elements to perform operations. Let's take this array:
int arr[5] = {1, 2, 3, 4, 5};
Here are some operations:
1. Printing each elements:
for(int i = 0; i < 5; i++) {
printf("%d", i);
}
2. Finding something(3 in this case):
for(int i = 0; i < 5; i++) {
if(arr[i] = 3) {
printf("Found the number at index %d", i);
}
}
4. Summing all elements:
int sum = 0;
for(int i = 0; i < 5; i++) {
sum += arr[i];
}
5. Copying an array:
int arr2[5];
for(int i = 0; i < 5; i++) {
arr2[i] = arr[i];
}
6. Inserting element at a position by shifting elements(we want to add 42 at index 2):
int index = 2; value = 42;
for(int i = 4 i >= 0; i--) {
arr[i + 1] = arr[i];
}
arr[index] = value;
7. Removing an element at an index from an array(index 2, element 3 in this case):
int index = 2;
for(int i = index; i < 4; i++) {
arr[i] = arr[i + 1];
}