﻿ C++ tutorial-loops: sum input values

C++ tutorial-loops: sum input values

Loops-sum input values

Let see other C++ code examples of using loops--for loop, while loop, and do while loop to enable a user to input a number of data points and then calculate the total of the data values. We provide three separate C++ code examples to solve the same problem. One C++ code example is using for loop and the two others are using while loop and do while loop.

Example 1: C++ code using for loop to sum input values

#include <cstdlib>
#include <iostream>
#include <conio.h>

using namespace std;

void sumValues(){
int sum=0,val,n,i;
cout<<"Enter number of data points:";
cin>>n;
for(i=0;i<n;i++){
cout<<"Values "<<i<<":";
cin>>val;
sum+=val;
cout<<"\n";
}

cout<<"Total:"<<sum;
}

//Start main
int main(){

sumValues();
getch();
return 0;

}

//End main

Example 2: C++ code using while loop to sum input values

#include <cstdlib>
#include <iostream>
#include <conio.h>

using namespace std;

void sumValues(){
int sum=0,val,n,i=0;
cout<<"Enter number of data points:";
cin>>n;
while(i<n){
cout<<"Values "<<i<<":";
cin>>val;
sum+=val;
i+=1;
cout<<"\n";
}

cout<<"Total:"<<sum;
}

//Start main
int main(){
sumValues();
getch();
return 0;

}

//End main

Example 3: C++ code using do while loop to sum input values

#include <cstdlib>
#include <iostream>
#include <conio.h>

using namespace std;

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

cout<<"Enter number of data points:";
cin>>n;
do{
cout<<"Values "<<i<<":";
cin>>val;
sum+=val;
i+=1;
cout<<"\n";
}while(i<n);

cout<<"Total:"<<sum;
}

//Start main
int main(){

sumValues();
getch();
return 0;

}

//End main