C Programming: Functions and Arrays
C Programming: Functions and Arrays
• A function is a set of statements enclosed within curly brackets ({}) that take
inputs, do the computation, and provide the resultant output.
• It means that instead of writing the same code again and again for different
arguments.
Introduction to Functions
• you can simply enclose the code and make it a function and then call it
multiple times by merely passing the various arguments.
• For example, printf() is a function; used to display output/print text to the screen:
#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
Output:
Hello World!
main() is a function, which is used to execute code
Function Definition
• Function definition consists of a function header that identifies the function.
• followed by the body of the function containing the executable code for that function
When a function defined.
•function_name: This is the function’s name that helps the compiler identify it whenever
we call it.
•arg1, arg2, ...argn: It is the argument or parameter list that contains all the parameters to
be passed into the function. A function may or may not require parameters. Hence, the
parameter list is optional.
•Body: The function’s body contains all the statements to be processed and executed
whenever the function is called.
EXAMPLE:1
Explanation:
void greet()
{
printf("Hello, welcome!\n");
}
Explanation:
return 0;
}
Output: Square of 4 is 16
Square of 7 is 49
Function Declaration
• The general format for declaring a function that accepts some arguments and
returns some value as result can be given as:
• Example:-2
int large (int x, int y);
• is a function declaration with function_name “large” with return _type “integer” and has two arguments “x” and
“y” of integer type.
Why and where we need function declaration: (Extra)
• If the function is defined before it is used:
• If you define the function before its usage, there is no need for a function declaration, as the
compiler can directly read the function's definition and understand how to call it.
• For Ex:
• The factorial() function is defined before the main() function.
• The factorial() function is used in main() after it has already been defined.
• No function declaration is needed because the compiler can directly read the function definition
before it is used.
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("Factorial of %d is %lld\n", number, factorial(number)); // Call the factorial function and display the result
return 0;
}
// Function Definition
long long int factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
}
Function Call
Function Call
Return Statement
• It is used at the end of a function to end or terminate it with or without a value.
• It can only be used in function that is declared with a return type such as int, float,
double etc.
• The function declared with void type does not return any value.
• Example 1:
int sum()
{
return variable;
}
Return Statement
Example 2: (No return value)
Void value()
{
printf(“ hello ”);
}
Example 3:
double large(double a, double b) {
if (a > b)
return a;
else return b;
}
Return Statement
Example 4:
/* C program to demonstrate Function with argument and with return value */
#include<stdio.h>
int add(int a, int b);
void main()
{
int a,b,sum;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
sum=add(a,b);
printf("The Sum of two numbers=%d\n",sum);
}
1. Call by value
2. Call by reference
int temp;
Output:
temp = a;
Enter two numbers:
a = b; 5 10
b = temp; Before swapping: x = 5, y = 10
printf("Inside swap function: a = %d, b = %d\n", a, b); Inside swap function: a = 10, b = 5
} After swapping (in main): x = 5, y = 10
int main() {
int x, y;
printf("Enter two numbers:\n");
scanf("%d %d", &x, &y)
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(x, y);
printf("After swapping (in main): x = %d, y = %d\n", x, y);
return 0;
}
Passing parameters to the functions
2. Call by Reference: Here both actual and formal parameters refer to same
memory location. Therefore any changes made to the formal parameters will get
reflected to actual parameters.
a b x y
address location(1024) address location(1025) address location(1024) address location(1025)
• A reference (address) is passed to the function.
• Changes made inside the function affect the original data.
Example:
#include <stdio.h>
Output:
void modifyValue(int *a) {
Before function call: num = 5
*a = *a + 10; // Modify the value at the address Inside function: *a = 15
printf("Inside function: *a = %d\n", *a); After function call: num = 15
}
int main() {
int num = 5;
printf("Before function call: num = %d\n", num);
modifyValue(&num); // Passing address of num
printf("After function call: num = %d\n", num); // Changed
return 0;
}
Passing parameters to the functions
• Example: swapping two numbers using call by reference
#include<stdio.h>
void swap(int *a, int *b);
int main()
{
int a=10, b=20; // a=10 //b=20
printf(“a=%d b=%d",a,b);
swap(&a, &b); //Address passed
printf(“x=%d y=%d",a,b); //After swapping now, a=20, b=10
}
void swap(int *x, int *y) //Actual Arguments will get Altered.
{
int temp;
temp=*x; // x=20
*x=*y; // y=10
*y=temp;
}
VARIABLES SCOPE
• In C, all constants and variables have a defined scope.
• By scope we mean the accessibility and visibility of the variables at different points in
the program.
• A variable or a constant in C has four types of scope: block, function, file and program
scope.
VARIABLES SCOPE
1. BLOCK SCOPE
• A statement block is a group of statements enclosed within an opening and closing curly brackets ({ }). If a variable is
declared within a statement block then, as soon as the control exits that block, the variable will also exist. Such a variable also
known as a local variable and is said to have a block scope.
• A variable declared inside a block (typically enclosed by curly braces {}) has block scope. This means the variable is
accessible only within that block and not outside it.
Example:
#include <stdio.h>
int main() {
int x = 10; // x has block scope in main
if (x == 10) {
int y = 20; // y has block scope inside the 'if' block
printf("y inside block: %d\n", y);
}
// printf("y outside block: %d\n", y); // Error: 'y' is not visible here
printf("x inside main: %d\n", x);
return 0;
}
• Example:
#include <stdio.h>
int main()
{
int i;
int x = 10;
printf("\n The value of x outside the while loop is %d", x);
while (i<3)
{
int x = i;
printf("\n The value of x inside the while loop is %d", x);
i++;
}
return 0;
}
• 2. FUNCTION SCOPE
• Function scope is applicable only with goto label names.
• The programmer can not have the same label name inside a function.
• Using goto statements is not recommended as it is not considered to be a good
programming practice. We will not discuss the goto statement in detail here but we will
take a look at an example code that demonstrates the function scope.
• Example:
int main() {
loop: /* A goto label has function scope */
goto loop; /* the goto statement */
return 0;
}
• In this example, the label Loop is visible from the beginning to the end of the main()
function. Therefore, there should not be more than one label having the same name within
the main() function.
VARIABLES SCOPE
3. PROGRAM SCOPE
• Global variables are those variables that can be accessed from any point in the program.
#include<stdio.h>
int x = 10;
void display();
int main()
{
int x = 2;
printf("\n The value of local variable x is= %d", x);
display();
}
void display()
{
printf("\n The value of global variable x is = %d", x);
}
VARIABLES SCOPE
4. FILE SCOPE
• When a global variable is accessible until the end of the file, the variable is said to have file
scope.
• To allow a variable to have file scope, declare that variable with the static keyword before
• A global static variable can be used any where from the file in which it is declared but it is not
• Such variables are useful when the programmer writes his own header files.
Storage Classes
1. auto (Automatic) Storage Class
•Default Storage Class: If no storage class is specified, the variable is assumed to have auto storage class by defaul
•Scope: Local to the function or block in which it is declared.
•Lifetime: Exists only during the function/block execution.
•Initialization: Initialized by default to garbage values.
•Usage: Primarily used for local variables inside a function.
•Example:
#include <stdio.h>
void myFunction() {
auto int x = 10; // auto is default, so it can be omitted
printf("Inside function: x = %d\n", x); Output:
} Inside function: x = 10
Explanation: The auto storage class is the default for local
int main() { variables. It is not explicitly required to use auto because local
myFunction(); variables are automatically considered as auto. They are created
return 0; when the function is called and destroyed when the function
} exits.
2. register Storage Class
• Scope: Local to the function or block where it is declared.
• Lifetime: Exists only during the function/block execution.
• Purpose: Indicates that the variable should be stored in a CPU register (if possible), providing
faster access compared to memory.
• Example:
#include <stdio.h>
void myFunction() {
register int x = 5; // register suggests storage in CPU register
printf("Inside function: x = %d\n", x);
}
int main() {
Explanation: The register keyword suggests that the
myFunction(); variable x should be stored in a CPU register for faster
return 0; access, although the compiler may choose not to use a
} register depending on available resources.
.
Output:
Inside function: x = 5
[Link] Storage Class
•Scope: If declared inside a function, the variable has local scope but retains its value across function calls. If
declared outside any function, it has file scope, meaning it is only visible within the file it is declared in.
•Lifetime: The variable exists for the lifetime of the program, i.e., it is created when the program starts and destroyed
when the program ends.
•Purpose: Used for retaining values between function calls (for local variables) and limiting visibility of
variables/functions to the current file (for global variables/functions).
•Initialization: Initialized to zero by default if not explicitly initialized.
•Example:
#include <stdio.h>
•Scope: extern variables or functions are visible across multiple files. It allows a
variable or function to be defined in one file but accessed in other files.
•Lifetime: Exists for the lifetime of the program.
•Purpose: Used to declare variables or functions that are defined in another file.
•Initialization: The extern declaration does not allocate memory for the variable but
tells the compiler that the variable is defined elsewhere.
Example :
File 1 (main.c):
#include <stdio.h>
extern int x; // Declare the variable defined in another file
int main() {
printf("Value of x: %d\n", x); // Accessing variable defined externally
return 0;
}
File 2 (data.c):
#include <stdio.h>
int x = 10; // Define the variable
the base case is a specific condition in the function. When it is met, it terminates the recursion. It is used
to make sure that the program will terminate. Otherwise, it goes into an infinite loop.
2. Recursive case: The part of code inside the recursive function executed repeatedly while calling the
recursive function is known as the recursive case.
Recursive Functions
Program to find a factorial of number using recursion.
Recursive Functions
Program to find a factorial of number using recursion.
#include<stdio.h>
int fact(int);
void main( )
{
int n,result;
printf(“Enter a number”);
scanf(“%d”,&n);
result=fact(n);
printf(“Factorial = %d”,result);
}
int fact(int n)
{
if(n==0)
return 1;
else
return (n*fact(n-1));
}
Example: Program to find nCr value using recursion
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
int main() {
int n, r, result;
printf("Enter a value for n and r: ");
scanf("%d %d", &n, &r);
result = nCr(n, r);
printf("nCr Value = %d\n", result);
return 0;
}
Arrays
• Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
• To create an array, define the data type (like int) and specify the name of the array followed by square
brackets [].
#include<stdio.h>
void main()
{
int number1;
int number2;
int number3;
int number4;
int number5;
Arrays
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
printf( "number1: %d \n", number1);
printf( "number2: %d \n", number2);
printf( "number3: %d \n", number3);
printf( "number4: %d \n", number4);
printf( "number5: %d ", number5);
}
Single Dimensional Array :- An Array which has only one subscript is known as Single
• The individual array elements are processed by using a common array name with different
index values that start with Zero and ends with array_size-1
data_type array_name[array_size];
Declaration of Arrays
• data_type: can be int, float or char….
• array_size : an integer constant indicating the maximum number of data elements to be stored.
Array Representation
Declaration of Arrays
a[0] holds the first element in the array
and so on..
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
Explanation:
Input:
•The program first asks the user to input the number of elements (n) in the array.
•Then it takes n integers from the user and stores them in an array called arr.
Finding the Smallest Number:
•The smallest number is initially assumed to be the first element (arr[0]).
•The program then iterates through the rest of the array, comparing each element with the current
smallest number. If a smaller number is found, it updates the smallest variable.
Output:
•The program prints the smallest number after completing the iteration through the array.
Two Dimension arrays
Two Dimension arrays
Two Dimension arrays
Two Dimension arrays
Operation on two-dimension arrays
Operation on two-dimension arrays
Storing values in arrays
Storing values in arrays
•
int main() {
int arr[5]; // Declare an array of size 5
printf("Enter 5 integers:\n");
#include <stdio.h>
int main() {
// 1. Initializing during declaration
int arr1[3] = {5, 10, 15};
• SORTING: It is the process of arranging elements in the list according to their values in
ascending or
descending order. A sorted list is called an ordered list.
• Ex: Bubble Sort, Selection Sort, Insertion Sort, Quick Sort.
• 1. Bubble sort will start by comparing the first element of the array with the second element, if
the first element is greater than the second element,
• it will swap both the elements, and then move on to compare the second and the third element, and
so on.
Operations on arrays
[Link] sort: This is an in-place comparison based algorithm It is comparison based algorithm
• The sorted part at left and unsorted part at right end. Initially sorted part is empty and
• The smallest element is taken from the unsorted array and swapped with the left most
[Link].
[Link] the array elements and the target element to be searched.
[Link] a loop counter i = 0.
[Link] the following steps while i < n (size of the array):
•If arr[i] == target, return the index i (element found).
•Otherwise, increment i by 1.
[Link] the loop completes without finding the target, return "Element not found".
[Link].
(Right R)
(Left L)
Find the middle element:
•Calculate the middle index:
. mid = low + (high - low) / 2
1. In linear search input data need not to be in [Link] binary search input data need to be in sorted
sorted. order.
3. The time complexity of linear search O(n). [Link] time complexity of binary search O(log n).
5. Linear search performs equality comparisons 5. Binary search performs ordering comparisons
1. Traversing an Array:- Traversing means visiting each element of the array for processing.
Algorithm:
Step 1: [INITIALIZATION] SET I = lower_bound
Step 2: Repeat Steps 3 to 4 while I< = upper_bound
Step 3: Apply Process to A[I]
Step 4: SET I=I+1
[END OF Loop]
Step 5: EXIT
Explanation:
•Initialization: Set the loop counter I to the lower bound (starting index).
•Iteration: Continuously process each array element at A[I] while I <= upper_bound (end index),
incrementing I after each step.
•Completion: The loop ends when all elements are processed, and the program exits
• Example:
• #include <stdio.h>
• int main() {
• int arr[] = {10, 20, 30, 40, 50}; Output:
Array elements are:
• int n = sizeof(arr) / sizeof(arr[0]);
10 20 30 40 50