Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
UNIT – 3
ARRAYS and FUNCTIONS
FUNCTION (Subroutine or Subprogram)
A function is a small program or program segment that carries out a specific, well-defined task.
GENERAL FORM OF A FUNCTION (STRUCTURE OF A FUNCTION)
This refers to the overall format or syntax pattern of how a function looks in C.
Example:
return_type function_name(parameter_list)
{
local declarations;
executable statements;
return value;
}
ELEMENTS OF USER-DEFINED FUNCTIONS
User-defined functions in C consist of the following three essential elements:
1. Function Prototype / Declaration
2. Function Definition
3. Function Call
1. Function Prototype / Declaration
Just like variables must be declared before use, functions must also be declared before they are
called in a program. This declaration is known as the Function Prototype or Function
Declaration.
A function prototype specifies the function name, return type, and parameter list.
It is similar to the function header but ends with a semicolon.
It does not include the function body.
Syntax
return_type function_name(parameter_list);
Components
return_type – The data type of the value returned by the function (int, float, double,
char).
function_name – Any valid identifier used as the name of the function.
parameter_list – Variables inside parentheses, separated by commas.
Example
int add(int a, int b);
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
A function prototype declares the following:
Type of value returned by the function
Function name
Number of parameters
Type of each parameter
2. Function Definition
A function definition is the actual program module written to perform a specific operation.
It consists of two major parts:
Function Header
Function Body
Syntax
return_type function_name(parameter_list)
{
declaration part;
executable part;
return statement;
}
return_type
Specifies the data type of the value the function returns.
If no value is returned, the return type must be void.
By default, if omitted, C assumes the return type as int.
function_name
The name of the function.
Must follow the rules of valid identifiers.
Parameters
Variables declared inside parentheses.
Separated by commas.
Example:
int add(int a, int b);
(return type → int, function name → add, parameters → int a, int b)
Function Body Components
a. Declaration Part
All variables used inside the function must be declared here.
b. Executable Part
Contains instructions that perform the required operation.
c. Return Statement
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
Used to send control back to the calling function, with or without a value.
Syntax Examples
1. Without returning a value:
return;
2. Returning a value:
return value;
Example Function Definition
int add(int a, int b)
{
int sum; // variable declaration
sum = a + b; // executable statement
return sum; // return statement
}
3. Function Call
After defining a function, it must be invoked to perform its task. This process of invoking
a function is called a Function Call.
A function is called by writing its name followed by parentheses, which contain the
required arguments (if any).
The number of arguments in the function call must match the number of parameters
in the function definition.
The order of arguments must also match the order of parameters in the definition.
Example
add(m, n);
UNDERSTANDING THE SCOPE OF FUNCTIONS.
Scope refers to the region of a program where a variable or piece of code is visible and can be
accessed.
Function Scope
* Each function in C is a separate block.
* Code inside one function cannot be accessed directly by another function.
* Functions interact only through function call.
* You cannot use goto to jump into another function.
Local Variables
* Declared inside a function.
* Created when the function begins.
* Destroyed when the function ends.
* Do not retain their value between function calls.
Static Local Variables
• Declared inside a function using the keyword static
• Lifetime: exists for the entire program run
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
• Scope: only inside that function
• Keeps (retains) its value between function calls
• Useful when a function must remember a previous value
Function Parameters
• They also have function scope
• Created when the function is called
• Destroyed when the function finishes
• Available throughout the entire function body
• Parameters act like local variables
File Scope
• All functions in C have file scope
• Meaning: functions are visible throughout the file where they are defined
• A function cannot be defined inside another function
• This is why C is not a fully block-structured language
FUNCTION PARAMETERS
✔The list of variables defined in the function header within the parentheses are called function
parameters.
✔There are 2 types of parameters in C functions:
i. Actual parameters
ii. Formal parameters
i. Actual (Real) Parameters
✔The variables that are used when a function is invoked are called actual parameters.
✔Actual parameters appear in the calling function when a function is invoked.
✔Actual parameters send values or addresses to the formal parameters.
✔Actual parameters may be constants, variables, or expressions.
Example:
res = add(m, n);
Here, m and n are actual parameters.
ii. Formal (Dummy) Parameters
✔The variables defined in the function header or function definition are called formal
parameters.
✔All formal parameter variables must be separately declared and separated by commas.
✔Formal parameters receive values from the actual parameters.
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
✔If formal parameters receive addresses, they must be declared as pointers.
✔Formal parameters should be variables only — expressions and constants are not allowed.
Example: int add(int a, int b);
Here, a and b are formal parameters.
Example Program: C Program to Define Actual and Formal Parameters
#include <stdio.h>
int add(int a, int b) // Formal parameters: a, b
{
int sum;
sum = a + b;
return sum;
}
int main()
{
int m, n, res;
printf("Enter the values for m and n\n");
scanf("%d %d", &m, &n);
res = add(m, n); // Actual parameters: m, n
printf("Sum = %d\n", res);
return 0;
}
CATEGORIES OF FUNCTIONS IN C
Classification of Functions
Based on parameters and return values, functions in C are classified into four types:
a. Functions with no parameters and no return value
b. Functions with no parameters but with return value
c. Functions with parameters and no return value
d. Functions with parameters and with return value
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
[Link] with No Parameters and No Return Value
• No data is sent from main() to the function.
• Function does not send any value back to main().
• Only the function body executes when called.
Example:
#include <stdio.h>
void add()
{
int a = 10, b = 20, sum;
sum = a + b;
printf("Sum = %d", sum);
}
void main()
{
add();
}
[Link] with No Parameters but With Return Value
• No data is passed from main() to the function.
• Function returns one value to main().
• Useful when function calculates something internally and sends result back.
Example:
#include <stdio.h>
int add()
{
int a = 10, b = 20, sum;
sum = a + b;
return sum;
}
void main()
{
int result;
result = add();
printf("Sum = %d", result);
}
c. Functions with Parameters and No Return Value
• Data is passed from main() to the function.
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
• Function does not return any value to main().
• Output is printed inside the function.
Example:
#include <stdio.h>
void add(int m, int n)
{
int sum;
sum = m + n;
printf("Sum = %d", sum);
}
void main()
{
add(10, 20);
}
d. Functions with Parameters and With Return Value
• Data is sent from main() to the function.
• Function returns a value back to main().
• Most commonly used type.
Example:
#include <stdio.h>
int add(int m, int n)
{
int sum;
sum = m + n;
return sum;
}
void main()
{
int result;
result = add(10, 20);
printf("Sum = %d", result);
}
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
ARGUMENT/PARAMETER PASSING METHODS
C uses two main parameter passing methods:
a. Call by Value
b. Call by Address (Call by Reference)
a. Call by Value
• Actual parameter values are copied into formal parameters.
• Changes made inside the function do not affect actual variables.
Example:
#include <stdio.h>
int add(int a, int b)
{
int sum = a + b;
return sum;
}
void main()
{
int m = 10, n = 20, res;
res = add(m, n);
printf("Result = %d", res);
}
b. Call by Address (Call by Reference)
• Addresses of actual variables are passed to the function.
• Formal parameters are pointers.
• Changes inside the function affect the actual variables.
Example (Addition):
#include <stdio.h>
int add(int *a, int *b)
{
int sum = *a + *b;
return sum;
}
void main()
{
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
int m = 10, n = 20, res;
res = add(&m, &n);
printf("Result = %d", res);
}
Example (Swap):
#include <stdio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void main()
{
int m = 10, n = 20;
swap(&m, &n);
printf("m = %d\nn = %d", m, n);
}
USING ARRAYS WITH FUNCTIONS
Arrays can be passed to functions in two ways:
a. Passing individual elements
b. Passing the whole array
a. Passing Individual Elements
• Each element is passed like a normal variable.
Example:
`
#include <stdio.h>
void print_square(int x)
{
printf("%d ", x * x);
}
void main()
{
int n, a[10], i;
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Squares:\n");
for(i = 0; i < n; i++)
print_square(a[i]);
}
b. Passing the Whole Array
Rules:
• Call the function by passing only the array name.
• In the function definition, declare the parameter as an array (size not required).
Example:
```
#include <stdio.h>
void read_array(int a[], int n)
{
int i;
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
}
void main()
{
int n, b[10], i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
read_array(b, n);
printf("The array elements are:\n");
for(i = 0; i < n; i++)
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
printf("%d ", b[i]);
}
ARGC AND ARGV – ARGUMENTS to main()
• Sometimes we need to pass values to a program when we run it.
• These values are called command line arguments.
• They are typed after the program name in the command line.
Example:
cc program_name
Here, program_name is a command line argument.
Two special arguments are used in C to receive command line values:
1. argc
• Stands for argument count.
• It stores the total number of command line arguments.
• Minimum value is 1 (the program name is always counted).
2. argv
• Stands for argument vector.
• It is an array of character pointers.
• Each element of argv stores one command line argument.
• All command line arguments are stored as strings.
Example program using argc and argv:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc != 2) {
printf("You forgot to type your name.\n");
exit(1);
}
printf("Hello %s", argv[1]);
return 0;
}
How to run:
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
If program name is name and user name is Tom
name Tom
Output: Hello Tom
Rules for command line arguments
• Arguments must be separated by spaces or tabs.
Example: run Spot run → three separate strings.
• Commas do not separate arguments.
Example: Herb,Rick,Fred → one single string.
• You can enter arguments containing spaces using quotes.
Example: "run fast now" → one single argument.
THE return STATEMENT
The return statement ends a function and sends a value back to the calling function.
Example:
int add(int x, int y)
{
return x + y;
}
When return x + y; executes, the function stops and returns the sum.
What Does main() return?
The main() function usually returns an integer value to the operating system.
return 0; → Program executed successfully
return 1; → Program terminated with an error
PROGRAMS USING FUNCTIONS:
Program 1: Factorial of a number
#include <stdio.h>
int factorial(int n)
{
int i, fact = 1;
for(i = 1; i <= n; i++)
fact *= i;
return fact;
}
int main()
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
{
int n, result;
printf("Enter a number: ");
scanf("%d", &n);
result = factorial(n); // function call
printf("Factorial = %d", result);
return 0;
}
Program 2: Prime number check
#include <stdio.h>
int isPrime(int n)
{
int i;
if(n <= 1)
return 0;
for(i = 2; i <= n/2; i++) {
if(n % i == 0)
return 0;
}
return 1;
}
int main()
{
int n, result;
printf("Enter a number: ");
scanf("%d", &n);
result = isPrime(n); // function call
if(result)
printf("Prime number");
else
printf("Not a prime number");
return 0;
}
Program 3: Sum of N elements
#include <stdio.h>
int findSum(int a[], int n)
{
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
int i, sum = 0;
for(i = 0; i < n; i++)
sum += a[i];
return sum;
}
int main() {
int n, i, result;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
result = findSum(a, n); // function call
printf("Sum = %d", result);
return 0;
}
Program 4: Simple calculator
#include <stdio.h>
float calc(float a, float b, char op)
{
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': if(b != 0) return a / b;
else return 0;
default: return 0;
}
}
int main()
{
float a, b, result;
char op;
printf("Enter operator (+ - * /): ");
scanf(" %c", &op);
printf("Enter two numbers: ");
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
scanf("%f %f", &a, &b);
result = calc(a, b, op); // function call
printf("Result = %.2f", result);
return 0;
}
Program 5: Linear search
#include <stdio.h>
int linearSearch(int a[], int n, int key)
{
int i;
for(i = 0; i < n; i++)
{
if(a[i] == key)
return i;
}
return -1;
}
int main()
{
int n, i, key, position;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter search key: ");
scanf("%d", &key);
position = linearSearch(a, n, key); // function call
if(position == -1)
printf("Element not found");
else
printf("Element found at position %d", position + 1);
return 0;
}
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
Program 6: Binary search
#include <stdio.h>
int binarySearch(int a[], int n, int key)
{
int low = 0, high = n - 1, mid;
while(low <= high) {
mid = (low + high) / 2;
if(a[mid] == key)
return mid;
else if(a[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main()
{
int n, i, key, position;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[n];
printf("Enter %d sorted elements:\n", n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter search key: ");
scanf("%d", &key);
position = binarySearch(a, n, key); // function call
if(position == -1)
printf("Element not found");
else
printf("Element found at position %d", position + 1);
return 0;
}
Program 7: Bubble sort
#include <stdio.h>
void bubbleSort(int a[], int n)
Course Titile: Programming In C Course Code: P22PSC1055
Pavan Krishna K – Assistant Professor
{
int i, j, temp;
for(i = 0; i < n - 1; i++) {
for(j = 0; j < n - i - 1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
int main()
{
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
bubbleSort(a, n);
printf("Sorted elements:\n");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}