Shahzadi Khan
ID:16262
Topic: Functions
function
DEFINITION:
• A Function is a block of code which only runs when it is
called
• Functions are important for reusing the code.
• You can pass parameters into the functions.
SYNTAX:
• returnType functionName() {
// Function body
}
• returnType functionName(parameterType1 parameterName1,
parameterType2 parameterName2, ...);
• returnType: Specifies the type of value the function will return (e.g., int,
void, float).
• functionName: The name used to call the function.
• parameterType: The data type of the parameter (e.g., int, float, string).
• parameterName: The name of the parameter (used within the function).
EXAMPLE:
void say() {
cout<<“Hello world”<<endl;
}
int main(){
say();
}
EXAMPLE 2:
void say(int num){
cout<<“hello world”<<num<<endl;
}
int main()
say(100);
}
Why we use function
• Code Reusability: Write code once and reuse it multiple times.
• It saves our time and make our execution fast.
• Improved Readability: Functions make the code more
understandable by giving descriptive names to specific tasks.
EXAMPLE:
void addition() {
Int a, b, sum;
cout<<“enter two numbers for addition:”<<endl;
cin>>a>>b;
Sum=a+b;
cout<<“addition:”<<sum<<endl;
}
int main(){
cout<<“first addition:”<<sum<<endl;
addition();
cout<<“second addition:”<<sum<<endl;
addition();
}

Functions in programing how functions work

  • 1.
  • 2.
    function DEFINITION: • A Functionis a block of code which only runs when it is called • Functions are important for reusing the code. • You can pass parameters into the functions.
  • 3.
    SYNTAX: • returnType functionName(){ // Function body } • returnType functionName(parameterType1 parameterName1, parameterType2 parameterName2, ...); • returnType: Specifies the type of value the function will return (e.g., int, void, float). • functionName: The name used to call the function. • parameterType: The data type of the parameter (e.g., int, float, string). • parameterName: The name of the parameter (used within the function).
  • 4.
    EXAMPLE: void say() { cout<<“Helloworld”<<endl; } int main(){ say(); } EXAMPLE 2: void say(int num){ cout<<“hello world”<<num<<endl; } int main() say(100); }
  • 5.
    Why we usefunction • Code Reusability: Write code once and reuse it multiple times. • It saves our time and make our execution fast. • Improved Readability: Functions make the code more understandable by giving descriptive names to specific tasks.
  • 6.
    EXAMPLE: void addition() { Inta, b, sum; cout<<“enter two numbers for addition:”<<endl; cin>>a>>b; Sum=a+b; cout<<“addition:”<<sum<<endl; } int main(){ cout<<“first addition:”<<sum<<endl; addition(); cout<<“second addition:”<<sum<<endl; addition(); }