Write C program to left rotate an array



techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
#define size 5 // defining Size of the array

void printArray(int arr[]);
void rotateByOne(int arr[]);


int main()
{
    int i, num;
    int arr[size];

    printf("Enter 5 elements array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    printf("Enter number of times to left rotate: ");
    scanf("%d", &num);

    // Actual rotation
    num = num % size;

    // Printing array before rotation
    printf("Array before rotationn");
    printArray(arr);

    // Rotating array n times
    for(i=1; i<=num; i++)
    {
        rotateByOne(arr);
    }

    // Printing array after rotation
    printf("\n\nArray after rotation\n");
    printArray(arr);

    return 0;
}

void rotateByOne(int arr[])
{
    int i, first;

    // Storing first element of array
    first = arr[0];

    for(i=0; i<size-1; i++)
    {
        // Moving each array element to its left
        arr[i] = arr[i + 1];
    }

    // Copying the first element of array to last
    arr[size-1] = first;
}


//Printing the given array

void printArray(int arr[])
{
    int i;

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

Result

C language

     





Related Topics




Popular Posts