Print modified array after multiple array range increment operations in C Program.

Given an array arr[m] with m number of integers and n, which is the value to be added in an array and r queries are given with some start and end. For each query we have to add value n from the start till the end of the limit in an array.

Syntax

struct range {
    int start, end;
};
void add_tomatrix(int arr[], struct range r[], int n, int size, int m);

Example Input and Output

Input:
arr[] = {1, 2, 3, 4, 5}
query[] = { { 0, 3 }, { 1, 2 } }
n = 2

Output:
Query1: { 3, 4, 5, 6, 5 }
Query2: { 3, 6, 7, 6, 5 }

Algorithm

This program can be solved by an easy approach in which −

  • We will iterate all the queries take traverse the array starting from the start point in the query and till the ending point stored in the query.
  • Add the value of n and print the array.
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

Example

#include <stdio.h>

struct range {
    int start, end; // struct to give the range for the array elements
};

void 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("<br>");
    }
}

int main() {
    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;
}

Output

Query 1: 5 6 10 1 10
Query 2: 5 8 12 3 10
Query 3: 5 8 12 5 12

How It Works

  • The program defines a struct range to store start and end indices for each query.
  • For each query, it iterates through the specified range and adds the value n to each element.
  • After each query, it prints the modified array to show the cumulative effect.

Conclusion

This approach efficiently handles multiple range increment operations on an array. The time complexity is O(m × k) where m is the number of queries and k is the average range size per query.

Updated on: 2026-03-15T11:55:32+05:30

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements