#include<iostream>
usingnamespace std;
int main()
{
int a,b,i,n,s=0;
cout<<"This program calculates s=(a+b)*i, where i is between 1 and 100, and tells us the value of i."<<endl;
cout<<"Give a and b: ";
cin>>a; //read a
cin>>b; //read b
cout<<"Give n: ";
cin>>n; //read n
for (i=1,100; i<=n; i++)
{
s=s+((a+b)*i);
cout<<"s=(a+b)*i="<<s<<endl;
cout<<"s="<<s<<". For i="<<i<<endl;
}
system("pause");
return 0;
}
this is the program i tryed to create in Dev-C++ 4.9.9.2
can someone plz explain me what is wrong :?
when i try to compile it gives me the next message: "multiple definition of 'main'; first defined here; Id returned 1 exit status; [Build Error] [Project.exe]Error1"
for (i = 1; i <= n; i++) {
s += ((a + b) * i);
std::cout << "s = (a + b) * i = " << s << std::endl;
std::cout << "s = " << s << " for i = " << i << std::endl;
}
If you take the braces out, the equivalent will be
1 2 3 4 5
for (i = 1; i <= n; i++) {
s += ((a + b) * i);
}
std::cout << "s = (a + b) * i = " << s << std::endl;
std::cout << "s = " << s << " for i = " << i << std::endl;
so the program will not give the correct output.
Recommendations:
+ Indent your code. This is very important for showing the flow of the program.
+ Don't use "std::endl" for every std::cout statement (read "endl" and "cout"; the std:: prefix isn't necessary because you have usingnamespace std;). std::cout << std::endl;
is equal to std::cout << "\n" << std::flush;
so you should only put std::endl in the second std::cout statement. To clarify, change
1 2
std::cout << "s = (a + b) * i = " << s << std::endl;
std::cout << "s = " << s << " for i = " << i << std::endl;
to
1 2
std::cout << "s = (a + b) * i = " << s << '\n';
std::cout << "s = " << s << " for i = " << i << std::endl;
it's likely not a big deal in terms of a performance hit, but it's more correct.
+ I mentioned usingnamespace std; earlier. Please don't use it. I will write an article explaining why.
Bottom line is that although usingnamespace std; saves you some typing it also imports the whole C++ std namespace so you run the risk of using a name in your code that is already defined by the C++ standard. This is called namespace collision and it can result in very subtle bugs and unexpected behavior.