Sum of Elements in an Array using For Loop in C Programming


This program is a simple C program that accepts a number as the limit of an array and then prompts the user to input values for that array. It then prints out the values of the array, followed by the total of all the values in the array.

It first declares variables i, j, n, and an array a[10] of integers. Then it prompts the user to enter the limit of the array using the scanf function. Next, it prompts the user to enter values for the array using a for loop and the scanf function.

Then, it uses another for loop to print out the values of the array, one at a time, along with their index. Then it iterates over the array, adding each element to the variable 'j' which is initially set to 0. Finally, it prints the total of all the values in the array, which is stored in the variable 'j'. It uses for loop and scanf function to take the input from the user and printf function to display the output on the console.

Source Code

#include<stdio.h>
int main()
{
  int i,j=0,n,a[10];
  printf("\nEnter the Limit:");
  scanf("%d",&n);
  printf("\nEnter the values:");
  for(i=0;i<n;i++)
  {
    scanf("%d",&a[i]);
  }
  printf("\nGiven values are:");
  for(i=0;i<n;i++)
  {
    printf("\na[%d]=%d",i,a[i]);
  }
  for(i=0;i<n;i++)
  {
    j=j+a[i];
  }
  printf("\nTotal value is:%d",j);
  return 0;
}



To download raw file Click Here

Output

Enter the Limit:5
Enter the values:1
2
3
4
5
Given values are:
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
Total values is:15

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C