0% found this document useful (0 votes)
7 views3 pages

Rotate Array in C Programming

The document contains a C program that rotates an array of integers by a specified number of positions. It includes functions to reverse portions of the array and to handle input and output in a specific format. The program reads an array from standard input, processes the rotation, and prints the result in the same array format.

Uploaded by

Ariharan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

Rotate Array in C Programming

The document contains a C program that rotates an array of integers by a specified number of positions. It includes functions to reverse portions of the array and to handle input and output in a specific format. The program reads an array from standard input, processes the rotation, and prints the result in the same array format.

Uploaded by

Ariharan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <stdio.

h>

#include <stdlib.h>

#include <string.h>

// Reverse helper

void reverse(int* nums, int start, int end) {

while (start < end) {

int temp = nums[start];

nums[start] = nums[end];

nums[end] = temp;

start++;

end--;

// Rotate function

void rotate(int* nums, int n, int k) {

k = k % n;

reverse(nums, 0, n - 1);

reverse(nums, 0, k - 1);

reverse(nums, k, n - 1);

int main() {

char *s = NULL;

size_t bufsize = 0;

// Read array string like [1,2,3,4,5,6,7]

getline(&s, &bufsize, stdin);

// Remove brackets
int len = strlen(s);

if (s[0] == '[') {

memmove(s, s + 1, len - 2); // shift left, remove '['

s[len - 2] = '\0'; // remove ']'

// Split by commas

int capacity = 1000;

int *nums = (int*)malloc(capacity * sizeof(int));

int count = 0;

char* token = strtok(s, ",");

while (token != NULL) {

if (count >= capacity) {

capacity *= 2;

nums = (int*)realloc(nums, capacity * sizeof(int));

nums[count++] = atoi(token);

token = strtok(NULL, ",");

int k;

scanf("%d", &k);

// Rotate

rotate(nums, count, k);

// Print result in same format

printf("[");

for (int i = 0; i < count; i++) {

printf("%d", nums[i]);
if (i < count - 1) printf(",");

printf("]\n");

free(nums);

free(s);

return 0;

You might also like