You are on page 1of 34

CO-III

Session 21 Introduction to Functions


Content:
Functions:
A function is a self-contained subprogram that is meant to do some specific, well-defined task.
NOTE: -
• A program consists of one or more functions.
• If a program has only one function, then it must be the main function.

Why Functions?
• Generally, a difficult problem is divided into sub problems and then solved. This divide and
conquer technique is implemented in C through functions. A program can be divided into
functions, each of which performs some specific task. So, the use of C functions modularizes and
divides the work of a program.
• When some specific code is to be used more than once and at different places in the program the use
of functions avoids repetition of that code.
• The program becomes easily understandable, modifiable and easy to deluge and test. It became
simple to write the program and understand what work is done by each part of the program.
• Functions can be stored in a library and reusability can be achieved.
Introduction:
A function is a group of statements that together perform a task. Every C program has at least one
function which is main(), and all the most trivial programs can define additional functions. We can divide up
code into separate functions. Logically each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to
another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.

Definition of Function:
The general form of a function definition in C programming language is as follows:

return_type function_name( parameter list )


{
body of the function
}

A function definition in C programming language consists of a function header and a function body. Here
are all the parts of a function:
• Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
• Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
• Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
• Function Body: The function body contains a collection of statements that define what the function
does.
Example:
Following is the source code for a function called max(). This function takes two parameters num1
and num2 and returns the maximum between the two:
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result =num2;
return result;
}

Declaration of Function
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
A function declaration has the following parts:

return_type function_name( parameter list );


For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so following is also
valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case you should declare the function at the top of the file calling the function.

Function Call:
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its function-ending closing
brace is reached, it returns program control back to the main program.
To call a function you simply need to pass the required parameters along with function name and if
function returns a value then you can store returned value. For example:

#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
void main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
We kept max() function along with main() function and complied the source code. While running final
executable, it would produce following result:
Max value is : 200

Categories of functions:
There are mainly four categories of functions are there they
are:
1)functions without argument and without return type
2)functions with argument and without return type
3)functions without argument and with return type
4)functions with argument and with return type.

1)functions without argument and without return type:


Consider main function –

void main()
{
area();
}
We have just called a function , we can see that there is no variable or anything specified between the pair of
round brackets.

void area(); //prototype


Now in the prototype definition of the function we can see the return value as Void. Void means it does not
return anything to the calling function

1
#include<stdio.h>
void add(); //function prototype
void main()
{
add(); //function call
}

void add() // function definition


{
int a=10,b=20;
printf(“%d”,a+b);
}
2
Functions with argument and without return type
In this category of function
• Function accepts argument but it does not return a value back to the calling Program .
• It is Single ( One-way) Type Communication
• Generally Output is printed in the Called function
• Here area is called function and main is calling function.
Program :
#include<stdio.h>
void add(int, int); //function prototype
void main()
{
int a=10,b=20;
void add(a, b);
}
void add(int x,int y)
{
printf(“%d”,x+y);
}

3
Functions without argument and with return type
In this category of functions, functions can be called without arguments but it returns a value
Program:
#include <stdio.h>
int add();
void main()
{
int c;
c = add();
printf(“%d”,c);
}
int add()
{
int a=10, b=20;
return a+b;
}

4
Functions with argument and with return type
In this example we are going to learn function which can accept an argument and return a value.
Function accepts argument and it return a value back to the calling Program thus it can be termed as Two-
way Communication between calling function and called function.
#include<stdio.h>
int add(int,int);
void main()
{
int a=10,b=20,c;
c=add(a,b);
printf(“%d”,c):
}
int add(int x,int y)
{
return x+y;
}

Practice Programs:
1. What is the output when the flowing program segment is executed?
int a=1,b=2;
int f1(int a,int b);
main()
{
int i=1,c,d;
c=5*(i+1);
d=10*(i-1);
printf(“% d, %d “,f1(a,c),f1(b,d));
}
int f1(int x,int y)
{
return(x*y);
}
2. What will be the output when the flowing program segment is executed?
#include<stdio.h>
int i;
void increment(int i)
{
i++;
}
int main()
{
for(i=0;i<10;increment(i))
{}
printf(“i=%d\t “,i)
}

To find the given numbe is Armstrong number or not using user defined function.
#include<stdio.h>
#include<conio.h>
int armstrong(int);
void main()
{
int temp,n;
clrscr();
printf("\n Enter the number to check for armstron no:");
scanf("%d",&n);
temp = n;
if (temp == armstrong(n))
printf("\n The given number %d is an armstrong number",temp);
else
printf("\n The given number %d is not an armstrong number",temp);
getch();
}
int armstrong(int m)
{
int sum=0,re;
while(m>0)
{
re=m%10;
sum=sum+(re*re*re);
m=m/10;
}
return(sum);
}
To find the maximum of given numbers using parameter passing in functions.
#include<stdio.h>
#include<conio.h>

