#include <iostream>
usingnamespace std;
int num,i;
void getnumber();
int sum();
int main(){
int m;
m=sum();
cout<<m;
return 0;
}
void getnumber(){
for(i=1;i<=5;i++)
cout<<"enter number: ";
cin>>num;
}
int sum(){
int sumi;
sumi+=i;
return(sumi);
}
Hey there.
Lets start from main.
According to your program, m is a return value of sum [sumi]
What does sum do? Adds i to it. What is i? Nothing, just has a garbage default value in it.
Remember that i is just used to run through the loop. i is not the value of what you entered!
You did not call getnumber() anywhere so it never touches that. :D
In getmain, think of m as a box in memory.
Suppose I enter
1
2
3
4
5
It first takes 1 and puts it into m. Then it removes 1 and puts 2 into the box etc.
I would suggest learning from a good book :)
Here is a way :
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
int main() {
cout << "Enter numbers";
int n,sum = 0;
for(int i = 0; i < 5; i++){
cin >> n;
sum+=n;
}
cout << "Thats " << sum << " when added!";
return 0;
}
thanks
i made array[5] but i'd like to add 2 or 3 numbers when i call sum
i wont insert 5 numbers to add,maybe id like to insert 4 numbers
thanks again
staticconstint MAXNUM = 5;
int num[MAXNUM];
void getnumber()
{ if (counter >= MAXNUM)
{ cout << "Array is full" << endl;
return;
}
cout<<"enter number: ";
cin>>num[counter];
counter++;
}
Note that I've made MAXNUM a constant. By using MAXNUM, instead of the hard coded value 5, if you ever want to change the size of the array, all you have to do is change that one line.