C Program to Increment every Element of the Array by one & Print Incremented Array

«
»

This program increments every element of the array by one & print incremented array.

Problem Description

This is a C program which increments every element of the array by one & print array. We need to add 1 to all the elements of the given array.

Problem Solution

1. Create an array of some size and define its elements.
2. Create a function in which the array created will be passed as parameter.
3. Inside this function, using for loop, access each element of the array, add 1 to the element and store this new value in the same place.
4. Print the array.

advertisement
Program/Source Code

Here is source code of the C Program to increments every element of the array by one & print array. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1.  
  2.     /*
  3.      * C Program to Increment every Element of the Array by one & Print Incremented Array
  4.      */
  5.  
  6.     #include <stdio.h>
  7.     void incrementArray(int[]);
  8.     void main()
  9.     {
  10.  
  11.         int i;
  12.         int array[4] = {10, 20, 30, 40};
  13.         incrementArray(array);
  14.         for (i = 0; i < 4; i++)
  15.            printf("%d\t", array[i]);   // Prints 2, 3, 4, 5
  16.  
  17.     }
  18.  
  19.     void incrementArray(int arr[])
  20.     {
  21.  
  22.         int i;
  23.         for (i = 0; i < 4; i++)
  24.             arr[i]++;     // this alters values in array in main()
  25.  
  26.     }
Program Explanation

1. Declare an array of some fixed size(i.e 4) and define all its element at the time of declaration.
2. Create a function an pass this array to this function as a parameter.
3. Inside this for loop, run a for loop from 0 to size-1, accessing each element of the array, add 1 to it and store the result in the same array index.
4. Print the array.

advertisement
Runtime Test Cases
11    21    31   41

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.

advertisement

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn