Shift Array Elements Left in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Shift Array Elements Left in C: Program to Rotate Array Left

📑 On this page:
  • Introduction
  • C Program to Shift Array Left
  • Sample Output
  • Program Explanation
  • Algorithm
  • Rotate Array by K Positions
  • Practice Exercise
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • How to shift array elements to the left
  • How to rotate an array by one position
  • How to rotate an array by K positions
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to shift array elements to the left.

Shifting or rotating array elements is a common operation in programming. It is used in many real-world applications, such as:

  • Rotating data in a circular buffer
  • Implementing queues and deques
  • Shifting elements in a sliding window
  • Data encryption and decryption algorithms

💡 Key Point: Left shift means moving elements to the left. The first element moves to the end of the array. For example, [10, 20, 30, 40] becomes [20, 30, 40, 10] after one left shift.

C Program to Shift Array Elements Left by One Position

#include <stdio.h>

int main() {
    int n, i;
    int first_element;
    
    // Ask user for number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Declare array
    int arr[n];
    
    // Read elements into the array
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Store the first element
    first_element = arr[0];
    
    // Shift all elements one position to the left
    for(i = 0; i < n - 1; i++) {
        arr[i] = arr[i + 1];
    }
    
    // Place the first element at the end
    arr[n - 1] = first_element;
    
    // Display the shifted array
    printf("\nArray after left shift: ");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output

Enter the number of elements: 5
Enter 5 elements:
10 20 30 40 50

Array after left shift: 20 30 40 50 10

Another Example:

Enter the number of elements: 4
Enter 4 elements:
5 15 25 35

Array after left shift: 15 25 35 5

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n; — number of elements
    • int i; — loop counter
    • int first_element; — stores the first element before shifting
  3. Get User Input: Reads the array elements from the user.
  4. Store First Element: first_element = arr[0]; saves the first element before it gets overwritten.
  5. Shift Elements Left: The for loop copies each element to the previous position:
    • arr[i] = arr[i + 1]; moves element at position i+1 to position i
    • This runs from i = 0 to i = n-2
  6. Place First Element at End: arr[n - 1] = first_element; puts the saved first element at the last position.
  7. Display Result: Prints the shifted array.
  8. Return: return 0; indicates successful program execution.

📝 Note: This method shifts by one position to the left. To shift by multiple positions, the operation can be repeated or a more efficient method can be used.

Algorithm to Shift Array Left by One Position

Step-by-step algorithm:

  1. Start
  2. Read the array elements
  3. Store the first element in a temporary variable
  4. For i = 0 to n-2:
    • arr[i] = arr[i + 1]
  5. Place the temporary variable at the last position: arr[n-1] = temp
  6. Print the shifted array
  7. End

Visual Example

Shifting [10, 20, 30, 40, 50] left by one position:

Original: [10, 20, 30, 40, 50]

Step 1: Save first element: temp = 10

Step 2: arr[0] = arr[1] → [20, 20, 30, 40, 50]

Step 3: arr[1] = arr[2] → [20, 30, 30, 40, 50]

Step 4: arr[2] = arr[3] → [20, 30, 40, 40, 50]

Step 5: arr[3] = arr[4] → [20, 30, 40, 50, 50]

Step 6: arr[4] = temp → [20, 30, 40, 50, 10]

Result: [20, 30, 40, 50, 10]

Rotate Array Left by K Positions

To shift the array left by K positions, we can either repeat the left shift K times (simpler but less efficient) or use a more efficient method.

Method 1: Repeating Left Shift K Times

#include <stdio.h>

int main() {
    int n, k, i, j, temp;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    printf("Enter the number of positions to shift left: ");
    scanf("%d", &k);
    
    // Handle k > n (use modulo)
    k = k % n;
    
    // Repeat left shift k times
    for(j = 0; j < k; j++) {
        temp = arr[0];
        for(i = 0; i < n - 1; i++) {
            arr[i] = arr[i + 1];
        }
        arr[n - 1] = temp;
    }
    
    printf("\nArray after shifting left by %d position(s): ", k);
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output:

Enter the number of elements: 6
Enter 6 elements:
10 20 30 40 50 60
Enter the number of positions to shift left: 2

Array after shifting left by 2 position(s): 30 40 50 60 10 20

Method 2: Efficient Rotation Using Reversal (O(n) time)

A more efficient method to rotate an array by K positions is to use the reversal algorithm:

  • Reverse the first K elements
  • Reverse the remaining N-K elements
  • Reverse the entire array
#include <stdio.h>

// Function to reverse a portion of the array
void reverseArray(int arr[], int start, int end) {
    while(start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

int main() {
    int n, k, i;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    printf("Enter the number of positions to shift left: ");
    scanf("%d", &k);
    
    // Handle k > n
    k = k % n;
    
    // Rotate left by k using reversal method
    reverseArray(arr, 0, k - 1);      // Reverse first k elements
    reverseArray(arr, k, n - 1);      // Reverse remaining elements
    reverseArray(arr, 0, n - 1);      // Reverse entire array
    
    printf("\nArray after shifting left by %d position(s): ", k);
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output:

Enter the number of elements: 7
Enter 7 elements:
10 20 30 40 50 60 70
Enter the number of positions to shift left: 3

Array after shifting left by 3 position(s): 40 50 60 70 10 20 30

How Reversal Algorithm Works

For rotating left by K positions:

  • Step 1: Reverse first K elements: [30, 20, 10, 40, 50, 60, 70]
  • Step 2: Reverse remaining N-K elements: [30, 20, 10, 70, 60, 50, 40]
  • Step 3: Reverse entire array: [40, 50, 60, 70, 10, 20, 30]
  • Time Complexity: O(n) — much faster than repeating K times

Time and Space Complexity

Method Time Complexity Space Complexity
Single Left Shift O(n) O(1)
Repeat K Times O(n × k) O(1)
Reversal Algorithm O(n) O(1)

💻 Practice Exercise

Challenge 1: Modify the program to shift elements right instead of left.

Challenge 2: Shift the array left by K positions without using extra space (already covered in reversal method).

🔍 Click to Show Solution for Challenge 1
#include <stdio.h>

int main() {
    int n, i;
    int last_element;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Store the last element
    last_element = arr[n - 1];
    
    // Shift all elements one position to the right
    for(i = n - 1; i > 0; i--) {
        arr[i] = arr[i - 1];
    }
    
    // Place the last element at the beginning
    arr[0] = last_element;
    
    printf("\nArray after right shift: ");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

/* Sample Output:
Enter the number of elements: 5
Enter 5 elements:
10 20 30 40 50

Array after right shift: 50 10 20 30 40
*/

Frequently Asked Questions

1. How do you shift elements in an array to the left in C?

Store the first element in a temporary variable, then move each element one position to the left using a loop, and finally place the temporary variable at the end.

2. What is the difference between shift and rotate?

In a shift, the elements that fall off are lost. In a rotate, the elements are wrapped around to the other end. The program above performs a rotation.

3. How do you shift an array left by K positions?

You can repeat the left shift K times, or use the reversal algorithm which is more efficient with O(n) time complexity.

4. What is the time complexity of array rotation?

The reversal algorithm has a time complexity of O(n), where n is the number of elements. The repeated shift method has O(n × k).

5. Can I shift an array without using extra space?

Yes, both the repeated shift method and the reversal algorithm use O(1) extra space (only a few temporary variables).

💡 Tip: The reversal algorithm is the most efficient way to rotate an array by K positions. It's a great technique to remember for coding interviews.

📖 Related Tutorials

  • Union of Two Arrays
  • Reverse an Array in C
  • Check if Two Arrays are Equal
  • More Array Assignments

Previous Topic: -->> Union of Two Arrays   ||   Next topic: -->> Check if Two Arrays are Equal


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.