int maximum(int,int,int);
void main()
{
int max,a,b,c;
clrscr();

printf("\n Enter the numbers a,b,c to find maximum:");


scanf("%d %d %d",&a,&b,&c);
max=maximum(a,b,c);
printf("\n The maximum among the %d,%d,%d is %d",a,b,c,max);
getch();
}

int maximum(int x,int y, int z)


{
if((x>y) && (x>z))
return(x);
else if(y>z)
return(y);
else
return(z);
}
To swap two numbers using pass by value
#include<stdio.h>
#include<conio.h>
void swap_by_value(int,int);
void main()
{
int a,b;
clrscr();

printf("\n Enter the two values a and b");


scanf("%d %d",&a,&b);
printf("\nThe value before swapping of a and b: a=%d,b=%d",a,b);
swap_by_value(a,b);
printf("\nAfter swapping of a and b: a=%d,b=%d using call by value",a,b);
getch();
}

void swap_by_value(int a,int b)


{
int temp;
temp = a;
a=b;
b=temp;
}
To find the square and cube of a number using parameter passing in functions.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int square(int);
int cube(int);
void draw_line();
void main()
{
int n,sq,cu;
clrscr();
printf("\n Enter the number to find square and cube:");
scanf("%d",&n);
draw_line();
printf("\nGiven Number\tSquare\t\t Cube\n");
draw_line();
printf("\n %d\t\t%d\t\t%d\n",n,square(n),cube(n));
draw_line();
getch();
}

void draw_line()
{
int i;
for(i=0;i<45;i++)
printf("-");
}

int square(int n)
{
return(n*n);
}

int cube(int n)
{
return(n*n*n);
}

To find the sum of N natural number using function.


#include<stdio.h>
#include<conio.h>

int sum_of_natural_number(int);

void main()
{
int sum,n;
clrscr();
printf("\n Enter the number n :");
scanf("%d",&n);
sum=sum_of_natural_number(n);
printf("\nThe sum of %d Natural numberis %d",n,sum);
getch();
}

int sum_of_natural_number(int n)
{
int sum=0,i=1;
while(i<=n)
{
sum=sum+i;
i++;
}
return(sum);
}

Session 22 Functions & Pointers


Content:
Function Pointer in C

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple
example that shows declaration and function call using function pointer.
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}

int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;

/* The above line is equivalent of following two


void (*fun_ptr)(int);
fun_ptr = &fun;
*/

// Invoking fun() using fun_ptr


(*fun_ptr)(10);
return 0;
}
Output:
Value of a is 10
Why do we need an extra bracket around function pointers like fun_ptr in above example?
If we remove bracket, then the expression “void (*fun_ptr)(int)” becomes “void *fun_ptr(int)” which is
declaration of a function that returns void pointer. See following post for details.
How to declare a pointer to a function?

int * ptrInteger; /*We have put a * operator between int


and ptrInteger to create a pointer.*/
Here ptrInteger is a pointer to integer. If you understand this, then logically we should not have any
problem in declaring a pointer to a function.So let us first see ..how do we declare a function? For example,
int foo(int);

Here foo is a function that returns int and takes one argument of int type. So as a logical guy will think, by
putting a * operator between int and foo(int) should create a pointer to a function i.e.
int * foo(int);
But in C, operator precedence also plays role here. So, in this case, operator () will take priority over operator *.
And the above declaration will mean – a function foo with one argument of int type and return value of int * i.e.
integer pointer. So, it did something that we didn’t want to do.
So, as a next logical step, we must bind operator * with foo somehow. And for this, we would change the default
precedence of C operators using () operator.

int (*foo)(int);
That’s it. Here * operator is with foo which is a function name. And it did the same that we wanted to do.

Following are some interesting facts about function pointers.

1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the
start of executable code.
2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers.
3) A function’s name can also be used to get functions’ address. For example, in the below program, we have
removed address operator ‘&’ in assignment. We have also changed function call by removing *, the program
still works.

#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}

int main()
{
void (*fun_ptr)(int) = fun; // & removed

fun_ptr(10); // * removed

return 0;
}

Output:

Value of a is 10

4) Like normal pointers, we can have an array of function pointers. Below example in point 5 shows syntax for
array of pointers.
5) Function pointer can be used in place of switch case. For example, in below program, user is asked for a
choice between 0 and 2 to do different tasks.

