0% found this document useful (0 votes)
21 views55 pages

Module 3 - C

Uploaded by

gokulrgowda7244
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)
21 views55 pages

Module 3 - C

Uploaded by

gokulrgowda7244
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/ 55

Principles of Programming using C – BPOPS203 MODULE 3

Module 3 Notes
Functions: Introduction using functions, Function definition, function
declaration, function call, return statement, passing parameters to
functions, scope of variables, storage classes, recursive functions. Arrays:
Declaration of arrays, accessing the elements of an array, storing values in
arrays, Operations on arrays, Passing arrays to functions, two dimensional
arrays, operations on two-dimensional arrays, two-dimensional arrays to
functions, multidimensional arrays, applications of arrays.

1
Principles of Programming using C – BPOPS203 MODULE 3

MODULE-3

FUNCTIONS

 A function is a block of statements that performs a particular task. Functions are basic building
blocks of C program. A function is a series of instructions or group of statements with one
specific purpose. A function is a program segment that carries out some specific, well defined
task. A function is a self-contained block of code that performs a particulartask.

The function can be classified into two categories:


1. Built-in Functions (Library functions)
2. User defined functions

1. Built-in functions:
 The C compiler has a collection of functions which performs a predefined task. Thesefunctions
are defined in the library of C compiler which are used frequently in the C program. These
functions are written by designers of C compiler.
 C supports many built in functions like
 Mathematical functions ex: sqrt(), pow()
 String manipulation functions ex: strcat(), strlen()
 Input and output functions ex: printf(), scanf()
 Memory management functions ex: malloc(), calloc()

2. User defined functions


The function written by programmer to do specific task is called user defined function.

Elements of user defined functions are shown below:


a. Function declaration
b. Function Call
c. Function definition

a. Function declaration/Function Prototype


Every function in C program should be declared before they are used. Function declaration gives
information to the compiler about
a. function name
b. type of arguments to be passed and
c. return value type

2
Principles of Programming using C – BPOPS203 MODULE 3

Syntax:
return_type function_name(type(1) parameter(1), ...,type(n) parameter(n));

b. Function Call
Invocation of the function is called function call. Control from calling function will be transferred to
the called function when the function call is made. The parameters used in function call are called
actual parameters.

Syntax:
function_name(parameter(1), ... parameter(n));

c. Function Definition
Function definition contains programming codes to perform specific task. Function definition consists
of two parts. Function Header that identifies the function, followed by Function Body that contains
the executable code for that function. The parameters used in function definition are called formal
parameters.

Syntax:
return_type function_name(type(1) parameter(1),..,type(n) parameter(n))
{
Local variable declaration;
Statement1;
Statement2;
.
.
Statement-n;
return statement;
}

Example:
#include <stdio.h>
#include <conio.h>
int add(int a, int b); ------------- function declaration
void main()
{
int a, b, sum;
clrscr();
printf("Enter two numbers to add \n");
scanf("%d %d", &a, &b);
3
Principles of Programming using C – BPOPS203 MODULE 3

sum=add(a,b); ---------------- function call & actual parameters


printf("\n sum=%d", sum);
getch();
}
int add(int a, int b) --------------  function definition & formal parameters
{
int sum;
sum=a+b;
return sum; ----------- return statement of function
}
Output:
Enter two numbers to add: 2 3
sum=5

Advantages of User Defined Functions:


1) User defined functions helps to decompose the large program into small segments which makes
programming easy to understand, maintain and debug.
2) If repeated code occurs in a program, Functions can be used to include those codes and execute
when needed by calling that function.
3) Programmers working on large project can divide the workload by making different functions.

return statement:

The return statement terminates the execution of the called function and returns control to the
calling function. When the return statement is encountered, the program execution resumes in the
calling function at the point immediately following the function call. A return statement may or
may not return a value to the calling function.
Syntax: return <expression>;
Specifying expression is optional. The value of expression, if present, is returned to the calling
function. A function that has void as its return type cannot return any value to the calling function.
For functions that have no return statement, the control automatically returns to the calling function
after the last statement of the called function is executed.

Categories / Classification of user defined functions: (based on parameter passing and return
value)
The user defined function categorized into 4 types. They are
a. Function without parameters and no return value
b. Function without parameters and return value
c. Function with parameters and no return value
d. Function with parameters and return value

4
Principles of Programming using C – BPOPS203 MODULE 3

a. Function without parameters and no return value


This type of function does not have parameters and does not return any values to the main
function.

Program:
#include <stdio.h>
#include <conio.h>
void add();
void main()
{
clrscr();
add();
getch();
}
void add()
{
int a, b, sum;
printf("Enter two numbers to add : ");
scanf("%d %d", &a, &b);
sum=a+b;
printf("\n sum=%d", sum);
}
Output:
Enter two numbers to add: 2 3
sum=5

5
Principles of Programming using C – BPOPS203 MODULE 3

b. Function without parameters and return value


This type of function does not have parameters and returns values to the main function.
Program:
#include <stdio.h>
#include <conio.h>
int add();
void main()
{
int sum;
clrscr();
sum=add();
printf("\n sum=%d", sum);
getch();
}
int add()
{
int a, b, sum;
printf("Enter two numbers to add \n");
scanf("%d %d", &a, &b);
sum=a+b;
return sum;
}
Output:
Enter two numbers to add: 2 3
sum=5

6
Principles of Programming using C – BPOPS203 MODULE 3

c. Function with parameters and no return value


