Answers for "add numbers c++"

C++
1

c++ sum up numbers

// Method 1: Mathematical -> Sum up numbers from 1 to n 
int sum(int n){
	return (n * (n+1)) / 2;
}

// Method 2: Using a for-loop  -> Sum up numbers from 1 to n 
int sum(int n){
	int tempSum = 0; 
  	for (int i = n; i > 0; i--){
     	tempSum += i;  
    }
  	return tempSum; 
}

// Method 3: Using recursion -> Sum up numbers from 1 to n 
int sum(int n){
	return n > 0 ? n + sum(n-1) : 0; 
}
Posted by: Guest on November-22-2020
1

add two numbers in c++

#include <iostream>
using namespace std;

//function declaration
int addition(int a,int b);

int main()
{
	int a,b;	//to store numbers
	int add;	//to store addition 
	
	//read numbers
	cout<<"Enter first number: ";
	cin>>a;
	cout<<"Enter second number: ";
	cin>>b;
	
	//call function
	add=addition(a,b);
	
	//print addition
	cout<<"Addition is: "<<add<<endl;
	
	return 0;
}

//function definition
int addition(int a,int b)
{
	return (a+b);
}
Posted by: Guest on May-07-2020
0

how to add numbers in for loop c++

#include <iostream>

int main() {
  int n = 0;
  int sum = 0;
  std::cout << "Please enter and integer: ";
  std::cin >> n;

  //this will ensure that the integer is posetive.
  while (n < 0 ) {
    std::cout <<"Please enter positive integer only.n";
    std::cout << "Please enter and integer: ";
    std::cin >> n;
  }

  for (int i = 0; i < n ; i++) {
    std::cout << i << "n";
    sum +=i
  }
  std::cout << "Sum of odd numbers is " << sum <<".n";

}
Posted by: Guest on February-16-2021

Browse Popular Code Answers by Language