#include <stdio.h>
void add(int a, int b)
{
printf("Addition is %d\n", a+b);
}
void subtract(int a, int b)
{
printf("Subtraction is %d\n", a-b);
}
void multiply(int a, int b)
{
printf("Multiplication is %d\n", a*b);
}

int main()
{
// fun_ptr_arr is an array of function pointers
void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
unsigned int ch, a = 15, b = 10;

printf("Enter Choice: 0 for add, 1 for subtract and 2 "


"for multiply\n");
scanf("%d", &ch);

if (ch > 2) return 0;

(*fun_ptr_arr[ch])(a, b);

return 0;
}

Enter Choice: 0 for add, 1 for subtract and 2 for multiply


2
Multiplication is 150

6) Like normal data pointers, a function pointer can be passed as an argument and can also be returned from a
function.
For example, consider the following C program where wrapper() receives a void fun() as parameter and calls the
passed function.

// A simple C program to show function pointers as parameter


#include <stdio.h>

// Two simple functions


void fun1() { printf("Fun1\n"); }
void fun2() { printf("Fun2\n"); }

// A function that receives a simple function


// as parameter and calls the function
void wrapper(void (*fun)())
{
fun();
}

int main()
{
wrapper(fun1);
wrapper(fun2);
return 0;
}

This point is very useful in C. In C, we can use function pointers to avoid code redundancy.
Passing Pointer to Function in C Programming

In C programming, we can pass the address of the variable to the formal arguments of a function. This method
of calling a function by passing pointer arguments is known as call by reference. Any change in the value of
formal parameters inside function will effect the value of actual argument. To pass a pointer to a function, we
have to declare the function argument of pointer type.
C program to show how to pass pointer to a function

#include<stdio.h>
#include<conio.h>
void getDoubleValue(int *F)
{
*F = *F + 2;
printf("F(Formal Parameter) = %d\n", *F);
}

int main(){
int A;
printf("Enter a numbers\n");
scanf("%d", &A);
/* Calling function using call by reference */
getDoubleValue(&A);
/* Any change in the value of formal parameter(F)
will effect the value of actual parameter(A) */
printf("A(Actual Parameter) = %d\n", A);
getch();
return 0;
}
Output

Enter a numbers
7
F(Formal Parameter) = 9
A(Actual Parameter) = 9
Call by value and call by reference:
Data can be passed from calling function to the called function in two ways
1. Call by value
2. Call by reference
In call by value a copy of the values of actual arguments from calling function are passed to the formal
parameters of the called function

Output:
values of x and y before swap
x=20 y=30
values of x and y after swap
x=20 y=30
Note:It is noticed that there is no change in the values of x and y of the function main after the call of the
function swap. Because, the function swap interchanged the values of a and b in the copy and this change is not
reflected in the original arguments x and y.
In call by reference the addresses of actual arguments are passed to the formal parameters. Since the formal
parameters hold addresses, they must be declared as pointers.

Output:Values of x and y before swap


x=20 y=30
values of x and y after swap
x=30 y=20
Note: since addresses of the actual parameters x and y are passed to the function swap, the interchange made by
the function swap is reflected in the actual arguments
Session 23 Recursion
RECURSION
Recursion is a process in which a problem is defined in terms of itself. The problem is solved
by repeatedly breaking it into smaller problems, which are similar in nature to the original
problem.

Smaller problems are solved and their solutions are applied to get the final
solution of the original problem.

To implement recursion technique in programming, a function should be


capable of calling itself. A recursive function is a function that calls itself.

Example:
void fun1()
{
--------
fun1();
--------
}
The function call fun1() is in the body of the function fun1().Thus fun1() calls itself. This feature is called
recursion.
Example:

void main()
{
printf(“\nKLU”);
main();
}
In this example main() calls itself indefinitely.
Since recursion process simulates repetitive process, it is required to check a condition for stopping the
repetitions.
Writing a Recursive Function
Recursion is a way of thinking about a problem, so before writing recursive function for a problem we should be
able to define the solution of problem in terms of a similar type of a smaller problem.
The two main steps in writing a recursion function are-
• Identification of base case and its solution, i.e., the case where solution can be achieved
without recursion.
• Identification of the general case or the recursive case i.e., the case in which recursion call
will be made.
Identification of base case is very important because without it the function will keep on calling
itself resulting in infinite recursion.
We must ensure that each recursive call takes us closer to the base case i.e., the size of the problem should be
diminished at each recursive call.
*The recursive calls must be made in such a way that finally we arrive at the base case. If we don’t do so, we
will have infinite loop.
*So merely defining a base case will not help us avoid infinite recursion, we should implement the function such
the base case finally reached.

