need some help this is my program so far and below is the what it is suppost to do.
thanks for any help!!
Write a program that declares, defines, and calls a non-void function that will compute the sum of the first n positive integers (where n is passed as a parameter). If n is negative, the function should return 0. Your main program should ask the user for the value of n, pass it to the function, and then output the returned result. For instance, if the function were passed a value for n of 5, the returned result should be 15, i.e. 1+2+3+4+5.
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int sum();
int main()
//int _tmain(int argc, _TCHAR* argv[])
{
int n;
int num;
num = 1;
cout << "enter a number";
cin >> n;
for ( num =1; num <= n; num++)
{
cout << num + num;
}
return 0;
}
int sum(int num)
{
return num + num;
}
It's a clue that all operations should be done in the function itself.
So you pass 5 as an argument to your function, and it looks like that 5 is being decremented 1 number at a time. The original number and the result of each decrement is added up. Looks like it stops once that 5 reaches 0, time to, return, I suppose.
#include "stdafx.h"
#include <iostream>
usingnamespace std;
// int sum(); We don't need this
int sum = 0;
int main()
{
int n;
int num; // Don't need this
num = 1; // or this
cout << "enter a number";
cin >> n;
for ( int num =1; num <= n; num++)
{
// add num to sum
}
// output sum
return 0;
}
/*
Don't need this
int sum(int num)
{
return num + num;
}*/
But of course that isn't what your professor has asked.
So declare the non-void function int sum(int n);
Then put your sum-ing loop in there.
Then call it from main cout << "Sum of " << n << " is " << sum(n) << end;
#include <iostream>
usingnamespace std;
int sum(int num);
int main()
//int _tmain(int argc, _TCHAR* argv[])
{
int n;
int num;
int sum;
sum =0;
num = 1;
cout << "enter a number";
cin >> n;
for ( num =1; num <= n; num++)
{
sum+=num;
cout << "Sum is " << sum << endl;
}
return 0;
}
usingnamespace std;
int sum(int,int );
int main()
//int _tmain(int argc, _TCHAR* argv[])
{
int n;
int num;
int sum;
sum =0;
num = 1;
cout << "enter a number";
cin >> n;
for ( num =1; num <= n; num++)
{
sum+=num;
cout << "Sum is " << sum << endl;
}
return 0;
}
int sum(int num, int sum)
{
return sum+=num;
}
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int sum(int num); //function prototype
int main(){
int num;
cout<<"Enter a nonegative number: ";
cin>>num;
cout<<"The sum is: "<<sum(num)<<endl;
return 0; //indicates successful termination
}//end main
int sum(int num){
int result=0;
if(num<0)
return 0;
else{
for(int counter=1;counter<=num;counter++){
result+=counter;
}//end loop for
}//end if...else
return result;
}//end function sum
Juan-Enrique-Hernandez-Perezs-MacBook-Pro:test Enrique$ ./hw_sumToN
Enter a nonegative number: 5
The sum is: 15