This type of function has parameters and does not return values to the main function.
Program:
#include <stdio.h>
#include <conio.h>
void add(int a, int b);
void main()
{
int a, b, sum;
clrscr();
printf("Enter two numbers to add \n");
scanf("%d %d", &a, &b);
add(a, b);
getch();
}
void add(int a, int b)
{
sum= a+ b;
printf("\n sum=%d", sum);
return;
}
Output:
Enter two numbers to add: 2 3
sum=5

7
Principles of Programming using C – BPOPS203 MODULE 3

d. Function with parameters and return value


This type of function has parameters and returns values to the main function.
Program:
#include <stdio.h>
#include <conio.h>
int add(int a, int b);
void main()
{
int a, b, sum;
clrscr();
printf("Enter two numbers to add \n");
scanf("%d %d", &a, &b);
sum=add(a,b);
printf("\n sum=%d", sum);
getch();
}
int add(int a, int b)
{
int sum;
sum=a+b;
return sum; //return statement of function
}
Output:
Enter two numbers to add: 2 3
sum=5

8
Principles of Programming using C – BPOPS203 MODULE 3

Argument/Parameter Passing Techniques:


There are two ways of passing parameters to the function
a. Pass by value (call by value)
b. Pass by reference (call by reference)

a. Pass by value: (call by value)


