16/02/2019

Sum of n real numbers using array

Sum of n real numbers using array: 

Here we want to sum the numbers using array. you can give many numbers and add them by array. We introducing here the array syntax. For example 1+2+3+2+5. First we will give the code and after that we will explain.
Sum of n real numbers using array

Code:

Sum of n real numbers using array input

#include<stdio.h>
int main()
{
  int i,n;
  float a[30],sum=0;
  printf("How many numbers you want to add:");
  scanf("%d",&n);
  for(i=0;i<n;i++)
  scanf("%f",&a[i]);
  for(i=0;i<n;i++)
  sum=sum+a[i];
  printf("The sum of the given numbers is %.2f",sum);
}

Output:

The output is given below:
Sum of n real numbers using array

Explanation: 

1. We first use <stdio.h> header package.
2. we use two integers variable i and n and two float variable a[30] and sum.
3. we use n for how many numbers users want to do sum and i is for for-loop. we use a[30] array variable to store the given numbers and we use sum variable to sum all the given numbers. Here you can change the array size by replacing the number 30. To know more about use of array variable visit syntax page.
4. We use two for-loop. First is for take all the given value from the users and save it in the array variable a[30]. Second for-loop for doing the sum of all the numbers. To know more about for-loop visit syntax package.
5. After that we print the sum and we use the syntax "%.2f" for showing 2 numbers after point in sum, like 12.35 or 4.20. You can use .3 or .4 as your wish for the changing. If you use .3 then it will like 1.235 or 5.125.


                                           If you have any doubts please comment below.  

No comments:

Post a Comment