C Input and Output Array Elements

Input and Output Array Elements in C

In C, you can input and output array elements using various methods. Here are a few common approaches:

  1. Using a for loop: You can use a for loop to iterate over the array elements and perform input or output operations on each element. Here's an example of how you can input elements into an array using a for loop:
#include <stdio.h>

int main() {
    int arr[5];

    printf("Enter 5 numbers:\n");

    for (int i = 0; i < 5; i++) {
        scanf("%d", &arr[i]);
    }

    printf("You entered: ");

    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

In this example, the user is prompted to enter 5 numbers, which are then stored in the arr array. The entered numbers are then printed using another for loop.

  1. Using a while loop: You can also use a while loop to input or output array elements. Here's an example of how you can output elements from an array using a while loop:
#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int i = 0;

    printf("Array elements: ");

    while (i < 5) {
        printf("%d ", arr[i]);
        i++;
    }

    return 0;
}

In this example, the elements of the arr array are printed using a while loop. The loop continues until the value of i reaches 5.

  1. Using pointers: Another approach is to use pointers to access and modify array elements. Here's an example of how you can input elements into an array using pointers:
#include <stdio.h>

int main() {
    int arr[5];
    int *ptr = arr;

    printf("Enter 5 numbers:\n");

    for (int i = 0; i < 5; i++) {
        scanf("%d", ptr);
        ptr++;
    }

    printf("You entered: ");
    ptr = arr;

    for (int i = 0; i < 5; i++) {
        printf("%d ", *ptr);
        ptr++;
    }

    return 0;
}

In this example, a pointer ptr is initialized to point to the first element of the arr array. The user is prompted to enter 5 numbers, which are stored in the array using the pointer. The entered numbers are then printed using the pointer.

These are just a few examples of how you can input and output array elements in C. There are other methods and variations depending on your specific requirements and programming style.

[[SOURCE 1]]