In this type, values of actual parameters are passed to the formal parameters. (i.e formal parameters
contains only the copy of the actual parameters). So if we do any changes in formal parameters in
the function definition the values of actual parameters will not change.
Program:
#include <stdio.h>
#include <conio.h>
void exchange(int a, int b);
void main()
{
int x,y,
clrscr();
printf(“Enter values of x & y : “);
scanf(“%d %d “, &x, &y);
printf(“\n old values x=%d y =%d”, x, y);
exchange(x,y) ;
printf(“\n new values x=%d y =%d”, x, y);
}
void exchange(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
Output:
Enter values of x & y: 2 3
old values x=2 y =3
new values x=2 y =3

b. Pass by reference: (call by reference)


In this type, addresses of actual parameters are passed to the formal parameters. So in the function
definition the formal parameters should be pointers. So if we do any changes in formal parameters
in the function definition the values of actual parameters will change.

9
Principles of Programming using C – BPOPS203 MODULE 3

Program:
#include <stdio.h>
#include <conio.h>
void exchange(int a, int b);
void main()
{
int x,y,
clrscr();
printf(“Enter values of x & y : “);
scanf(“%d %d “, &x, &y);
printf(“\n old values x=%d y =%d”, x, y);
exchange(&x,&y) ;
printf(“\n new values x=%d y =%d”, x, y);
}
void exchange(int *a, int *b)
{
int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}
Output:
Enter values of x & y: 2 3
old values x=2 y =3
new values x=3 y =2

10
Principles of Programming using C – BPOPS203 MODULE 3

Formal Parameters and Actual Parameters


 Formal Parameters:
 The variables defined in the function header of function definition are calledformal
parameters.
 All the variables should be separately declared and each declaration must be separated by
commas.
 The formal parameters receive the data from actual parameters.
 Actual Parameters:
 The variables that are used when a function is invokedin function call are called actual
parameters.
 Using actual parameters, the data can be transferred from calling functionto the called
function.
 The corresponding formal parameters in the function definition receive them.
 The actual parameters and formal parameters must match in number and type of data.
Differences between Actual and Formal Parameters

RECURSION:
Usually a function (user defined function) is called from main function. If a function calls itself, it is
known as recursion. There are two types of recursion:
a. Direct Recursion
b. Indirect Recursion
Syntax:
function1()
{
11
Principles of Programming using C – BPOPS203 MODULE 3

function1();

}
Factorial using Recursion: Write a C Program to find factorial of a given number using recursion.
#include <stdio.h>
#include <conio.h>
int factorial(int);
void main()
{
int num,fact;
clrscr();
printf(“Enter the number to find it’s factorial:”);
scanf(“%d”,&num);
if(num<0)
{
printf(“\nFactorial of negative number is not possible”);
}
else
{
fact=factorial(num);
printf(“The factorial of %d is %d”, num,fact);
}
getch();
}
int factorial(int num)
{
if(num==0||num==1)
{
return 1;
}
else
{
return(num*factorial(num-1));
}
}
Output:
Enter the number to find its factorial:5
The factorial of 5 is 120

12
Principles of Programming using C – BPOPS203 MODULE 3

Fibonacci Series using Recursion: Write a C Program to print Fibonacci Series using recursion.
#include <stdio.h>
int Fibonacci(int Number)
{
if (Number ==0)
return 0;
else if (Number==1)
return 1;
else
return(Fibonacci(Number-1)+Fibonacci(Number-2));
}
void main()
{
int Number, i=0;
printf("Please enter How many Fibonacci number to be displayed:\n ");
scanf("%d",&Number);
printf("Fibonacci series are:\n");
for(i=0;i<Number;i++)
{
printf("%d\t", Fibonacci(i));
}
}
GCD using Recursion: Write a C Program to find GCD of two numbers using recursion.
#include <stdio.h>
int GCD(int, int);
void main()
{
int num1, num2, res;
printf("enter two numbers\n”);
scanf(“%d%d”,&num1,&num2);
res=GCD(num1, num2);
printf(“\n GCD of %d and %d = %d”, num1, num2, res);
getch();
}
intGCD(int x, int y)
{
int rem;
rem=x%y;
if(rem==0)
return y;
13
Principles of Programming using C – BPOPS203 MODULE 3

else
return (GCD(y,rem));
}
Write C Program to calculate exp(x,y) using recursion.
#include <stdio.h>
int exp_rec(int, int);
void main()
{
int num1, num2, res;
printf(“\nEnter two numbers”);
scanf(“%d%d”, &num1,&num2);
res=exp_rec(num1,num2);
printf(“\nRESULT=%d”,res);
getch();
}
int exp_rec(int x, int y)
{
if(y==0)
return 1;
else
return (x*exp_rec(x,y-1));
}

SCOPE OF VARIABLES
A scope in any program is a region of the program where a defined variable can have its existence
and beyond that it cannot be accessed. Scope is the accessibility and visibility of the variables at
different points in the program. A variable or constant in C has four types of scope: block, function,
program, file.

1. Block Scope: A statement block is a group of statements enclosed within 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 cease to exist. Such a variable also known as local variable is said to have
block scope.
#include <stdio.h>
int main()
{
int var = 34; // Scope of this variable is within main() function only.
printf("%d", var);
return 0;
}

14
Principles of Programming using C – BPOPS203 MODULE 3

2. Function Scope: The only type of identifier with function scope is a label name. A label is
implicitly declared by its appearance in the program text and is visible throughout the function that
declares it. A label can be used in a goto statement before the actual label is seen. Function scope
begins at the opening of the function and ends with the closing of it. Function scope is applicable to
labels only. A label declared is used as a target to goto statement and both goto and label statement
must be in same function.
void main()
{
……
……
loop:
……
……
……
goto loop;
…..
…..
}
In the above example label loop is visible from the beginning to the end of the main() function.
3. Program Scope: Program scope of variables in C is defined as having the availability of the
variable throughout the program. It means that the variable has a global scope, and it is available
all around for every function and every block in the program. Global variables declared outside the
function bodies have a program scope. The availability of global variables stays for the entire
program after its declaration. Moreover, global variables are initialized to zero automatically by the
compiler.

#include <stdio.h>
// variable with program scope
int x = 10;
void func()
{
// x is available in func() function,
// x now equals 10 + 10 = 20
x += 10;
printf("Value of x is %d\n", x);
}
void main()
{
func();
// x is also available in main() function

15
Principles of Programming using C – BPOPS203 MODULE 3

x += 30; // x now equals 20 + 30 = 50


printf("Value of x is %d", x);
}
4. File Scope : When a global variable is declared with static keyword it is said to have File Scope.
A global static variable can be used anywhere from the file in which it is declared but it is not
accessible by any other file.
ex: static int x;

STORAGE CLASSES:
Storage Classes defines the scope and lifetime of variables and functions declared within a C
program.
Syntax: <storage_class_specifier> <data_type> <Variable_name>

1. Extern Storage Class


Variables of this storage class are ―Global variables. Global Variables are declared outside the
function and are accessible to all functions in the program. Generally, External variables are declared
again in the function using keyword extern.
Ex: extern int num1 ;
Storage - Main Memory
Accessibility - Accessible within all program files that are a part of the program.
Default initial Value - Zero
Existence - Exists throughout the execution of program
2. Static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the life-
time of the program instead of creating and destroying it each time it comes into and goes out of
scope. Therefore, making local variables static allows them to maintain their values between function
calls. The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.
Ex: static int x=10;
Storage - Main Memory
Accessibility - Local: Accessible within function or block in which it is declared.
Global: Accessible with in the program in which it is declared.
Default initial Value - Zero
Existence - Local: Retains value between function calls
Global: Preserves value in program files
3. Automatic (Auto) storage class
This is default storage class. All variables declared are of type Auto by default. In order to Explicit
declaration of variable use auto keyword
auto int num1 ; // Explicit Declaration
Storage - Main Memory
Accessibility - Accessible within function or block in which it is declared
16
Principles of Programming using C – BPOPS203 MODULE 3

Default initial Value - Garbage value


Existence - Exists when the function or block in which it is declared is entered. Ceases to exist when
the control returns from the function or the block in which it was declared.
4. Register storage class
register keyword is used to define local variable. Local variables are stored in register instead of RAM.
As variable is stored in register, the Maximum size of variable = Maximum Size of Register. Unary
operator [&] is not associated with it because Value is not stored in RAM instead it is stored in
Register. This is generally used for faster access.
Ex: register int i;
Storage - CPU register
Accessibility - Accessible within function or block in which it is declared
Default initial Value - Garbage value
Existence - Exists when the function or block in which it is declared is entered. Ceases to exist when
the control returns from the function or the block in which it was declared.

Example for storage classes


#include <stdio.h>
int x;
void autoStorageClass()
{
printf("\nDemonstrating auto class\n\n");
auto int a = 32;
printf("Value of the variable a declared as auto: %d\n",a);
}
void registerStorageClass()
{
printf("\nDemonstrating register class\n\n");
register char b = 'G';
printf("Value of the variable b declared as register: %c\n",b);
}
void externStorageClass()
{
printf("\nDemonstrating extern class\n\n");
extern int x;
printf("Value of the variable x declared as extern: %d\n",x);
x = 2;
printf("Modified value of the variable 'x’ declared as extern: %d\n",x);
}
void staticStorageClass()
{
int i = 0;
printf("\nDemonstrating static class\n\n");
17
Principles of Programming using C – BPOPS203 MODULE 3

printf("\nLoop started:\n");
for (i = 1; i< 5; i++)
{
static int y = 5;
int p = 10;
y++;
p++;
printf("\nThe value of y declared as static is %d\n",y);
printf("The value of non-static variable p is %d\n",p);
}
printf("\nLoop ended:\n");
}
void main()
{
printf("A program to demonstrate storage Classes in C\n\n");
autoStorageClass();
registerStorageClass();
externStorageClass();
staticStorageClass();
}

18
Principles of Programming using C – BPOPS203 MODULE 3

19
20
20
Principles of Programming using C – BPOPS203 Module 3

22
Principles of Programming using C – BPOPS203 Module 3

23
Principles of Programming using C – BPOPS203 Module 3

ARRAYS
Definition
An Array is a fixed-size sequenced collection of elements of the same data type.
Arrays are referred to as structured data types because they are used to represent data values that
have a structure of some sort and array is a derived data type.
Numerical arrays are arrays in which the values of array elements are numbers (integer/float).
Character arrays or Strings are arrays in which the values of array elements are characters.

• An array is a group of data items of the same data type.


• An array name is a variable name that is used to represent a group of items.
• The elements are stored sequentially one after the other in memory.
• Array is a derived data type.
• Any element can be accessed by using name of the array and position of element in the
array.
• Each value in an array is reference by a single name, which is the name of the array, and
a subscript or index, which indicates the position of the value in the array.
• The subscript is always a positive integer number, which is enclosed in a pair of square
brackets. Example: int n[5]
• The below example shows that n is an array which can store integer values at 5
continuous locations starting from n[0],n[1],n[2],[n3],n[4] memory locations.

Types of Arrays
1. One Dimensional Arrays (1-D Arrays)
2. Two Dimensional Arrays (2-D Arrays)
3. Multi Dimensional Arrays

1. SINGLE DIMENSIONAL ARRAY


Definition:
Single dimensional array uses single subscript and single pair of square brackets to store the values.

Declaration:
Declaration of array is used for creation of memory space based on the type to store the values of
array.

24
Principles of Programming using C – BPOPS203 Module 3

Syntax: data type variable_name[size];


 data_type specifies the type of elements that will be contained in the array, such as int,
float or char.
 variable_name is a meaningful valid identifier.
 The size indicates the maximum number of elements that can be stored inside the array.

Example:
int n[5];
float avg[5];
char city_name[10];

The values can be stored in array using following methods:


1 Initializing all specified memory locations (compile time initialization)
2. Initializing individual elements (compile time initialization)
3 Partial array initialization.
4. Initialization during program execution. (Run time initialization)

Initialization:
Initialization is assigning values to array elements during declaration. Initialization of array can be
done in TWO ways:
i. Compile Time Initialization
ii. Run Time Initialization

i. Compile Time Initialization


In compile Time initialization the array elements are assigned values when they are declared.

Syntax: data type variable_name[size]={List of values};

Example:
intn[5]={10,20,30,40,50}; 10 20 30 40 50
n[0] n[1] n[2] n[3] n[4]

10 20 30 0 0

int n[5]= {10,20,30}; n[0] n[1] n[2] n[3] n[4]

NOTE: If the number of values in the list is less than array size then the remaining elements are
assigned to 0 automatically.

25
Principles of Programming using C – BPOPS203 Module 3

float avg[5]= {32.5, -22.22, 0, 55, 7};

32.5 -22.22 0 55 7

avg[0] avg[1] avg[2] avg[3] avg[4]

char city_name[10] =”BENGALURU”;


(OR)
char city_name[10]= { ‘B’ , ‘E’ , ‘N’ , ‘G’ , ‘A’ , ‘L’ , ‘U’ , ‘R’ , ‘U’ , ‘\0’};

B E N G A L U R U \0

NOTE: When the user initializes the character array by giving each character then the \0 character
should also be specified. Also, one extra element space must be declared to store null character
(\0) in case of character arrays.

char city_name[10]= { ‘B’ , ‘E’ , ‘N’ , ‘G’ , ‘A’ , ‘L’ , ‘U’ , ‘R’ , ‘U’ , ‘\0’};

NOTE: If array size is not given then system automatically allocates the required memory space.

Example 1: (Compile Time Initialization)

ii. Initializing individual elements:


The syntax for initializing an individual element of a one-dimensional array is as follows:
array_name[index] = value;
Where array_name represents the name of the array.
• index represents the position of the array element in the array.
• value represents the value being assigned to the array element.
Example:
int age[5];
age[01]=2;

26
Principles of Programming using C – BPOPS203 Module 3

age[1]=4;
age[2]=34;
age[3]=3;
age[4]=4;
iii. Partial array initialization:
It is allowed in C language, if the number of values to be initialized is less than size of array,then the
remaining locations will be initialized to zero automatically by compiler.
Example: int age[5]={2,3}; 2 3 0 0 0

iv. Run Time Initialization


In Run Time Initialization, the value of the array is initialized during execution of the program.
Example: for(i=0; i<n; i++)
{
scanf(“%d”, &a[i]);
}

Example 2 (Run Time Initialization)


#include <stdio.h>
#include<conio.h>
void main()
{
int n, a[10],i;
clrscr();
printf(“Enter the number of Elements in the array\n”);
scanf(“%d”, &n);
printf(“Enter the array elements \n”);
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);
printf(“Printing of array elements \n”);
for(i=0; i<n; i++)
printf(“%d\n”, a[i]);
}

Reading and writing one dimensional array


The following shows the reading and writing to the one dimensional array: Example:
int age[5];
Reading: for(i=0;i<5;i++)

27
Principles of Programming using C – BPOPS203 Module 3

scanf ("%d", &age [i]);


Writing:
for (i=0;i<5;i++)
printf("%d", age[i]);
Example 1:
Write C program to find the sum of N numbers using single dimensional array.
#include <stdio.h>
#include<conio.h>
void main()
{
int n, a[10],i,sum; clrscr();
printf(“Enter the number of Elements in the array\n”);
scanf(“%d”, &n);
printf(“Enter the array elements \n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]); sum=0;
for(i=0;i<n;i++) sum=sum+a[i];
printf(“SUM=%d\n”, sum);
getch();
}
Output:
Enter the number of Elements in the array
5
Enter the array elements
10
20
30
40
50
SUM=150
Example 2:
Write a C program to read N integers into an array A and to
(i)find the sum of odd numbers
(ii) find the sum of even numbers
(iii) find the average of all numbers
#include <stdio.h>
#include <conio.h>
void main()
{
int n,i,a[10],oddsum,evensum;
28
Principles of Programming using C – BPOPS203 Module 3

float avg;
clrscr();
printf(“Enter the value of n:\n”);
scanf(“%d”, &n);
printf(“ Enter the array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);
oddsum=0;
evensum=0;
for(i=0;i<n;i++)
{
if(a[i] % 2 == 0)
evensum=evensum+a[i];
else
oddsum=oddsum+a[i];
}
avg=(evensum+oddsum)/n;
printf(“The sum of EVEN number is:%d\n”,evensum);
printf(“The sum of ODD number is:%d\n”, oddsum);
printf(“The average of all number is:%f\n”, avg);
getch();
}
Output:
Enter the value of n:
5
Enter the array elements
1
2
3
4
5
The sum of EVEN number is: 6
The sum of ODD number is: 9
The average of all number is: 3

