給定一個數組arr[m],其中包含m 個整數和n(要添加到數組中的值),並給出r 個查詢,並給出一些開始和結束。對於每個查詢,我們必須在數組中添加從開頭到限制末尾的值 n。
Input: arr[] = {1, 2, 3, 4, 5} query[] = { { 0, 3 }, { 1, 2 } } n = 2 Output: If we run above program then it will generate following output: Query1: { 3, 4, 5, 6, 5 } Query2: { 3, 6, 7, 6, 5 }
這個程式可以透過一個簡單的方法來解決,其中-
START STEP 1 : DECLARE A STRUCT range for start AND end LIMITS STEP 2 : IN FUNCTION add_tomatrix(int arr[], struct range r[], int n, int size, int m) int i, j, k; LOOP FOR i = 0 AND i < m AND i++ LOOP FOR j = r[i].start AND j<= r[i].end AND j++ arr[j] = arr[j] + n END FOR LOOP FOR k = 0 AND k < size AND k++ PRINT arr[k] END FOR END FOR STOP
#include <stdio.h> struct range{ int start, end; //struct to give the range for the array elements }; int add_tomatrix(int arr[], struct range r[], int n, int size, int m){ int i, j, k; for ( i = 0; i < m; i++) //for all the elements in a struct we defined{ for(j = r[i].start; j<= r[i].end; j++) //from where till where we want our results to be updated{ arr[j] += n; //add the value of the particular range } printf("Query %d:", i+1); for ( k = 0; k < size; k++){ printf(" %d",arr[k]); // print the whole array after every query } printf("</p><p>"); } } int main(int argc, char const *argv[]){ int arr[] ={3, 4, 8, 1, 10}; struct range r[] = {{0,2}, {1, 3}, {3, 4}}; int n = 2; int size = sizeof(arr)/sizeof(arr[0]); int m = sizeof(r)/sizeof(r[0]); add_tomatrix(arr, r, n, size, m); return 0; }
如果我們執行上面的程序,那麼它將產生以下輸出-
Query 1: 5 6 10 1 10 Query 2: 5 8 12 3 10 Query 3: 5 8 12 5 12
以上是在C程式中,進行多個陣列範圍增量操作後,列印修改後的陣列的詳細內容。更多資訊請關注PHP中文網其他相關文章!