w3resource

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


40. New Array from First and Last Elements

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

For more Practice: Solve these Related Problems:

  • Write a C program to create an array from the first two and last two elements of a given array.
  • Write a C program to swap the first and last elements of an array and then output the modified array.
  • Write a C program to extract the first element and the element before last from an array.
  • Write a C program to construct a new array containing only the extreme elements (first, last, and middle) of the original array.


Go to:


Previous: Extract Middle Elements from Two Arrays.
NEXT : Array of Two: Check for 15 or 20.

C Programming Code Editor:



What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.