// this is with functions
#include <iostream>
usingnamespace std;
int add(int a,int b){
int f;
f = a + b;
return f;
}
int main(){
int g, h, j, i;
cout<<"enter first number: ";
cin>>g;
cout<<"enter second number:";
cin>>h;
j = add(g,h);
cout<<"sum is:"<<j;
cout<<"\n\n enter another number:";
cin>>g;
cout<<"enter seond number please:";
cin>>h;
i = add(g,h);
cout<<" sum is"<<i<<j;
}
now without funcitons
1 2 3 4
j = g+h;
i =g+h;
and why do we even have this
1 2
int f;
f = a + b;
we are not using f anywhere, or is it possible if we could do cout<<"answer is:"<<f;
The code you provided is just an example of a function, it is not actually useful in real code.
Functions are useful for writing complex code only once and then calling the function multiple times in other places. Then if a change is required, you only have to change the code in one place instead of many.
#include <iostream>
#include <cctype>
#include <algorithm>
//Moderate function. Gets called 6 times. more than 20 lines of economy
//Lateg got bug fixed. I am glad that I did not had to change it 6 times
//transforms string to ordered set of characters for easy compare
std::string normalize(std::string s)
{
s.erase(std::remove_if(s.begin(), s.end(), [](char c)
{ return !isalpha(c);}),
s.end());
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
std::sort(s.begin(), s.end());
return s;
}
//Sensible name
bool are_anagrams(const std::string& lhs, const std::string& rhs)
{
return normalize(lhs) == normalize(rhs);
}
int main()
{
std::cout.setf(std::ios::boolalpha);
//Easy to read and understand code intent
std::cout << are_anagrams("Forum", "Mruof") << '\n' <<
are_anagrams("C plus PLUS ++", "LUSpclusP") << '\n' <<
are_anagrams("then", "than") << '\n';
}
That is also a contrived example of something useful. When a function returns something complicated, I often store it in a local variable named result before returning it. This is purely to make debugging easier. By storing it somewhere, I can put a breakpoint at that location and see the value that is going to be returned.
In addition to avoiding duplicate code, functions are helpful when designing and coding a complex program. You can break the problem down into smaller pieces, code each as a function, test the function, and move on to the next piece. In real-world settings, the different pieces might be coded by different people, or even entirely different teams.