0% found this document useful (0 votes)
9 views10 pages

Functions

The document provides comprehensive notes on functions in C++, explaining their structure, types, and components. It covers built-in and user-defined functions, function prototypes, definitions, calls, and various parameter passing methods. Additionally, it discusses function overloading, inline functions, and includes a complete example program demonstrating these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

Functions

The document provides comprehensive notes on functions in C++, explaining their structure, types, and components. It covers built-in and user-defined functions, function prototypes, definitions, calls, and various parameter passing methods. Additionally, it discusses function overloading, inline functions, and includes a complete example program demonstrating these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

HSSC-II Computer Science - Functions Chapter Notes

Student: Huzaifa
Status: ✅ MASTERED

What are Functions?


Functions are like recipes in a cookbook:

Name (like "Make Biryani")

Ingredients needed (parameters/arguments)


Instructions (the code inside)

What you get at the end (return value)

Types of Functions

1. Library/Built-in Functions
Functions that C++ already provides:

cout , cin , getch() , clrscr() , strlen()

Ready to use, no need to write them

2. User-defined Functions
Functions YOU create for specific problems

Write once, use multiple times

Solve specific tasks

Function Components (The Big Three)

1. Function Prototype (Declaration)

cpp

void sayHello(); // Just the signature

2. Function Definition
cpp

void sayHello() // Function header


{
cout << "Hello Pakistan!"; // Function body
}

3. Function Call

cpp

sayHello(); // Actually using the function

Function Signature (Function's "ID Card")


Contains 3 parts:

1. Function Name: sayHello

2. Return Type: void , int , float

3. Arguments/Parameters: (int a, int b)

Examples:

cpp

void sayHello() // Name: sayHello, Return: void, Args: none


int addNumbers(int a, int b) // Name: addNumbers, Return: int, Args: two ints
float calculateArea(float l, float w) // Name: calculateArea, Return: float, Args: two floats

Function Structure

Function Header
The first line containing the signature:

cpp

int addNumbers(int a, int b) // This entire line is the header

Function Body
Everything inside the curly braces:
cpp

{
int sum = a + b; // Body content
return sum; // Body content
}

Return Statement
Analogy: Like handing something back to the person who asked for it

void vs int difference:


void: "I do something but don't give anything back" (like telling a joke)

int: "I do something AND give you a number back" (like asking for calculation)

cpp

// INT function - returns a value


int addTwoNumbers(int x, int y)
{
int sum = x + y;
return sum; // Hands back the result
}

// VOID function - does work but returns nothing


void displayMessage()
{
cout << "Hello World!";
// No return statement needed
}

Scope of Functions
Local Functions: Only available in current program file

Global Functions: Available across multiple programs (like built-in functions)

Parameters

Formal Parameters
Placeholder names in function definition:
cpp

void addNumbers(int a, int b) // 'a' and 'b' are FORMAL parameters

Actual Parameters
Real values passed when calling function:

cpp

addNumbers(5, 10); // '5' and '10' are ACTUAL parameters

Parameter Passing Methods

1. Pass by Value
Analogy: Giving someone a photocopy - original stays unchanged

cpp

void changeNumber(int x)
{
x = 100; // Changes the COPY only
}

int num = 5;
changeNumber(num); // num is still 5

2. Pass by Reference
Analogy: Giving someone the actual original - changes affect original

cpp

void changeNumber(int &x) // Notice the & symbol!


{
x = 100; // Changes the ORIGINAL
}

int num = 5;
changeNumber(num); // num is now 100

Key Difference:

Pass by Value: Temporary change (like working with a copy)


Pass by Reference: Permanent change (working with original)
Scope of Variables

Local Variables
Analogy: Room-specific items (like toothbrush in bathroom)

Created inside a function


Only work inside that function

"Die" when function ends

Global Variables
Analogy: House-wide items (like WiFi password)

Created outside all functions

Work everywhere in the program

Stay alive throughout program execution

Static Variables
Analogy: Items in your room that never get thrown away

cpp

void countVisits()
{
static int visitCount = 0; // Remembers value between calls
visitCount++; // Keeps incrementing: 1, 2, 3, 4...
}

Default Arguments
Analogy: Backup plans for function parameters (like ordering food with default drink)

cpp

void orderFood(char dish[], char drink[] = "Coke", int quantity = 1)


{
cout << "Order: " << quantity << " " << dish << " with " << drink;
}

// Can be called as:


orderFood("Biryani"); // Uses defaults: 1 Biryani with Coke
orderFood("Karahi", "Pepsi"); // Uses default quantity: 1 Karahi with Pepsi
orderFood("Pizza", "Sprite", 3); // No defaults: 3 Pizza with Sprite
Rules:

Default arguments must go at the END

Once you use a default, ALL parameters after it must have defaults

Inline Functions
Analogy: Having a photocopy machine at your desk vs walking to copy room

Regular Function:
Program "jumps" to function, executes, jumps back
Slower but uses less space

Inline Function:

cpp

inline int square(int x)


{
return x * x;
}

Compiler puts function code directly where you call it

Faster execution but uses more space if called frequently

When to Use:

Small, simple functions (1-2 lines)


Functions called very frequently

When speed is critical

Function Overloading
Analogy: Multiple "Ahmed"s doing different jobs - same name, different specialties

cpp

// Same name "calculate" but different parameters


void calculate(int a, int b) // For integers
void calculate(float a, float b) // For floats
void calculate(int a, int b, int c) // For three numbers

How C++ Chooses:


Looks at parameters you pass
Matches them to the right function signature

Advantages:

One logical name for related functions

Cleaner, more readable code


Easy to remember

Key Teaching Analogies That Worked


🎯 Functions = Recipes in cookbook
🏠 Variable scope = Rooms in a house
📄 Pass by value = Working with photocopy
📱 Pass by reference = Using actual phone
🏪 Return = Vending machine giving back result
👥 Function overloading = Multiple people with same name, different jobs

Complete Example Program


cpp
#include <iostream.h>
#include <conio.h>

int globalVar = 100; // Global variable

// Function overloading examples


void display(int x)
{
cout << "Integer: " << x << endl;
}

void display(char str[])


{
cout << "String: " << str << endl;
}

// Pass by reference example


void changeValue(int &x)
{
x = x * 2;
}

// Function with default arguments


void greet(char name[], char msg[] = "Hello")
{
cout << msg << " " << name << "!" << endl;
}

void main()
{
clrscr();

// Function overloading in action


display(42);
display("Pakistan");

// Pass by reference
int num = 5;
changeValue(num);
cout << "Changed value: " << num << endl; // Now 10

// Default arguments
greet("Huzaifa");
greet("Ali", "Salam");
getch();
}

✅ CHAPTER STATUS: FULLY MASTERED


Next Topics: Pointers, Classes & Objects (OOP), File Handling

You might also like