C loop-sum input values

Now take a look at other examples of using loops--for loop, while loop, and do while loop to enable a user to input a number of data values and then calculate the total of the data values. We provide three separate C code examples. One C code example is using for loop and the two others are using while loop and do while loop.


Example 1: using for loop

#include <stdio.h>
#include <stdlib.h>

void sumValues(){

  int sum=0,val,n;
  printf("Enter number of data points:");
  scanf("%d",&n);
  int i;
  for(i=0;i<n;i++){
    printf("Values %d:",i);
    scanf("%d",&val);
    sum+=val;
    printf("\n");
}
   printf("Total:%d\n",sum);

}

int main(int argc, char *argv[])
{
  sumValues();
  system("PAUSE");
  return 0;
}

Example 2: using do while

#include <stdio.h>
#include <stdlib.h>

void sumValues(){
  int sum=0,val,n;

  printf("Enter number of data points:");
  scanf("%d",&n);
  int i=0;
  while(i<n){
    printf("Values %d:",i);
    scanf("%d",&val);
    sum+=val;
    i++;
    printf("\n");
}

printf("Total:%d\n",sum);

}

int main(int argc, char *argv[])
{
  sumValues();
  system("PAUSE");
  return 0;
}

Example 3: using do while loop

#include <stdio.h>
#include <stdlib.h>

void sumValues(){
int sum=0,val,n;

printf("Enter number of data points:");
scanf("%d",&n);
int i=0;
do{
printf("Values %d:",i);
scanf("%d",&val);
sum+=val;
i++;
printf("\n");
} while(i<n);

printf("Total:%d\n",sum);

}

int main(int argc, char *argv[])
{
sumValues();
system("PAUSE");
return 0;
}

HTML Comment Box is loading comments...



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.