Practical-16
Write a program to accept 10 numbers and display its sum using pointer.
Introduction
In this program, we will learn to accept 10 numbers and display its sum using pointer.
Algorithm
- Start
- Declare an array of 10 integers.
- Declare a pointer variable.
- Initialize the pointer variable.
- Accept 10 numbers as input.
- Use a cycle to add the elements to the variable sum.
- Display the sum.
- End
Code
Practical-16.c
//Include the function stdio.h that allows us to use the Input/Output functions
#include<stdio.h>
//Define a macro to set the size
#define SIZE 10
int main ()
{
//Declare and define the variables
int numbers[SIZE];
int *numptr;
int sum = 0;
int i;
//We use a cycle to accept 10 numbers as input
for(i=0;i<SIZE;i++)
{
printf("Enter your number: ");
scanf("%d",&numbers[i]);
}
//We set the *numptr of the array numbers
numptr = numbers;
//We use a cycle that adds the elements to the variable sum
for (i=0;i<SIZE;i++)
{
sum += *numptr;
numptr++;
}
//Display the sum
printf("The sum is: %d",sum);
//End of program
}
Output
Enter your number: 1
Enter your number: 2
Enter your number: 3
Enter your number: 4
Enter your number: 5
Enter your number: 6
Enter your number: 7
Enter your number: 8
Enter your number: 9
Enter your number: 10
The sum is: 55
Explanation
The program starts by declaring an array of 10 integers, a pointer variable, a variable sum and a variable i. Then, we initialize the pointer variable and use a cycle to accept 10 numbers as input. We set the *numptr of the array numbers and use a cycle that adds the elements to the variable sum. Finally, we display the sum.