Flow of Control in Recursive Functions

When any function is called from main(), the memory is allocated to it on stack. A recursive function calls itself,
the memory for called function is allocated on top of memory allocated to calling function and different copy of
local variables is created for each function call. When the base case is reached, the function returns its value to
the function by whom it is called and memory is de-allocated and the process continues.

Let us take the example how recursion works by taking a simple function.

// A C++ program to demonstrate working of recursion


#include<stdio.h>
void printFun(int test)
{
if (test < 1)
return;
else
{
printf(“%d ”, test );
printFun(test-1); // statement 2
printf(“test is %d ”,test );
return;
}
}

int main()
{
int test = 3;
printFun(test);
}

Output :
321123

When printFun(3) is called from main(), memory is allocated to printFun(3) and a local variable test is
initialized to 3 and statement 1 to 4 are pushed on the stack as shown in below diagram. It first prints ‘3’. In
statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable test is initialized to
2 and statement 1 to 4 are pushed in the stack. Similarly, printFun(2) calls printFun(1) and printFun(1) calls
printFun(0). printFun(0) goes to if statement and it return to printFun(1). Remaining statements of printFun(1)
are executed and it returns to printFun(2) and so on. In the output, value from 3 to 1 are printed and then 1 to 3
are printed. The memory stack has been shown in below diagram.

Examples of Recursion:
Recursive function to find factorial of an integer
For example (Factorial of 5) is: !5 = 5*4*3*2*1 = 120
Factorial program using recursion

/*C program to find factorial of a number using recursion.*/

#include <stdio.h>
//function for factorial
long int factorial(int n)
{
if(n==0) return 1;
return n*factorial(n-1);
}

int main()
{
int num;
long int fact=0;

printf("Enter an integer number: ");


scanf("%d",&num);

fact=factorial(num);
printf("Factorial of %d is = %ld",num,fact);
printf("\n");
return 0;
}

Factorial of an integer is a recursive function in Mathematics and is defined as follows


n!= 1 , if n=0 or 1
n(n-1)! , if n>1
Using this mathematical function we can write the corresponding C code.
long int factorial ( int n)
{
if (n = = 0 )
return(1)
else
return(n*factorial(n-1));
}
Session 24 More Problems on Recursion
Contents:
Summation of numbers from 1 to n
We can say the sum of the numbers from 1 to n is equal to n plus the sum of numbers 1 to n-1.
summation(n) = n + summation(n-1)
summation (4) = 4 + summation (3)
= 4 + 3 + summation (2)
= 4 + 3 + 2 + summation (1)
= 4 + 3 + 2 + 1 + summation (0)
We know summation will be equal to 0 and in this case the function should retun 0.

int summation (int n)


{
if(n==0)
return 0;
return (n + summation(n-1));
}

Program:
#include<stdio.h>
int add(int n);
int main()
{
int num;
printf(“enter a positive number”);
scanf(“%d”,&num);
Printf(“sum of n numbers is: %d\n”,add(n));
}

Int add(int x)
{
If(n!=0)
return( n+add(n-1) );
else
return n;
}

For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14.GCD of 36,60 is 12.
Finding GCD of two numbers
This program takes two positive integers as input from the user and calculates GCD using recursion.
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1,n2));
return 0;
}

int hcf(int n1, int n2)


{
if (n2 != 0)
return hcf(n2, n1%n2);
else
return n1;
}

Fibonacci Series
Following is another example which generates fibonacci series for a given number using a recursive function:
#include <stdio.h>
int fibonaci(int i)
{
if(i= =0)
return 0;
else if (i= =1)
return 1;
else return (fibonaci(i-1) + fibonaci(i-2));
}
void main()
{
int i;
for (i = 0; i < 10; i++)
printf("%d\t%n", fibonaci(i));

}
When the above code is compiled and executed, it produces the following result:
0 1 1 2 3 5 8 13 21 34

Session 25 Storage Classes


Content:
Storage class of variable Determines following things –
1. Where the variable is stored
2. Scope of Variable
3. Default initial value
4. Lifetime of variable
A. Where the variable is stored :
Storage Class determines the location of variable , Where it is declared. Variables declared with auto storage
classes are declared inside main memory whereas variables declared with keyword register are stored inside the
CPU Register.

B. Scope of Variable
Scope of Variable tells compile about the visibility of Variable in the block.
Variable may have (a)Block Scope , (b)Local Scope and (c)External Scope.

Wiki has defined variable scope as –


In computer programming, a scope is the context within a computer program in which a variable name or other
identifier is valid and can be used, or within which a declaration has effect