Example 3:
Write C Program to evaluate the polynomial f(x) = a4x4+a3x3+a2x2+a1x+a0, for a given value of x
and its coefficients using Horner’s method.

29
Principles of Programming using C – BPOPS203 Module 3

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float coeff[10], x, fx;
int i;
clrscr();
printf(" Enter the coefficients of a given polynomial (i.e.,a0,a1,a2,a3,a4 )\n");
for(i = 0 ; i<= 4 ; i++)
{
printf(“coeff [%d] = \n“,i);
scanf("%f", &coeff[ i] );
}
printf(" Enter the value of x \n");
scanf("%f",&x);
fx=0;
for( i = 4 ; i>= 0 ; i--)
fx = fx +pow(x,i) * coeff[ i];
printf("f(%f) = %.2f\n",x,fx);
getch();
}
Output
Enter the coefficients of a given polynomial (i.e., a0, a1, a2, a3 and a4)
coeff [0] = 1 coeff [1] = 2 coeff [2] = 3 coeff [3] = 4 coeff [4] = 5
Enter the value of x
2
f(2) = 129.00
Example 4:
Write a C program to generate Fibonacci numbers using arrays.
#include <stdio.h>
#include<conio.h>
void main()
{
int i,n,fib[10]={0,1,1};
clrscr();
printf(“Enter the number of terms to generate\n”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
fib[i+3]=fib[i+2]+fib[i+1];

30
Principles of Programming using C – BPOPS203 Module 3

printf(“\n Fibonacci Series:\n”);


printf(“The initial values are\n”);
printf(“%d \n %d \n %d\n”, fib[0],fib[1],fib[2]);
printf(“The generated series is\n”);
for(i=3;i<n+3;i++)
printf(“%d\n”, fib[i]);
getch();
}
Output:
Enter the number of terms to generate
5
Fibonacci Series:
The initial values are
0
1
1
The generated series is
2
3
5
8
13

Example 5:
Write a C program to read N elements and find biggest element in the array.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],n,I,largest;
clrscr();
printf(“Enter the size of the array\n”);
scanf(“%d”, &size);
printf(“Enter the elements of the array\n”);
for (i=0;i<n; i++)
scanf(“%d”, &a[i]);
largest= a[0];
for(i=1;i<size;i++)
{
if(a[i]>largest)
31
Principles of Programming using C – BPOPS203 Module 3

largest=a[i];
}
printf(“The largest element in the array is %d\n”, largest);
getch();
}
Output:
Enter the size of the array
5
Enter the elements of the array
12
35
-10
-50
28
The largest element in the array is 35

