C Exercise Example 68

100 Classic C Examples

Title:There are n integers. Move each of the preceding numbers backward by m positions, and the last m numbers become the first m numbers.

Program analysis:An auxiliary array can be used to store the elements that need to be moved, and then the elements are moved to the correct positions as required.

Example 1

#include <stdio.h>
// Use the shiftArray function to move the array elements.
void shiftArray(int arr[], int n, int m) {
    int temp[m];

    // Save the last m numbers to a temporary array.
    for (int i = n - m, j = 0; i < n; i++, j++) {
        temp[j] = arr[i];
    }

    // Move the first n-m numbers backward by m positions.
    for (int i = n - m - 1; i >= 0; i--) {
        arr[i + m] = arr[i];
    }

    // Put the numbers in the temporary array at the front.
    for (int i = 0; i < m; i++) {
        arr[i] = temp[i];
    }
}
// In the main function, get the array input by the user and the position to move, call the s hiftArray function, and finally output the moved array.

int main() {
    int n, m;

    printf("Please enter the number of integers n:");
    scanf("%d", &n);

    printf("Please enter the number of positions m to move backward:");
    scanf("%d", &m);

    int arr[n];

    printf("Please enter %d integers:", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    shiftArray(arr, n, m);

    printf("Array after moving:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

Example 2

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> #include <stdlib.h> int main() { int arr[20]; int i,n,offset; // Input array size and array contents printf("Total numbers?\n"); scanf("%d",&n); printf("Input %d numbers.\n",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); // Input the shift offset printf("Set your offset.\n"); scanf("%d",&offset); printf("Offset is %d.\n",offset); // Print the array before rotation print_arr(arr,n); // Rotate the array and print move(arr,n,offset); print_arr(arr,n); } // Print array void print_arr(int array[],int n) { int i; for(i=0;i<n;++i) printf("%4d",array[i]); printf("\n"); } // Rotate the array void move(int array[],int n,int offset) { int *p,*arr_end; arr_end=array+n; // The next position after the last element of the array int last; // Rotate until the offset is 0 while(offset) { last=*(arr_end-1); for(p=arr_end-1;p!=array;--p) // Rotate right by one *p=*(p-1); *array=last; --offset; } }

100 Classic C Examples

other extensions