C. Default Initial Value of the Variable


Whenever we declare a Variable in C, garbage value is assigned to the variable. Garbage Value may be
considered as initial value of the variable. C Programming have different storage classes which has different
initial values such as Global Variable have Initial Value as 0 while the Local auto variable have default initial
garbage value.

D. Lifetime of variable
Lifetime of the = Time Of - Time of Variable
variable Declaration Destruction
Suppose we have declared variable inside main function then variable will be destroyed only when the control
comes out of the main .i.e end of the program.

C Programming Storage Class


Every variable in C programming has two properties: type and storage class. Type refers to the data type of
variable whether it is character or integer or floating-point value etc. And storage class determines how long it
stays in existence.
There are 4 types of storage class:
1. Automatic 2. External 3. Static 4. register

Automatic storage class


Keyword for automatic variable
auto
Variables declared inside the function body are automatic by default. These variable are also known as local
variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are rarely used.
External storage class
External variable can be accessed by any function. They are also known as global variables. Variables declared
outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1 and that
variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in file 2
to indicate that, the variable specified is global variable and declared in another file.
Example to demonstrate working of external variable
#include
void Check();
int a=5;
/* a is global variable because it is outside every function */
int main(){
a+=4;
Check();
return 0;
}
void Check(){
++a;
/* ----- Variable a is not declared in this function but, works in any function as they are global variable ------- */
printf("a=%d\n",a);
}

Register Storage Class


Keyword to declare register variable
Register
Example of register variable
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register rather than
memory. Value stored in register is much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared register
variables.
Since, there are limited number of register in processor and if it couldn't store the variable in register, it will
automatically store it in memory.

Static Storage Class


The value of static variable persists until the end of the program. A variable can be declared static using
keyword: static. For example: static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check();
void main()
{
Check();
Check();
Check();
}
void Check()
{
static int c=0;
c++;
printf("%d\t",c);
}
Output: 1 2 3 Output: 1 1 1 Default value of c =0 if static

Global Declaration:
#include<stdio.h>
void Check();
int a=5; // "a” is global variable because it is outside every function
void main()
{
a+=4;
printf("a=%d\n",a);
Check(); // Variable “a” is not declared in this function but, works in any
function as they are global variable
}
void Check()
{
++a;
printf("a=%d\n",a);
}

Output: a=9, a=10

What is the output of the following program?


void main( )
{
static int y;
printf(“\n x=%d”, ++x);
printf(“\n y=%d”, y+=5);
}

What is the output of the following program?

void main( )
{
int i;
for(i=1; i<5; i++)
printf(“%d\n”, fun1( ));
}
int fun1(void )
{
static int x=10;
return(++x);
}

Demonstration of Extern Storage Class

First File: main.c


#include <stdio.h>
#include “support.c”
int count ;
extern void write_extern();
void main()
{
count = 5;
write_extern();
}

Output: count is 5
//Default value of extern is Zero

Session 26 Arrays
Content:
Arrays:

An array is a group of similar data types stored under a common name.

int a[10]; // Here a[10] is an array with 10 values.


int B[10] = {21,23,12,34};
// B[0] = 21 ; B[1] =23 ; B[2] = 12 ; B[3]=34;
TYPES:
1. One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array

Solutions for Lab Taken to Class:

Insert elements in 1D-Array

for (i=0; i < n; i++)


{ printf(“Enter the %d element = ”,i+1);
scanf(“%d”, &marks[i]);
}

Display elements in 1D-Array

for (i=0; I < n; i++)


printf(“\n marks[%d] = %d”, i+1,marks[i]);

Student practice the following two programs:

1. Program to print the position of given element from the list of values (To print the location of
given employee id in an array)
void main( )
{
int a[10],i,n,pos,ele;
printf(“enter n value”);
scanf(“%d”,&n);
printf(“enter values for the array”);
for(i=0;i<n;i++)
{
scanf(“%d”,&n);
}
printf(“enter the value to find position”);
scanf(“%d”,&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
pos=i+1;
}
}

printf(“position of the given value is %d”,pos);


}

2. program to find the average of given N positive integers and then find out the number of elements
less than the average and greater than the average.
void main( )
{
int a[10],i,n,lcount=0,scount=0,avg,sum=0;
printf(“ enter n value”);
scanf(“%d”,&n);
printf(“enter values for the array”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i]);
}
avg=sum/n;
for(i=0;i<n;i++)
{
if(a[i]>=avg)
Gcount++;
else
scount++;
}
printf(“number of values less than average =%d”,scount);
printf(“number of values grater than average=%d”,lcount);
}