Two-Dimensional Arrays
• The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns.
• 2D arrays are created to implement a relational database(table) lookalike data structure.
• It provides ease of holding the bulk of data at once which can be passed to any number of
functions wherever required.

Declaration of Two-Dimensional Arrays in C


A two-dimensional array has two subscripts. It is declared using the below syntax.

Syntax: datatype arrayname[row-size][column-size];


Example : int a[3][3];
Here, a is a 2-D array with 3 rows and 3 columns. This informs the compiler to reserve 9
locations consecutively one after the other. The elements are stored as below.
Col-0 Col-1 Col-2
Row-0 n[0][0] n[0][1] n[0][2]
Row-1 n[1][0] n[1][1] n[1][2]
Row-2 n[2][0] n[2][1] n[2][2]

Initialization of 2D Arrays in C
The two-dimensional arrays can be initialized in the following way. In case of 2-D arrays the values
are initialized row wise. Assigning required values to a variable at the time of declaration before
processing is called initialization.
32
Principles of Programming using C – BPOPS203 Module 3

Example:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Col-0 Col-1 Col-2
int n[3][3]= {
{10, 10, 10}, Row-0 10 10 10
{20, 20, 20}, ----> Row-1 20 20 20
{30, 30, 30} Row-2 30 30 30
};

Example2: Col-0 Col-1 Col-2


int n[3][3]= { Row-0 10 0 0
{10},
Row -1 20 0 0
{20}, ---------->
{30} Row-2 30 0 0
};

Reading and Writing 2-D arrays

In general, to read 6 values, we can write:


