w3resource

C Exercises: Create a new array taking the first and last elements of a given array of integers and length one or more

C-programming basic algorithm: Exercise-40 with Solution

Write a C program to create a new array taking the first and last elements of a given array of integers and length one or more.

C Code:

#include <stdio.h>
#include <stdlib.h>

// Function prototype for 'print_array'
void print_array(int parray[], int size);

int main(void){ 
    // Declaration and initialization of variables
    int arr_size;
    int a1[] = {10, 20, 30, 40, 50};

    // Calculating the size of the array
    arr_size = sizeof(a1)/sizeof(a1[0]);

    // Printing elements in the original array
    printf("Elements in original array are: ");  
    print_array(a1, arr_size);

    // Creating a new array with the first and last elements from the original array
    int result[] = { a1[0], a1[arr_size - 1]};

    // Calculating the size of the new array
    arr_size = sizeof(result)/sizeof(result[0]);

    // Printing elements in the new array
    printf("\nElements in new array are: ");  
    print_array(result, arr_size);
}     

// Definition of the 'print_array' function
void print_array(int parray[], int size)
{
    int i;      
    for( i=0; i<size-1; i++)  
    {  
        // Printing each element with a comma and a space
        printf("%d, ", parray[i]);  
    } 
    // Printing the last element without a comma and space
    printf("%d ", parray[i]);  
    // Printing a new line to separate the elements
    printf("\n");   
}

Sample Output:

Elements in original array are: 10, 20, 30, 40, 50 

Elements in new array are: 10, 50

Pictorial Presentation:

C Programming Algorithm: Create a new array taking the first and last elements of a given array of integers and length 1 or more

Flowchart:

C Programming Algorithm Flowchart: Create a new array taking the first and last elements of a given array of integers and length 1 or more

C Programming Code Editor:

Previous: Write a C program to create a new array containing the middle elements from the two given arrays of integers, each length 5.
Next: Write a C program to check if a given array of integers and length 2, contains 15 or 20.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming-exercises/basic-algo/c-programming-basic-algorithm-exercises-40.php