0000 The sum of the elements of a Array is calculated using a pointer | MyCareerwise

FOR FREE YEAR SOLVED

The sum of the elements of a Array is calculated using a pointer

Back to Programming

Description

The elements of the array are taken as input. The sum of the elements is calculated using a pointer. A pointer should be the same data type as the data type of the array. The pointer points to the first element of the array at the beginning and then traverse the whole array and calculate the sum.

Algorithm

INPUT: Array elements
OUTPUT: the sum of the elements
PROCESS:
Step 1: [taking the input]
	Read n [number of elements]
	For i=0 to n-1 repeat
		Read a[i]
	[end of ‘for’ loop]
Step 2: [calculating the sum of the array]
	Declare p as a pointer
	Set p<-a [the base address of the array]
	Set s<-0
	For i=0 to n-1 repeat
		Set s<-s+*p
		Set p<-p+1
	[End of ‘for’ loop]
Step 3: Stop.

Code

Complexity:

The time complexity to take the number of elements is O(n) and the time complexity to calculate the sum of the array is also O(n).  

Therefore, the time complexity of this program is O(n).