for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d", &matrix[i][j]);
Similarly to display 6 elements stored in the matrix, we can write:
for(i=0;i<2;i++)
for(j=0;j<3;j++)
printf("%d ", matrix[i][j]);

Limitations of Arrays:

Although arrays provide an easy way to store multiple values of the same type together, they have
certain limitations.
The size of an array that you specify at the time of creation cannot be altered later. In other words,
you cannot add more elements to an array than specified in its size.
It is very difficult to insert an element between two existing elements. If you want to insert a new
element between two existing elements, you first need to make space for the new element by
moving all the existing elements up by one index.
Shortage of Memory, if we don't know the size of memory in advance.
Wastage of Memory, if array of large size is defined.

33
Principles of Programming using C – BPOPS203 Module 3

Advantages of Array:

1. It is used to represent multiple data items of same type by using only single name.
2. It can be used to implement other data structures like linked lists, stacks, queues,trees, graphs
etc.
3. 2D arrays are used to represent matrices.

2 D Array-Compile Time Initialization Example


#include<stdio.h>
void main()
{
int i, j;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
/*Printing 2D array*/
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}
}
}

2 D Array-Run Time Initialization Example


/* Read matrix with m rows and n columns*/
for(i=0;i<m;i++) // m-rows
for(j=0;j<n;j++) //n-colums
scanf(“%d”, &a[i][j]);

/*Write matrix */
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf(“%d”, a[i][j]);

Example 1:

Write a C program for addition of two matrices

34
Principles of Programming using C – BPOPS203 Module 3

#include<stdio.h>
#include <conio.h>
void main()
{
int a[5][5], b[5][5], c[5][5], i,j,m,n,p,q;
clrscr();

printf(“Enter the row size and column size of matrix A:\n”);


scanf(“%d %d”, &m,&n);

printf(“\n Enter the elements of matrix A:”);


for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &a[i][j]);

printf(“Enter the row size and column size of matrix B:\n”);


scanf(“%d %d”, &p,&q);

printf(“\n Enter the elements of matrix B:”);


for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf(“%d”, &b[i][j]);

for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf(“\n Sum of Matrices\n:”);
for(i=0;i<p;i++)
for(j=0;j<q;j++)
printf(“%d”, c[i][j]);
}

35
Example 2
Implement Matrix Multiplication and validate the rules of multiplication.

Program:
#include<stdio.h>
#include <stdlib.h>
int main()
{
int a[5][5], b[5][5], c[5][5], m,n,p,q,i,j,k;
printf("Enter the order of matrix A(m and n):");
scanf("%d %d", &m,&n);
printf("Enter the order of matrix B(p and q):");
scanf("%d %d", &p,&q);
/* Check compatibility of two matrices*/
if(n!=p)
{
printf("Matrix multiplication is not possible…Try again");
exit(0);
}
else
/* Read matrix A*/
printf("\n Enter the elements of matrix A(m * n):\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d", &a[i][j]);
/* Read matrix B*/
printf("\n Enter elements of matrix B(p * q):\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d", &b[i][j]);
/* Matrix multiplication*/
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]= c[i][j] +a[i][k]*b[k][j];
36
}
}
}
printf("The Matrix A is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t", a[i][j]);
printf("\n");
}
printf("The Matrix B is\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%d\t", b[i][j]);
printf("\n");
}
printf("The Resultant Matrix C is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t", c[i][j]);
printf("\n");
}
}
Output1:
Enter the order of matrix A(m and n): 2 4
Enter the order of matrix B(p and q): 2 2
Matrix multiplication is not possible…Try again

Output 2:
Enter the order of matrix A(m and n):2 3
Enter the order of matrix B(p and q):3 2
Enter the elements of matrix A(m * n):
1
2
3
4
5
6

37
Enter elements of matrix B(p * q):
1
2
3
4
5
6
The Matrix A is
1 2 3
4 5 6
The Matrix B is
1 2
3 4
5 6
The Resultant Matrix C is
22 28
49 64
Output 3:
Enter the order of matrix A(m and n):2 2
Enter the order of matrix B(p and q):2 2
Enter the elements of matrix A(m * n):
2
2
2
2
Enter elements of matrix B(p * q):
2
2
2
2

The Matrix A is
2 2
2 2
The Matrix B is
2 2
2 2
The Resultant Matrix C is
8 8
8 8
38
Principles of Programming using C – BPOPS203 MODULE 3