To Calculate Average Using Arrays

#include <stdio.h>
int main(){
int n, i;
float num[100], sum=0.0, average;
printf("Enter the numbers of data: ");
scanf("%d",&n);
while (n>100 || n<=0)
{
printf("Error! number should in range of (1 to 100).\n");
printf("Enter the number again: ");
scanf("%d",&n);
}
for(i=0; i<n; ++i)
{
printf("%d. Enter number: ",i+1);
scanf("%f",&num[i]);
sum+=num[i];
}
average=sum/n;
printf("Average = %.2f",average);
return 0;
}

C program to read N integers into an array A and


* a) Find the sum of negative numbers
* b) Find the sum of positive numbers
* c) Find the average of all numbers
d) program to find the sum of all even and odd numbers
e) program to find the count of even numbers and odd numbers
f)
* Display the results with suitable headings
*/
#include <stdio.h>
#define MAXSIZE 10

void main()
{
int array[MAXSIZE];
int i, num, negative_sum = 0, positive_sum = 0;
float total = 0.0, average;

printf ("Enter the value of N \n");


scanf("%d", &num);
printf("Enter %d numbers (-ve, +ve and zero) \n", num);
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array elements \n");
for (i = 0; i < num; i++)
{
printf("%+3d\n", array[i]);
}
/* Summation starts */
for (i = 0; i < num; i++)
{
if (array[i] < 0)
{
negative_sum = negative_sum + array[i];
}
else if (array[i] > 0)
{
positive_sum = positive_sum + array[i];
}
else if (array[i] == 0)
{
;
}
total = total + array[i] ;
}
average = total / num;
printf("\n Sum of all negative numbers = %d\n", negative_sum);
printf("Sum of all positive numbers = %d\n", positive_sum);
printf("\n Average of all input numbers = %.2f\n", average);
}
Session 27 Pointers & Arrays
Contents:
POINTERS AND ARRAYS
Arrays are abstract data types which store a group of logically related items belonging to same data type and are
referred by a common name.
Array is identified by its name (common name) .Which is nothing but the base address of the array or address of
first element of the array. Array name is pointer to the array.
Let int a[5] be an array and the computer reserve 5 storage locations as follows:

𝑎[0] 𝑎[1]𝑎[2]𝑎[3]𝑎[4]

10 20 30 40 50
2000 2002 2004 2006 2006
a (array name)

&a[0]

Array name ‘a’ represent the base address i.e 2000. Thus both a and &a[0] represent the address of the first
element i.e 2000.

In general &a[i] is represented as a+i to get the i th elements address of the array.

similarly a[0] is 10 & *(a+1) also gives 10


a[1] is 20 & *(a+2) also gives 20
a[2] is 30 & *(a+3) also gives 30
a[3] is 40 & *(a+4) also gives 40
In general a[i] gives the value at i th location and is represented in pointers by *(a+i)

Array Of Pointers

We can declare an array that contains pointers as its elements. Every element of this array is a pointer variable
that can hold address of any variable of appropriate type.
The syntax of declaring an array of pointers is similar to that of declaring arrays except that an asterisk is
placed before the array name.
datatype *arrayname[size];

For example to declare an array of size 10 that contains integer pointers we can write
int *arrp[10];
/*Program for understanding the concept of array of pointers*/
#include<stdio.h>
main ( )
{
int *pa[3];
int i,a=5,b=10,c=15;
pa[0]=&a;
pa[1]=&b;
pa[2]=&c;
for(i=O;i<3;i++)
{
printf ("pa [%d] = %u \t",i,pa[i]);
printf("*pa[%d] = %d\n",i,*pa[i]);
}
}
Output:
pa[O] = 2012 *pa[O] = 5
pa[l] = 2560 *pa[l] = 10
pa[2] = 3020 *pa[2] = 15

Here pa is declared as an array of pointers. Every element of this array is a pointer to an integer. pa[i] gives the
value of the ith element of 'pa' which is an address of any int variable and *pa[i] gives the value of that int
variable.

