So im trying to add the previous number to the next one like 1+2+3+4+5...+n,
when i put int a = 0; in the For loop it doesnt add it just displays like if i write 15 down there it just says
1
2
3
4
5...
if i put int a = 0; out of for it works fine, can someone help me understand this in and out thing?
#include <iostream>
usingnamespace std;
int main()
{
cout <<"Enter a number > " << flush;
int b;
cin >> b;
int a = 0;
for (int i = 0 ; i<b ;i = i+1 ){
a=a+i;
cout << a << endl;
}
return 0;
}
Defining "a" inside the for loop means that each iteration through the for loop will set "a" to zero before you use it.
Defining "a" outside the for loop means that you only define "a" once. Then when you change "a" inside the for loop it will always have a new value each iteration of the loop.
Hope that helps,
Andy
P.S. most generally the third part of the for loop i written i++. What you have will work, but i++ is the shorter more common version.
#include <iostream>
// This version will show you the value of "a".
int main()
{
//mstd::SetScreen();
std::cout << "Enter a number > " << std::flush;
int b;
std::cin >> b;
int a = 0;
for (int i = 1; i <= b; i = i + 1) // <--- Set i to start at 1. Changed the middle part to <= so i would catch the last number.
{
a += i; // <--- Shorter version. Works the same.
std::cout << a << std::endl;
}
// Used to keep the console window open.
std::cin.get(); // <--- Gets the \n left over from the first cin.
std::cin.get();
return 0;
}
//// This version will show you what is being added together to get your answer.
//int main()
//{
// std::cout << "Enter a number > " << std::flush;
// int b;
// std::cin >> b;
// int a = 0;
//
// std::cout << "The result of adding ";
//
// for (int i = 1; i <= b; i = i + 1)
// {
// a += i;
//
// std::cout << i;
// ((i == b) ? std::cout << "" : std::cout << " + ");
// }
// std::cout << " is " << a << std::endl;
//
// Used to keep the console window open.
std::cin.get(); // <--- Gets the \n left over from the first cin.
std::cin.get();// return 0;
//}
See what you think. Let me know if you have any questions.