Example 3
Program to find transpose of matrix
#include<stdio.h>
void main()
{
int a [10] [10], t [10] [10];
int m,n,i,j;
printf("In Enter the order of matrix");
scanf ("'%d%d", &m, &n) ;
printf("In Enter the element of matrix one by one");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scant (“%d",&a[i][j]);
for(i=0;i‹m;i++)
for(j=0;j<n;j++)
t[[i][j]=a[j][i];
printf ("In Original Matrix In");
for(i=0;i<m;i++)
{
for (j=0; j<n; j++)
printf("%d\t", a[i][j]);
printf("\n");
printf("In Transpose Matrix In");
for(i=0:i<n:i++)
{
for(j=0;j<m;j++)
printf("%d\t",t[i][j]);
printtf ("\n");
}
}

Multi-Dimensional Arrays
C allows arrays of three or more dimensions. The exact limit is determined by compiler.
The general form of a muti-dimensional array is
data_typearray_name[s1][s2][s3]….[sm];
Where s, is the size of the ith dimension.
Some examples are: int survey[3][5][12]; float table[5][4][5][3];
Survey is a three-dimensional array declared to contain 180 integer type elements.
Table is a four-dimensional array containing 300 elements of floating-point type.
Operations on Arrays
1. Traversing an array
2. Inserting an element in an array
3. Deleting an element from an array
4. Merging two arrays
5. Searching an element in an array
6. Sorting an array in ascending or descending order

1. Traversing an array: Traversing an array means accessing each and every element of the array for
a specific purpose.
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int i, n, arr[20];
clrscr();
printf(“\n Enter the number of elements”);
scanf(“%d”, &n);
printf(“\n Enter the elements”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nThe array elements are”);
for(i=0;i<n;i++)
printf(“%d”,arr[i]);
}
2. Inserting an element in an array: Inserting an element in an array means adding a new data
element to an already existing array.
Program: Write a C program to insert a number at a given location in an array.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,num,pos,arr[10];
clrscr();
printf(“\n enter the number of elements in the array”);
scanf(“%d”,&n);
printf(“\nenter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nenter the number to be inserted”);
scanf(“%d”,&num);
printf(“\nEnter the position at which the number has to be added”);
scanf(“%d”,&pos);
for(i=n-1;i>=pos;i--)
arr[i+1]=arr[i];
arr[pos]=num;
n++;
printf(“\nthe array after insertion of %d is”,num);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]);
getch();
}
Program: Write a C program to insert a number in an array that is already sorted in ascending
order.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,num,j,arr[10];
clrscr();
printf(“\n enter the number of elements in the array”);
scanf(“%d”,&n);
printf(“\nenter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nenter the number to be inserted”);
scanf(“%d”,&num);
for(i=0;i<n;i++)
{
if(arr[i]>num)
{
for(j=n-1;j>=i;j++)
arr[j+1]=arr[j];
arr[i]=num;
break;
}
}
n++;
printf(“\nthe array after insertion of %d is”,num);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]);
getch();
}
3. Deleting an element from an array
Deleting an element from an array means removing a data element from an already existing array.
Program: Write a C program to delete a number from a given location in an array.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,pos,arr[10];
clrscr();
printf(“\n enter the number of elements in the array”);
scanf(“%d”,&n);
printf(“\nenter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nEnter the position at which the number has to be deleted”);
scanf(“%d”,&pos);
for(i=pos;i<n-1;i++)
arr[i]=arr[i+1];
n--;
printf(“\nthe array after deletion of is”);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]);
getch();
}
Program: Write a C program to delete a number from an array that is already sorted in ascending
order.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,num,j,arr[10];
clrscr();
printf(“\n enter the number of elements in the array”);
scanf(“%d”,&n);
printf(“\nenter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nenter the number to be inserted”);
scanf(“%d”,&num);
for(i=0;i<n;i++)
{
if(arr[i]==num)
{
for(j=i;j<n-1;j++)
arr[j]=arr[j+1];
}
}
n--;
printf(“\nthe array after deletion is”);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]);
getch();
}
4. Merging two arrays: Merging two arrays in a third array means first copying the contents of the
first array into the third array and then copying the contents of the second array into the third
array.
Program: Write a C program to merge two unsorted arrays.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n1,n2,m,arr1[10],arr2[10],arr3[10],index=0;
clrscr();
printf(“\n enter the number of elements in the first array”);
scanf(“%d”,&n1);
printf(“\nenter the values”);
for(i=0;i<n1;i++)
scanf(“%d”,&arr1[i]);
printf(“\n enter the number of elements in the second array”);
scanf(“%d”,&n2);
printf(“\nenter the values”);
for(i=0;i<n2;i++)
scanf(“%d”,&arr2[i]);
m=n1+n2;
for(i=0;i<n1;i++)
{
arr3[index]=arr1[i];
index++;
}
for(i=0;i<n2;i++)
{
{
arr3[index]=arr2[i];
index++;
}
printf(“\nthe array after merging is”);
for(i=0;i<m;i++)
printf(“%d\t”,arr3[i]);
getch();
}
5. SEARCHING
• The process of finding a particular item in the large amount of data is called searching.
• The element to be searched is called key element. There are two methods of searching:
1. Linear search (sequential search)
2. Binary search

1. Linear search
• Linear search is also called sequential search and is a simple searching technique.
• In this technique the key item is searched in the linear order i.e, one after the other
from first element to last element.
• The search may be successful or unsuccessful. If key item is present, the search is
successful, otherwise unsuccessful search.
Example 1:
Write C Program to implement Linear search
#include <stdio.h>
#include <conio.h>
void main()
{
int n,i,a[],key;
clrscr();
printf(“Enter the number of integers:\n”);
scanf(“%d”,&n);
printf(“Enter the %d items:\n”, n);
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);
printf(“Enter the key element to search:\n”);
scanf(“%d”, &key);
for(i=0;i<n;i++)
{
if(key == a[i])
{
printf(“\n Search Successful”);
exit(0);
}
}
printf(“\n Search Unsuccessful”);
getch();
}

Advantages of linear search:


• Very simple Approach.
• Works well for small arrays.
• Used to search when elements are not sorted.
Disadvantages of linear search:
• Less efficient if array size is large
• If the elements are already sorted, linear search is not efficient.
2. Binary Search
• Binary search is a simple and very efficient searching technique which can be applied if the
items are arranged in either ascending or descending order.
• In binary search first element is considered as low and last element is considered as high.
• Position of middle element is found by taking first and last element is as follows.
mid=(low+high)/2
• Mid element is compared with key element, if they are same, the search is successful.
• Otherwise, if key element is less than middle element then searching continues in left part
of the array.
• If key element is greater than middle element then searching continues in right part of the
array.
• The procedure is repeated till key item is found or key item is not found.
• Each time based on the comparison of searched element with the middle element, the area
to be searched is reduced.