The array of pointers can also contain addresses of elements of another array.
/*Program for understanding array of pointers* /
#include<sidio.h>
main( )
{
int i,arr[4]={5,lO,15,20};
int *pa[4];
for(i=O;i<4;i++)
pa[i] = &arr[i];
for(i=O;i<4;i++)
{
printf ("pa [%d] = %u \t",i,pa[i]);
printf (" *pa[%d] = %d\n",i,*pa[i]);
}
}
Output:
pa[O] = 1000 *pa[O] = 5
pa[l] = 1002 *pa[l] = 10
pa[2] = 1004 *pa[2] = 15
pa[3] = 1006 *pa[3] = 20

Here 'pa' is declared as array of pointers. Each element of this array contains the address of each element of
array 'arr'.
******************************************************************************
Now we'll take a 2-D array arr with 3 rows and 4 columns. An array of pointers of size 3 is declared and each
pointer in this array is assigned the address of Oth element of each row of the 2-D array, i.e., ith element of pa is
a pointer to Oth element of ith row of a 2-D array. This can be done as-

int arr[3] [4]={{10;11,12,13}, {20,21,22,23}, {30,31,32,33}};


int *pa[3];
for(i=0;i<3;i++)
pa [i] = arr[i] ;

Now let us see how we can access the elements of the 2-D array' arr using the array of pointers pa.
pa[0] is a pointer to the 0th element of 0th I-D array of the array arr, similarly pa will be a pointer to 0th element
of ith I-D array of arr.

Since base type of pointer pa[i] is int, so if we want the address of jth element of ith I-D array then we can add j
to the expression pa[i]. Hence the expression pa[i]+j will give the address of jth element of ith I-D array. So the
expression *( pa[i]+j ) will give the value of the jth element of ith I-D array.

We know that pa[i] is equivalent to *(pa+i). So the above expression can be written as *(*(pa+i) +j), and we
know that this expression is equivalent to pa[i][j]. So finally we can access the jth element of ith I-D array by
writing pa[i][j].
/"program for understanding array of pointers*/
#include<stdio.h>
main( )
{
int i, j , arr [3] [4] = { { 10, 11, 12, 13}, {2 0,21,22, 23 }, {3 0, 31,32,33 } } ;
int *pa[3];
for(i=O;i<3;i++)
pa [i] =arr [i] ;,
for(i=O;i<3;i++)
{ for(j=O;j<4;j++)
printf("%d ",pa[i] [j]);
printf("\n");
}
}
Output:
10 11 12 13
20 21 22 23
30 31 32 33
Pointer to an Array

We can also declare a pointer that can point to the whole array. This pointer is useful
when talking about multidimensional arrays.
Declaring a pointer to an array.
int (*Ptr)[10] ;
Here ptr is pointer that can point to an array of 10 integers. Note that it is necessary to enclose the pointer name
inside parentheses. Here the type of ptr is 'pointer to an array of 10 integers' Note that the pointer that points to
the 0th element of array and the pointer that points to the whole array are totally different. The following
program shows this'::
/*P9.11 Program to understand difference between pointer to an integer and pointer to an array of
integers*/
#include<stdio.h>
int main(void)
{
int *p; /*Can point to an integer*/
int (*ptr)[5]; /*Can point to an array of 5 integers*/
int arr[5];
p=arr; /*Points to 0th element of arr*/
ptr=&arr; /*Points to the whole array arr*/
printf("p=%p,ptr=%u\n",p,ptr);
p++;
ptr++;
printf("p=%p,ptr=%u\n",p,ptr);
return 0;
}
Output:
p = 3000, ptr = 3000
p = 3004, ptr = 3010

Here p is pointer that points to 0th element of array arr, while ptr is a pointer that points to the whole array arr.
The base type of p is 'int' while base type of ptr is an array of 5 integers.' We Know that the pointer arithmetic is
performed relative to the base size, so if we write ptr++, then the pointer ptr will be shifted forward by 10 bytes.
The following figure shows the pointers p and ptr, in this chapter we'll use darker arrow to denote pointer to an
array

On dereferencing a pointer expression we get a value pointed to by that pointer expression. Pointer to an array
points to an array, so on dereferencing it we should get the array, and the name of array denotes the base
address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it
points.
/*Program to dereference a pointer to an array*/
#include<stdio.h>
main ( )
{
int arr [5J = {3, 5,6,7,9} ;
int *p=arr;
int (*ptr) [5]=arr;
printf("p = %u, ptr = %u\n",p,ptr);
printf("*p = %d, *ptr = %u\n",*p,*ptr);
printf("sizeof(p) = %u, sizeof(*p) = %u\n",sizeof(p),sizeof(*p));
printf("sizeof(ptr) = %u, sizeof(*ptr) = %u\n",sizeof(ptr),sizeof(*ptr));
}
p = 3000, ptr = 3000
*p = 3, *ptr = 3000
sizeof(p) = 2, sizeof(*p) = 2
sizeof(ptr) = 2, sizeof(*ptr) = 10

Session 28 Two Dimensional Arrays & Arrays and Functions


Content:
2D-Arrays
The syntax of declaration of a 2-D array is similar to that of I-D arrays, but here we have two subscripts.
Syntax:
data_type variable[row] [column];
Example:
int a[3][4];

Initilizing a 2D Array
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array
with 3 rows and each row has 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to
the previous example −

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Processing 2-D Arrays

For processing 2-D arrays, we use two nested for loops. The outer for loop corresponds to the row
and the inner for loop corresponds to the column.

Insert elements in 2D-Array


Matrix : A[n][m] => n x m => i x j ; i = 0 to < n
j = 0 to < m
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
printf(“Enter the %d x %d element = ”,i+1,j+1);
scanf( “%d”, &A[i][j] );
}
}

