luc068.c (1424B)
1 /* Given an array p[5], write a function to shift it circularly left by two positions. Call this function for a 4 x 5 matrix and get its rows left shifted. 2 */ 3 4 /* Let Us C, Chap- 14 (Multidimensional Arrays), Qn No.: C(h) */ 5 6 /* This file is auto-generated by a bot. */ 7 /* This code is not compiled; it is for reference only. */ 8 9 10 #include <stdio.h> 11 #include <stdlib.h> 12 13 void shift_left_two(int *p, int n); 14 void print_row(int *p, int n); 15 16 int main() 17 { 18 int mat[4][5] = { 19 {15, 30, 28, 19, 61}, 20 {1, 2, 3, 4, 5}, 21 {10, 20, 30, 40, 50}, 22 {5, 4, 3, 2, 1} 23 }; 24 int i; 25 26 printf("Original Matrix:\n"); 27 for (i = 0; i < 4; i++) 28 print_row(mat[i], 5); 29 30 // Apply shift to each row 31 for (i = 0; i < 4; i++) 32 { 33 shift_left_two(mat[i], 5); 34 } 35 36 printf("\nMatrix after shifting each row left by 2:\n"); 37 for (i = 0; i < 4; i++) 38 print_row(mat[i], 5); 39 40 return 0; 41 } 42 43 void shift_left_two(int *p, int n) 44 { 45 if (n < 2) return; // Cannot shift if less than 2 elements 46 47 int temp1 = p[0]; 48 int temp2 = p[1]; 49 int i; 50 51 // Shift elements left by 2 52 for (i = 0; i < n - 2; i++) 53 { 54 p[i] = p[i + 2]; 55 } 56 57 // Place the first two elements at the end 58 p[n - 2] = temp1; 59 p[n - 1] = temp2; 60 } 61 62 void print_row(int *p, int n) 63 { 64 int i; 65 for (i = 0; i < n; i++) 66 { 67 printf("%d ", p[i]); 68 } 69 printf("\n"); 70 }