Example 1:
/*Searching an element using Binary Search*/
#include <stdio.h>
#include<conio.h>
int main()
{
int i, n, begin, end, middle, key, pos=-1, found=0, a[20];
clrscr();
printf("Enter total number of elements in the array\n");
scanf("%d", &n);
printf("Enter elements in ascending order \n");
for (i = 0; i< n; i++)
scanf("%d", &a[i]);
printf("Enter the element to be searched\n");
scanf("%d", &key);
begin = 0;
end = n - 1;
while (begin <= end)
{
middle = (begin+end)/2;
if (a[middle] == key)
{
printf("The searched element %d is found at location %d\n", key, middle);
found=1;
break;
}
else if (a[middle] > key)
end = middle - 1;
else

}
begin = middle - 1;
if (begin > end && found==0)
printf("The searched element %d is not found in the array\n", key);
getch();
}

Output 1:
Enter total number of elements in the array
5
Enter elements in ascending order
10
20
30
40
50
Enter the element to be searched
10
The searched element 10 is found at location 1.

Output 2:
Enter total number of elements in the array
5
Enter elements in ascending order
10
20
30
40
50
Enter the element to be searched
55
The searched element 55 is not found in the array

Advantages of Binary search



• Simple technique
• Very efficient searching technique
Disadvantages of Binary Search
 The elements should be sorted.
• It is necessary to obtain the middle element, which are stored in array. If the elements are
stored in linked list, this method cannot be used.
6. SORTING
• The process of arranging elements in either ascending order or descending order is called
Sorting.
• Sorting is the process of arranging elements in the list according to their values, in ascending
or descending order.
• Sorted lists are especially important in list searching because they facilitate rapid search
operations.
• The three simple and most important among them are:
i. Bubble sort
ii. Selection sort
iii.Insertion sort

i. Bubble Sort
• This is the simplest and easiest sorting technique.
• In this technique two successive elements of an array such as a[i] and a[i+1] are compared.
• If a[i]>=a [i+1] then they are exchanged, this process repeats till all elements of an array are
arranged in ascending order.
• After each pass the largest element in the array is sinks at the bottom and the smallest
element in the array is bubble towards top. So this sorting technique is also called as sinking
sort and bubble sort.
Program: Write C program to input N integers in a single dimensional array and sort them in
ascending order using Bubble sort.

/* Sort the given set of N numbers using Bubble sort*/


#include<stdio.h>
#include<conio.h>
void main()
{
int num[25], n, i, j, temp;
clrscr();
printf(" Enter the total number of elements in the array\n");
scanf("%d",&n);
printf(" Enter the array elements one by one\n");
for(i = 0; i< n; i++)
{
scanf("%d",&num[i]);
}
printf("The given unsorted input array is\n");
for(i = 0; i< n; i++)
printf("num[%d]=%d \n", i,num[ i]);
for(i = 0; i< n; i++)
{
for(j = 0; j < (n-i-1); j++)
{
if( num[j] >num[j+1] )
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
printf("The sorted output array using Bubble Sort is\n");
for(i = 0; i< n; i++)
printf( "num[%d]=%d\n",i,num[i] );
getch();
}
Output:
Enter the total number of elements in the array 5
Enter the array elements one by one
89
-5
-25
10
45
The given unsorted input array is
num[0]=89
num[1]=-5
num[2]=-25
num[3]=10
num[4]=45
The sorted output array using Bubble Sort is
num[0]=-25
num[1]=-5
num[2]=10
num[3]=45
num[4]=89

ii. Selection Sort


In Selection sort, the smallest element is exchanged with the first element of the array. Then the
second smallest element is exchanged with the second element of the array and so on until all the
elements are sorted.
Example:

Program: Write C program to input N integers in a single dimensional array and sort them in
ascending order using Selection sort.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,j,t,n,min,loc;
clrscr();
printf(“Selection Sort\n”);
printf(“Enter total number of elements\n”);
scanf(“%d”, &n);
printf(“Enter the elements\n”);
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);

for(i=0;i<=n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<n;j++)
{
if(min>a[j])
{
min=a[j];
loc=j;
}
}
t=a[i];
a[i]=min;
a[loc]=t;
}
printf(“\n The sorted elements
are\n”); for(i=0;i<n;i++)
printf(“%d\n”, a[i]);
getch();
}

PASSING ARRAYS TO FUNCTIONS


a. Pass Individual Array Elements
Passing array elements to a function is similar to passing variables to a function.
i) Passing individual elements
#include <stdio.h>
void display(int age1, int age2)
{
printf("%d\n", age1);
printf("%d\n", age2);
}

int main()
{
int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}
ii) Passing Addresses
#include <stdio.h>
void func(int *num);
void main()
{
int arr[5]={1, 2, 3, 4 ,5};
func(&arr[3]);
}
void func(int *num)
{
printf(“%d”,*num);
}

b. Passing entire Array : To pass an entire array to a function, only the name of the array is passed
as an argument.

// Program to calculate the sum of array elements by passing to a function


#include <stdio.h>
float calculateSum(float num[]);
int main()
{
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[])
{
float sum = 0.0;
for (int i = 0; i < 6; i++)
{
sum += num[i];
}
return sum;
}
Pass Multidimensional Arrays to a Function
To pass multidimensional arrays to a function, only the name of the array is passed to the function
(similar to one-dimensional arrays).
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
scanf("%d", &num[i][j]);
}
}
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2])
{
printf("Displaying:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
printf("%d\n", num[i][j]);
}
}
}

You might also like