Display elements in 2D-Array

Matrix : A[n][m] => n x m => i x j ; i = 0 to < n


j = 0 to < m
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
printf (“\t %d”, A[i][j]);
}
printf (“\n”);
}

Explanation of the following program:

1. Program to read and print values of an m*n matrices.


void main()
{
int a[10][10],r,c,i,j;
printf(“enter number of rows and columns”);
scanf(“%d%d”,&r,&c);
printf(“enter values for the matrix”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“values in the matrix are”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“\t %d”,a[i][j]);
}
printf(“\n”);
}
}

Passing array to Functions


If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal
parameter in one of following three ways and all three declaration methods produce similar results because each
tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional
arrays as formal parameters.
void myFunction(int param[], int size) {
.
.
.
}
Example
Now, consider the following function, which takes an array as an argument along with another argument and
based on the passed arguments, it returns the average of the numbers passed through the array as follows −
#include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);

int main () {

/* an int array with 5 elements */


int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );

return 0;
}
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum = 0;

for (i = 0; i < size; ++i) {


sum += arr[i];
}
avg = sum / size;

return avg;
}

When the above code is compiled together and executed, it produces the following result −
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C performs no
bounds checking for formal parameters.

Session 29 Linear Search


Content:
Linear Search
Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items
one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the
search continues till the end of the data collection.

A simple approach is to do linear search, i.e

• Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
• If x matches with an element, return the index.
• If x doesn’t match with any of elements, return -1.
// Linearly search x in arr[]. If x is present then return its
// location, otherwise return -1
int search(int arr[], int n, int x)
{
int i;
for (i=0; i<n; i++)
if (arr[i] == x)
return i;
return -1;
}

The time complexity of above algorithm is O(n).


Linear search is rarely used practically because other search algorithms such as the binary search algorithm and
hash tables allow significantly faster searching comparison to Linear search.

Session 30 Binary Search


Content:
Binary Search
• Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
• A simple approach is to do linear search. The time complexity of above algorithm is O(n). Another
approach to perform the same task is using Binary Search.
• Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of
the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found or the interval is empty.

The idea of binary search is to use the information that the array is sorted and reduce the time complexity to
O(Logn).
We basically ignore half of the elements just after one comparison.
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid
element. So we recur for right half.
4. Else (x is smaller) recur for the left half.
Recursive implementation of Binary Search

#include <stdio.h>

// A recursive binary search function. It returns location of x in


// given array arr[l..r] is present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;

// If the element is present at the middle itself


if (arr[mid] == x) return mid;

// If element is smaller than mid, then it can only be present


// in left subarray
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);

// Else the element can only be present in right subarray


return binarySearch(arr, mid+1, r, x);
}

// We reach here when element is not present in array


return -1;
}

int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
Run on IDE

Output:
Element is present at index 3
Iterative implementation of Binary Search

C/C++PythonJava
#include <stdio.h>

// A iterative binary search function. It returns location of x in


// given array arr[l..r] if present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r)
{
int m = l + (r-l)/2;

// Check if x is present at mid


if (arr[m] == x)
return m;

// If x greater, ignore left half


if (arr[m] < x)
l = m + 1;

// If x is smaller, ignore right half


else
r = m - 1;
}
// if we reach here, then element was not present
return -1;
}

int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
Output:
Element is present at index 3
Time Complexity:
The time complexity of Binary Search can be written as

T(n) = T(n/2) + c
The above recurrence can be solved either using Recurrence T ree method or Master method. It falls in case II of
Master Method and solution of the recurrence is \Theta(Logn).
Session 31 Bubble Sort
Content:
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they
are in wrong order.

Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap
them.

Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one
whole pass without any swap to know it is sorted.

Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Fourth Pass
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

// C program for implementation of Bubble sort


#include <stdio.h>
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)

// Last i elements are already in place


for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
for (int i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Output:
Sorted array:
11 12 22 25 34 64 90

Time complexity: Best Case:O(N) Average case: O(N2) Worst Case:O(N2)


Space complexity :In Place or O(1)

You might also like