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

Understanding Arrays in C Programming

The document provides an introduction to arrays in programming, explaining their definition, types, and importance in storing multiple values efficiently. It covers one-dimensional, two-dimensional, and multi-dimensional arrays, along with their declaration, initialization, and operations such as sorting and searching. Additionally, it illustrates how to use arrays with functions to perform calculations like average and square of elements.

Uploaded by

hshamajain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views43 pages

Understanding Arrays in C Programming

The document provides an introduction to arrays in programming, explaining their definition, types, and importance in storing multiple values efficiently. It covers one-dimensional, two-dimensional, and multi-dimensional arrays, along with their declaration, initialization, and operations such as sorting and searching. Additionally, it illustrates how to use arrays with functions to perform calculations like average and square of elements.

Uploaded by

hshamajain
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

MODULE 3

ARRAYS

INTRODUCTION : WHY DO WE NEED ARRAYS?


Say we have a problem in our hand to store marks scored by 50 students in C language subject. To store 50
marks we have to declare 50 variables of integer data type as shown below:
int marks_1, marks_2, marks_3, marks_4… ..................... marks_50;

Now suppose we have to store values into these variables then 50 scanf statements or initializing 50 values
has to be done as shown:
scanf(“%d”,
&marks_1);
scanf(“%d”,
&marks_2);
scanf(“%d”,
&marks_3);
………………..scanf(“%d”, &marks_50);
OR
marks_1=
25;
marks_2=23;
marks_3=20;
………….. so on marks_50=21;

marks_1 25 marks_2 23 marks_3 20

marks_4 15 So on………… marks_50 21

This style of programming is fine for a small set of values. But if we have to store 1000 or 10000 values
declaring so many variables is a cumbersome process. Alternative solution is Arrays!
3.1 DEFINITION OF ARRAYS
o The array is a fixed-size sequenced collection of elements of same data type.
o The array is a collection of homogeneous elements of same data type.
o Array groups the data items of similar types sharing the common name.
o Arrays are called as subscripted variables because; it is accessed using
subscripts/indexes.
Ex:
➢ 1. List of employees in an organization.
2. List of products and their cost sold by a store.
3. Test scores of a class of students.

➢ Here marks[0]=10, marks[1]=20, marks[2]=30 and marks[3]=40. This subscript/index


notation is borrowed from Mathematics where we have the practice of writing: marks4,
marks3, marks2 and so on.
➢ In C the array index starts with 0.
3.2 TYPES OF ARRAYS

I. One dimensional arrays/Single-Subscripted Variable


II. Two dimensional arrays/Double-Subscripted Variable
III. Multidimensional arrays

3.2.1 One-Dimensional Arrays: A list of items can be given one variable name using only
one subscript and such a variable is called a single subscripted variable or one dimensional
array.

Ex: int marks[4];


➢ Here marks is the name of the array which is capable of storing 4 integer values. The
first value will be stored in marks[0], the second value will be stored in marks[1] and so on
and the last value will be in marks[3].
Declaration of One-Dimensional Array: Here is general syntax for array declaration along
with examples.

Syntax
data_type array_name[size];
Examples : int marks[4];
Float temperature[5];

Note: Declaration and definition specify the data type of array,its name and size

Initialization of One-Dimensional Array: After array is declared, next is storing values in


to an array is called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization

1. Compile time initialization: If we assign values to the array during declaration it is


called compile time initialization. Following are the different methods of compile time
initialization.
a) Initialization with size
b) Initialization without size
c) Partial initialization
d) Initializing all values zero

a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
float temperature[5]={29.5, 30.7, 35.6, 45.7, 19.5};

b) Initialization without size: We needn’t have to specify the size of array provided we
are initializing the values in beginning itself.
Syntax: data_type array_name[ ]={list of values};
Examples: int marks[ ]={ 95,35, 67, 87};
float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};
c) Partial initialization: If we not specify the all the elements in the array, the
unspecified elements will be initialized to zero.
Example: int marks[5]={10,12,20};
Here, marks[3] and marks[4] will be initialized to zero.

d)Initializing all the elements zero: If we want to store zero to all the elements in the
array we can do.
Examples: int marks[4]={0};
float temperature[5]={0};

2. Run time initialization: Run time initialization is storing values in an array when
program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example:
printf(“Enter the marks”);
for(i=0; i<4; i++)
{
scanf(“ %d”, &marks[i]);
}
Note: Every iteration of for loop will help us to fill values into marks array (i.e.
marks[0]=95, marks[1]=35, marks[2]=67, marks[3]=87)

Accessing the array elements: Accessing the array element is done using a loop statement
in combination with printf statements or any other processing statements. Example of
accessing the array elements and calculating total marks is given below:
Example: void main( )
{
int total=0, marks[4]={35,44,55,67};
for(i=0; i<4; i++)
total=total+marks[i]; /* calculating total marks*/
printf(“Total marks=%d”,total);
}
Output: Total marks=201
USING ARRAYS WITH FUNCTIONS:
In large programs that use functions we can pass Arrays as parameters. Two ways of passing
arrays to functions are:
1. Pass individual elements of array as parameter
2. Pass complete array as parameter

Let us take an example program that uses a function square( ) to calculate square of numbers
stored in an array. In this program each array element is passed one by one.

Example-1 Example-1 cont’d:


int void square(int no )
square(int); {
void main( ) int sq;
{ sq=no*no; /*square is
int num[5], i; calculated*/
num[5] ={3,4, 8, 9, 10}; printf(“square is=%d ”, sq);
for(i=0; i<5; i++) }
{
square(num[i]);
}
} Output:
} Square is=9 16 64 81 100

This diagram clearly illustrates how each individual element of array num[ ] is passed to
function square through parameter no.

3 4 8 9 10
0 1 2 3 4 num[3]=9→ no

num[1]=4 copied → no

num[0]=3 copied to no
num[2]=8→ no

Next program illustrates how to pass an entire array to a function average () and calculate
average marks. First sum of all the elements of array marks
(i.e.35+65+75+95+85) is calculated and average is stored in a variable avg. value in avg
variable is returned to main( ) and stored in avg1

Example-2: Example-2 cont’d:


float average(int score[ ] )
float average(int {
score[]); void main( ) int i ,
{ sum=0; float
int marks[5], avg;
i float avg1; for(i=0; i<5;i++)
marks[5] ={35,65, 75, 95, {
85}; sum=sum+score[i];
avg1=average(marks); }
printf(“average=%f”, avg1) avg=sum/5
} ; return
(avg);
}

Output:
average=71.000000

In the above example each value of array marks[ ] is copied to array scores[ ] as shown
below:
marks[0]=35 copied to scores[0]

marks[1]=65 copied to scores[1]

marks[2]=75 copied to scores[2]

marks[3]=95 copied to scores[3]

marks[4]=85 copied to scores[4]

using these values average is calculated: (35+65+75+95+85)/5=


71.000000

3.2.2 Two-Dimensional Arrays: A list of items can be given one variable name using two
subscripts and such a variable is called a single subscripted variable or one dimensional
[Link] consists of both rows and columns. Ex: Matrix.
Declaration of Two-Dimensional Array: Here is general syntax for array declaration along
with examples.
Syntax : data_tye array_name[row_size][column_size];
Example: int marks[4][4];
Initialization of Two-Dimensional Array: After array is declared, next is storing values in
to an array is called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization

1. Compile time initialization: If we assign values to the array during declaration it is


called compile time initialization. Following are the different methods of compile time
initialization.
Syntax data_type array_name[size]={list of elements};

Example: int marks[2][4]={1,2,3,4,5,6,7,8};


float city_temp[2][2]={29.5,30.5,35.6,45.7};

2. Run time initialization: Run time initialization is storing values in an array when
program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example: printf(“Enter the marks”);
for(i=0; i<3; i++)
for(j=0;j<4;j++)
{
scanf(“ %d”, &marks[i][j]);
}

More Examples: Other way of initialization:


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

012 1234
a 345 b 5678

678 9 10 11 12
Example for Invalid initialization
int A[3][]={1,2,3,4,5}
Note: Never have column size undeclared in two dimension array.

3.2.3 Multi Dimensional Arrays:

• Multidimensional arrays can have three, four or more dimensions.


• A three-dimension array is an array of two dimensional arrays. It has row, column and
depth associated with it.

Declaring multidimensional arrays: Example


int table[3][5][4];

Here are two examples illustrating three-dimensional array declaration and


initialization
A[3][4][2]={
{
{ 1,2},
4 rows &
{3,4},
{5,6}, 2 columns
{7,8},

},

{ 3 depth
{ 8,9},
{10,11},
{12,13},
{14,15},
},
{
{ 8,9},
{10,11},
{12,13},
{14,15},
}
}
OPERATIONS PERFORMED ON ONE_DIMENSIONAL ARRAY
SORTING: It is the process of arranging elements in the list according to their values in
ascending or descending order. A sorted list is called an ordered list.
Ex: Bubble Sort, Selection Sort, Insertion Sort, Shell Sort, Merge Sort, Quick Sort.
Bubble Sort
Bubble sort will start by comparing the first element of the array with the second element, if
the first element is greater than the second element, it will swap both the elements, and then
move on to compare the second and the third element, and so on.

#include<stdio.h>
void main( )
{
int i,j,n,temp,a[100]; printf("Enter
the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
for(j=0;j<(n-i)-1;j++)
{
if( a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
{ printf("%d\n",a[i]);
}
}
Selection Sort
Selection sort will start by comparing the first element with other elements and finds
minimum element and swaps, then it starts comparing by taking second element with other
elements and so on.

void main( )
{
int a[100],i,j,n,temp,pos;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if( a[pos]>a[j])
Pos=j;
}
if(pos !=i )
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
SEARCHING: It is the process of finding the location of the specified element in a list.
➢ The specified element is often called the search key.
➢ If it is found search is successful, otherwise it is unsuccessful.
Ex: Binary Search, Linear Search, Sequential Search.

Linear Search

Linear search is a very basic and simple search algorithm. In Linear search, we search an
element or value in a given array by traversing the array from the starting, till the desired
element or value is found.

#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n, a[100], i, key,loc;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i]
{
loc=i+1;
break;
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);
else
printf("The search is unsuccessful\n");
}
Binary Search
Binary search works only on a sorted set of elements. To use binary search on a collection, the
collection must first be sorted. The array is divided into two parts. Compared with middle
element if it is not successful, then it is compared whether it is lesser or greater than middle
element. If it is lesser, search is done towards left part else right part.

#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n, a[100], i, key, loc, high, low, mid;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
loc = mid+1;
break;
}
else
{
if(ele<a[mid])
high=mid-1;
else
low=mid+1;
}
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);
else
printf("The search is unsuccessful\n");
}

3.3 Character Arrays and String Concepts


Definition: String is a variable length data stored in a character array.
Example: “hello”, “India”
I. C- strings
➢ In C a string is a data structure based on an array of char.
➢ A string is a sequence of elements of the char data type.
➢ There is no separate data-type called string in C language.
➢ As strings are variable-size data we have to represent them using character Arrays.
Example string is:

R A J E S H \0 Delimiter ‘\0’
indicates end
0 1 2 3 4 5 6 of string

Strings in C are classified into two types:


1. String literals
2. String variables

String literals are also known as string constants, is a sequence of characters enclosed by
double quotation marks is called string literals. A string literal is a constant its value cannot
be changed. Some examples are:
Examples: “New Delhi”, “I Love India” etc.

String variables are nothing but character array. Following syntax and examples illustrates
declaring string variables.
Example: char array_name[ ]= “raj”
How string is stored?
➢ A string, even a literal one is very similar to an array of characters.
➢ The only difference between array of char and string is that, a string must end with null
character (\0).
➢ If you use a literal string in a program, it is stored in consecutive bytes in memory and
compiler places the null character at the end.
➢ Below fig shows storage for literal string “CBIT”
C B I T \0

Declaring string variables: A string is declared like an array of characters.


Syntax: char string_name[size];
Ex: char name[21];
Size 21 means it can store up to 20 characters plus the null character. Entire storage location
name is divided in to 21 boxes called bytes, each of which holds one character. Each
character is element of data type char.

Initializing the string in the declaration


char first[10]={‘t’,’a’,’b’,’l’,’e’,’\0’};
char second[10]=”table”;
Difference between a single character string and a single character array is:
Single character array takes 1 byte whereas single character string occupies two bytes as
shown below:

A \0 Single character string

‘A’ 25

Limitations of Strings: One string variable cannot be directly assigned to another string as
in the case of ordinary scalar variables.
Let us say int a=10, b;
b=a; /* is perfectly valid */
But take an example of string initialization:
char name1[ ] = “hello”;
char name2[10 ];
name2=name1; /* This initialization is invalid */

But this initialization can be done using a loop and assigning individual characters of name1
to name2 as shown below:
void main( )
{
int char name1[ ]= “hello”;
int char name2[5];
for (int i=0; i<4;i++)
{
name2[i] =name1[i];
}
name2[i]= ‘\0’;
}

Printing and reading a string: Token oriented input/output function


Printing a string using printf: We can use printf function with %s format specifier to print
a string on to the monitor. The %s is used to display an array of characters that is terminated
by null character.
Example:
(1) char name[10]=”Andy”;
printf(“the name is
%s\n”,name);
o/p: the name is Andy

(2) char name[ ]= “ MANGALORE”;


printf(“%s”, name);
printf (“%9.6s”, name);
printf(“%-10.3s”, name);
M A N G A L O R E %s prints entire string

%9.6s prints first 6 characters out


M A N G A L
of 9 characters

Prints first 3 characters but in left


M A N justified manner because of (- )
sign

Reading a string using scanf( )


It uses string conversion specifier %s to accept a string data. Following example illustrates
it:
char name[20];
scanf(“%s”, name);
Note: while reading strings we needn’t specify address of operator (&) as the character array
itself is an address (i.e name itself is base address of array in the above example)

Disadvantage of reading strings using scanf( ) function is multiple words strings cannot be
read. For example say we have to read NEW DELHI, following scanf( ) reads only NEW and
stops.

scanf(“%s”, name);

say input is
N E W D E L H I

Only part of a string (NEW) is read and second half (DELHI) is ignored.

N E W

Edit set Conversion code %[ ]: In addition to %s we can also use edit set conversion code
%[ ], which specifies the type of characters that can be accepted by scanf ( ) function.

For Example say we have to accept only 0-9 digits in a string then edit set code can be used as
follows:
char name[20];
scanf(“%[0123456789]”, name)
Example strings that will be read by above statement are:
12345, 123, 567, 7890 etc.

NOTE: Suppose we want to skip particular set of characters in a string, then we have to use:
^ symbol in edit set conversion code. Following example illustrates same:
Example 1:
char name[20];
scanf(“%[^A-Z]”, name)

This function skips all Capital alphabets from a string.


Say string is APPLE, banana, Mango
Accepted words are: banana, ango
Example 2:
Char name[20];
Scanf(“%[^\n]”,name);

This function will read a line of characters including white space.

II. String manipulation function:

C library supports a large number of string handling functions that can be used to carry
out many of the string manipulations and are stored in header file “string.h”. Following are
the most commonly used string handling functions.
1. strcpy( ) copies one string over another
2. strlen( ) finds the length of a string
3. strcmp( ) compare two strings
4. strcat( ) concatenates two strings
5. strcpy( ) copies left most n characters of source to destination
6. strcmp( ) compares left most of n characters of source to destination.
1. strcpy( ): It is possible to assign a value to a string variable using strcpy( ). It allows
us to copy a string from one location to another. The string to be copied can be literal or
string variable.
The general form of call to strcpy is
strcpy(dest,source);
Strcpy() function has two parameters. The first is the dest, a string variable whose value is
going to be changed. The second is the source the string literal or variable which is going to
be copied to the destination.
Ex: char first[14];
char last[14];
strcpy(first,”ravi kumar”);
strcpy(last,first);
After two calls to strcpy, first and last each has a value “Ravi kumar”
A call to strcpy can be used to copy just part of a string. Either or both of the parameters can
refer to addresses past the beginning of their strings.
Ex: char name[20]=”Ravi kumar”;
char newname[20]=”Lee Davis”;
strcpy(name+5,newname+4);

name R A V I D A V I S \0

0 1 2 3 4 5 6 7 8 9 10 11 12 13

Strcpy does not check to see whether there is room for the resulting string at the specified
location. If there is no room, it copies characters on top of whatever variables follow in
memory. This may destroy the contents of other variables.

[Link]():the string length function can be used to find the length of the string in bytes. It
takes the form
length=strlen(str);
The parameter to strlen, str is a string. The return value length is an integer representing
current length of str in bytes excluding the null character.
Ex: str=”CBIT”
lenth=strlen(str); //4
str=’\0’
length=strlen(str); //0

[Link]( ): A strcmp() is used to compare two strings. It takes the two strings as a
parameter and returns an integer value based on the relationship between two strings.
General form of call to strcmp()

result=strcmp(first,second);

result>0 if first> second

result=0 if first==second

result<0 if first<second

Ex: int res;


res=strcmp(“cat”,”car”); //res>0
res=strcmp(“pot”,”pot”);//res==0
res=strcmp(“big”,”little”);//res<0

[Link]( ): often it is useful to concatenate or join two strings together. The strcat function
is used to join two strings together. The resulting string has only one null character at the
end.
General form of a call to strcat( )
strcat(first, second);

After the call, first contains all the characters from first, followed by the ones from second up
to and including the first null character in second.
Note: strcat stops copying when it finds a null character in the second string. If it doesn’t
find a null character, strcat continues copying bytes from memory until it finds null
character. The programmer must check to make sure that the resulting string fits in the
variable.
Ex: char dest[30]=”computer”;
char second[15]=” programming”;
strcat(dest,second); //computer programming

[Link]( ): The strncmp function compares up to specified number of characters from


the two string, starting at the address specified, and returns integer representing the
relationship between the compared string sections. It compares the character by
character until it finds a null character or characters that are different or until it has
compared number of characters.
General form of call to strncmp()
Result=(firstaddress, secondaddress, numchars);

Ex: char first[30]=”string”; char


second[10]=”stopper”; int n;
if(strncmp(first,second,4)==0) printf(“first
four characters are alike\n”); else
if(strncmp(first,second,4)<0)
printf(“first four characters of first string are less\n”); else
printf(“first four characters of first string are greater\n”);

[Link]( ): The strncpy function allows us to extract a substring from one string and
copy it to another location.
General form of call to strncpy

strncpy(dest, source, numchars);

The strncpy function takes three parameters. Here this statement copies the numchars of the
source string in to dest string. Since numchar does not include null character , we have to
place it explicitly in the source string.
Ex: char source[20]=”computer world”;
char dest[10];
strncpy(dest,source,3); //first three characters of source is copied into dest
dest[3]=’\0’; //we have to put null character at the end of dest string
printf(“%s”,dest); //com
Array of strings: Array of string is an array of one dimensional character array, which
consists of strings as its individual elements.
Declaration of array of strings: Char name[size1][size2];
Ex:
char days[7][10]={“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};

PROGRAMS
1. WACP 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.
Output the results compared with appropriate headings.
#include<stdio.h>
void main( )
{
int oddsum=0, evensum=0, i ,N, A[20];
float avg;
printf(“enter the size of an array\n”);
scanf(“%d”,&N)
printf(“Enter the array elements\n”);
for(i=0;i<N;i++)
{
scanf(“%d”, &A[i]); /* reading array values*/
}
for(i=0;i<N;i++)
{
if(A[i]%2==0);
{
evensum=evensum+A[i]; /* compute even sum */
}
else
{
oddsum=oddsum+A[i]; /* compute odd sum */
}
}
avg=(evensum+oddsum)/N;
printf(“even sum is = %d\n”, evensum);
printf(“odd sum is = %d\n”, oddsum);
printf(“Average of all is = %f\n”, avg);
}

2. Program to read and write the elements of one dimensional array


void main( )
{
int a[10],i,n;
printf(“enter the number of elements in an array\n”);
scanf(“%d”,&n)
printf(“enter the elements of an array\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“the elements of an array are\n”);
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
}

3. Program to read and write the elements of two dimensional arrays


#include<stdio.h>
void main()
{
int a[10][10],i,j,m,n;
printf(“enter the size1 and size2 of 2 dimensional array\n”); scanf(“%d”,&m,&n)
printf(“enter the elements of an array\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“the elements of 2 dimensional array are\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf(“%d”,a[i][j]);
printf(“\n”);
}
}
4. Program to count number of odd numbers and even numbers in an array:
void main( )
{
int odd_count=0, even_count=0, i , num[10];
printf(“Enter the array elements\n”);
for(i=0;i<10;i++)
{
scanf(“%d”, &num[i]); /* reading array values*/
}
for(i=0;i<10;i++)
{
rem=num[i]%2;
if(rem==0)
{
even_count++; /* increase even counter by1 */
}
else
{
odd_count++; /* increase odd counter by1 */
}
}
printf(“odd count is = %d\n”, odd_count);
printf(“even count is = %d\n”, even_count);
}

5. C program to find largest element in the two dimensional array.

#include<stdio.h>
void main()
{
int m,n,a[5][5],i,j,large;
printf("enter the size1 and size2 of 2D array\n");
scanf("%d%d",&m,&n);
printf("enter the elements of 2d array\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d"&a[i][j]);
large=a[0][0];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
if(a[i][j]>large)
large=a[i][j];
}
printf("large=%d",large);
}

6. Write a C program to concatenate two strings without using build in function


strcat.
void main()
{
char str1[50],str2[25];
int i=0,j=0;
printf("enter the string1\n");
gets(str1);
printf("enter the string2\n");
gets(str2); while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
i++;
j++;
}
str1[i]='\0' ;
printf("concatanation of string is %s",str1);
}
7. Implement string copy operation STRCOPY(str1,str2) that copies a string
str1 to another string str2 without using library function.

#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100],s2[100];
int i;
printf("\nEnter the string1 :");
gets(s1);
i=0;
while(s1[i]!='\0')
{
S2[i]=s1[i];
i++;
}
s2[i]='\0';
printf("\nString2 value is %s ",s2);
}
User defined functions and Recursion
A function is a block of code to perform a specific task.
>- Every C program has at least one function main(). Without main ( ) function, there is
technically no C program.
>- In modular programming, the program is divided into separate s m a l l programs c a ll ed
modules. Each module is designed to perform specific function. Modules make our
actual program shorter, hence easier to read and understand.

Advantages of functions:
Reusability: Particular set of instructions can be used repeatedly from
several different places within the program .
Easy debugging: since each function is smaller and has a logical clarity, it is easy to
locate and correct errors in it.
Build library: Functions allows a programmer to build a customized library of
frequently u sed routines or system-dependent features. Each routine can be
programmed as a separate function and stored within a special library file.

TYPES OF C FUNCTIONS:
There are 2 types of functions in C programming:
1. Library function
2. User defined function

Library Function
Library functions are the in-built function in C compiler.
For example:
main( )//The execution of every C program starts from this main() function
printf( ) //prinf() is used for displaying output in C
sqrt(x);// finds the square root of x
scanf( ) //scanf() is used for taking input in C

User Defined Function


C allows programmer to define their own function according to their requirement.
These types of functions are known as u ser-defined functions.

ADVANTAGE S OF USER DEFINED FUN CTIONS:


1. User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and debug.
2. If repeated code occurs in a program . Function can be used to include those codes
and execute when needed by calling that function.
3. Programmer working on large project can divide the workload by making different
functions.
FUNCTIONS AND PROGRAM STRUCTURE
Basic structure of C program with function is shown below:
#include <stdio.h>
global declarations; //function declarationor
void function_name( parameter list); functionprototype
void main()
{

local declarations ;
statements;
function_name(parameter list); II functioncall
• • • • • • • • • • •

• • • • • • • • • • •

void function_name(parameter list ) //function definition


{
local declarations ;
statements;
}

▪ Every C program begins from main() and program starts executing the codes inside main( )
function.
▪ When the control of program reaches to function_name() inside main( ) function, the control
of program jumps to void function_name( ) and executes the codes inside it.
▪ When all the codes inside that user-defined function are executed, control of the program
jumps to the statement just after function_name( ) from where it is called.

Function Declaration
Every function in C program should be declared before they are used.
Function declaration gives compiler information about
function name
type of arguments to be passed
and return type
The syntax is shown below:

Function Call
A function can be called by specifying its name followed by a list of arguments enclosed in
the parentheses and separated by commas.
The syntax is shown below:

Function Definition
Function definition contains programming codes to perform specific
task. The syntax is shown below:

Where:
return_type is the data type that the function returns.
F unction- name refers to the name of the function.

The formal par ameters are a comma separated list of variables that receive the
values from the main program when a function is called.
The return statement returns the result of the function.

Return Type

Function Name

Local D eclarati on
int sum ( int a , int b )
Parameter Lis t
{
(Formal Parameters)
'---- int c ;
-- c = a + b ;
return ( c ) ;
\
J

Return Statement
Statements

ACTUAL AND FORMAL parameters/ arguments.


• Argument (or parameter) refers to data that is passed to function (function definition)
while calling function.
• Arguments listed in ''function call '' statements are referred to as actual arguments.
These actual values are passed to a function to compute a value or to perform a task.
• The arguments used in the ''function declaration '' are referred as formal arguments. They
are simply formal variables that accept or receive the values supplied by the calling
function.
• The number of actual and formal arguments and their data types should be same.

Example:
Program to add two integers. Make a function add integers and display sum in main ( ) function .
#include <stdio.h>
Int add(int , int); // function prototype
void main()
{

int a,b,sum;
printf("Enters two number to add \n");
scanf("%d %d", &a,&b);
sum=add(a ,b); //actual arguments
printf(\n sum=%d", sum);
}

int add(int a,int b ) //formal arguments


{

int sum; I I localdeclaration


sum=a+b;
return sum;
}

Output :
Enters two number to add 2 3
sum=5
Location of functions.
Locations of functions suggest the placement of function definitions with respect to main()
program. There are three alternatives to specify the location for function

Alternative 1 .
In this type the function definition are placed before the main() program bod y. In this case
defining or declaring function prototype can be omitted.
It is considered poor style to omit function prototype, even if it is not technically necessary.

Alternative2
In this type the function definition are placed after the main( ) program.
Here one has to place the function prototype statement well before main( ) program
appearance in order to assists C compiler for type checking and function call location with
respect to function definition.
Alternative 3
Here the function body is placed in one file and the main() program with function
protot ype in another file. In the file say add.h the following function will be defined
ARRAYS AND FUNCTIONS
The arrays can be passed to functions using two methods:
1. Passing Individual Elements of Array
All array-elements can be passed as individual elements to a function like any other
variable.
The array-element is passed as a value parameter i.e. any change in the formal-
parameter will not affect the actual-parameter i.e., array-element .
Example: Program to illustrate passing individual elements of an array to a function.
#incude<stdio.h>
void display(int a)
{
printf("%d", a);
}

void main()
{

int c[3]={2,3,4};
display(c[2]);
}

Output:
4
Passing the Whole Array
Here, the parameter passing is similar to pass by reference.
In pass by reference, the formal parameters are treated as aliases for actual
parameters.
So, any changes in formal parameter imply there is a change in actual parameter.
Example: Program to find average of 6 marks using pass by reference.
#include <stdio.h>
void average(int m[])
{

int i ,avg;
int avg, sum=0;
for(i=0;i<6;i++)
sum= sum+ m[i];
avg =(sum/6);
printf(“aggregate marks= %d ", avg);
}

void main()
{

int m[6]={60, 50, 70, 80, 40, 80, 70};


average(m); // here m is the base address .
}

Output:
aggregate marks= 70

CLASSIFICATION OF USER-DEFINED FUNCTIONS


1. Function with no arguments and no return value (void and parameter less functions)
2. Function with no arguments and return valu e
3. Function with arguments but no return value
4. Function with arguments and return value

1. Function with no arguments and no return value (void and parameter less functions):
▪ This type of functions will not have any parameter and they will not return any value
to the calling functions.
▪ There is no data transfer between the calling function and called function. So calling
function cannot send values and hence called function cannot receive the data.
Example: Program to illustrate function with no arguments and no return value.
#include <stdio.h>
void add();
void main()
{
add();
}
void add()
{
int a, b, sum;
printf( "Enters two number to add : ");
scanf( "%d %d", &a, &b);
sum=a+b;
printf("\n sum=%d", sum);
}

Output:
Enters two number to add: 2 3
sum=5

2. Function with no arguments and with return value:


In this category there is no data transfer from the calling function to the called
function. But there is a data transfer from called function to the calling function.
When the function definition returns a value the calling function receives one
value from the called function.
Example: Program to illustrate function with no arguments and return value.
#include <stdio.h>
int add( );
void main()
{

int sum; sum=add();


printf("\n sum=%d", sum);
}

int add()
{

int a, b, sum;
printf("Enters two number to add \n");
scanf( "%d %d", &a, &b);
sum=a+b;
return sum;
}

Output:
Enters two number to add 2 3
sum=5
3. Function with arguments but no return value:
Here there is a data transfer from the calling function to called function.
But there is no data transfer from the called function to the calling function. The
called function will have parameters but no return type.
Example: Program to illustrate function with arguments but no return value
#include <stdio.h>
void add(int a, int b);
void main()
{
int a, b;
printf("Enters two number to add \n");
scanf("%d %d", &a, &b);
add(a, b);
}
void add(int a, int b)
{

int sum= a+ b ;
printf(\n sum=%d", sum);
}

Output:
Enters two number to add 2 3
sum=5

4. Function with arguments and return value:


• In this category there is a data transfer between the calling function and called function.
• When parameters are passed, the called function can receive values from the calling
function. When the function returns a value the calling function can receive a value
from the called function.
Example: Program to illustrate function with arguments and return value
#include <stdio.h>
int add(int a, int b) ;
void main()
{
int a, b, sum;
printf("Enters two number to add \n");
scanf("%d %d", &a, &b);
sum=add(a ,b);
printf("\n sum=%d", sum);
}
int add(int a, int b)
{
int sum;
sum=a+b;
return sum; //return statement of function
}
Output:
Enters two number to add 2 3
sum=5
RECURSION
A function that calls itself is known as recursive function.
The rule to be followed for recursive function is that
➔ Establish boundar y conditions that terminate the recursive c a l l s .
➔ Implement the recursive calls so that each call brings one step closer to the solution.
Every recursive function must be provided with a way to end the recursion. In
this example when, n is equal to 0, there is no recursive call and recursion ends.
Example: Program to find factorial of a number using recursion.
#include<stdio.h>
int fact(int n)
{

If(n==1)
return 1;
return (n*fact(n-1);
}
void main()
{

int n,res;
printf(Enter the va1ue of n \n");
scanf("%d", &n);
res=fact(n);
printf( result = % d",res);
}

Output:
Enter a positive integer: 5 Result = 120
The recursion refers to the process where a function calls itself either directly or
indirectly. There are two types of recursion:
1: Direct recursion
2: Indirect recursion

Direct Recursion:
It refers to a process where function calls itself directly as illustrated in the figure below.

Indirect recursion:
It refers to a process where a function calls another function and that function calls back
the original function. The process of indirect recursion takes place as illustrated below.
Figure: Indirect recursion Here the func l() calls func2() and func2() calls func3() and func3()
calls func1().
Example: Program to generate Fibonacci series using recursion
#include <stdio.h>
int fibonacci(int);
void main()
{

int n, i = 0, c;
printf("\n Enter the number of terms :");
scanf("%d", &n);
printf("fibonacci series is :\n");
for(c=1 ; c<= n;c++ )
{

Printf(“%d\t”,fibonacci( c));

i++;
}
}
int fibonacci(int n)
{
If(n==0||n==1)
return n ;
else
return (fibonacci(n-1) + fibonacci(n-2));
}

Declaration of Storage Class


▪ Variables in C also declared as Storage class which provides information about their
location and visibility.
▪ The storage class determines the part of the memory where the variable would be
stored.
▪ The storage class also determines the initial value of the variable and it used to define the
scope and lifetime of variable. There are four types of scope in c:
1. Block scope.
2. Function scope.
3. File scope.
4. Program scope
There are two storage location in computer: CPU Registers and M emory

Scope Rules
Scope
The region of a program in which a variable is available for use
Visibility
The program's ability to access a variable from the memory
Lifetime
The lifetime of a variable is the duration of time in which a variable exists in the memory
during execution
Rules of use
1. The scope of a global variable is the entire program file
2. The scope of a local variable begins at point of declaration and ends at the end of
the block or function in which it is declared
3. The scope of a formal function argument is its own function
4. The lifetime (or longevity) of an auto variable declared in main is the entire
program execution time, although its scope is only the main function
5. The Ife of an auto variable declared in a function ends when the function is exited
6. A static local variable, although its scope is limited to its function, its lifetime extends till
the end of program execution.
7. All variables have visibility in their scope, provided they are not declared again
8. If a variable is redeclared within its scope again, it loses its visibility in the scope of the
redeclared variable
C provides variety of storage class specifiers that can be used to declare explicitly the scope
and lifetime of variables.
Syntax:

Where:
➔ Storage_class is any class i.e auto, static, extern and register.
➔ Data_type refers to the existing data type.
➔ identifier is the variable name.

auto
Storage: memory.
Default initial value: garbage value.
Scope: local to the block in which the variable is defined.
Life: till the control remains within the block in which the variable is defined.
A program to illustrate the use of auto.
#include<stdio.h>
void main()
{
auto int i=1 ;
{
auto int i=2;
{
auto int i=3;
printf(“\n%d”,i);
}
printf(“\n%d”,i);
}
printf(“\n%d”,i);
}

Output:
3 2 1

register
>- Storage: CPU R e g i s t e r .
>-
Default initial value: garbage value.
Scope: local to the block in which the variable is defined.
>- Life: till the control remains within the block in which the variable is defined.
A program to illustrate the use of register.
#include<stdio.h > void main()
{
register int i;
for(i=1;i<=10;i++)
printf(”%d",i);
}
Output:
1 2 3 4 5 6 7 8 9 10

Note:
1. If the microprocessor has 16-bit registers then they cannot hold a float value or a
double value which requires 4bytes(32-bit) and 8 bytes(64-bit)
2. If you want to use the register storage class (16-bit microprocessor) with float and
double variable then you won't get any error messages. Your compiler would treat the
variables as auto storage class.

static
>- Storage: memory.
>- Default initial value: zero.
>- Scope: local to the block in which the variable is defined.
>- Life: value of the variable persists between different function calls.
>- The different b/w two programs 1st auto and 2nd static storage class for variable 'i'
the scope of auto and static both use local to the block in which the variable is
declared.
>- Those program consists two functions main ( ) and increment ( ).
>- The increment ( ) function called from main ( ) function for three times.
>- Each time increment the v alue of 'i' and print.
>- When variable 'i' is auto each time increment and re-initialized to 1.

A program example to differentiate between auto and static class specifiers.

Automatic Static

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


increment (); increment() ;
void main() void main()
{ {
increment () ; increment ();
increment () increment ();
; increment () increment ();
;

} }
increment () increment()
{ {
auto int i= 1; static int i= 1;
pr intf ("%d\t ",i); pr intf ("%d\t ",i);
i++ ; i++·,

} }
Output Output:
:1 11 1 2 3
A program example to illustrate the use of global variable.
#include<stdio.h>
int i =1;
void increment();
void main()
{
printf("%d\t",i);
increment();
increment( );
}
void increment()
{

i++;
printf("%d\t",i);
}
Output:
123

extern
Storage: memory.
Default initial value: zero.
Scope: global.
Life: as long as the program's execution doesn't come to an end.
The extern keyword is used before a variable to inform the compiler that this variable
is declared somewhere else. The extern declaration does not allocate storage for
variables.

file1.c file2.c

# i nclude<stdio.h > #i nclud e ''f i l e1.c" ;


int a = 7 ; - ma in()
voi d f un () {
{ extern int a;
pr i ntf (“%d”,a) ; fu n() ;
}
•• •• ••

•• •• •• •
}

gl obal va riabl e from one f i le can be used in other usi ng extern keyword.
A Program example to illustrate the use of extern.

File l .c
File2.c
#include<st dio.h>
int i = 1·
' #include<stdio.h>
void increment () ; #include ''Filel.c''
void main()
{ void increment ()
printf ("%d\t",i) ; {
extern int i;
increment (); printf ("%d\t",++i) ;
increment () ; }

123

Program examples:
/* Program to convert Binary to decimal using recursion */
#include <stdio.h>
int BinToDec(int num) ;
void main ()
{
long binarynum,decimalnum;
printf("Enter a binary number : ");
scanf ("%ld ", &binarynum);
decimalnum=BinToDec(binarynum);
printf ("Equivalent decimal number of %d is %d”,binarynum,decimalnum);
}
/*recursive function to convert binary to decimal*/
int BinToDec(int num)
{
if (! ( num/10)) return (num);
return (num % 10 + BinToDec (num/10) * 2);
}
Question Bank
1. Explain function definition, function call and function declaration with example
2. Define recursion. Explain recursion with an example.
3. What is function? Write a C program to find cube of a number using function.
4. Explain with an example the variations of functions.
5. How arrays are passed as parameter to function. Explain with program example.
6. Write recursive program to generate Fibonacci series. Explain
7. Write a recursive program to find the factorial of number. Explain
8. Write recursive program to convert Binary number to decimal number. Explain
9. Write a program to compare, concatenate and find the l e n g t h of the string using
functions.
10. Write program to find whether given number is prime number or not using functions.
11. List the difference between formal and actual parameters with example.
12. Explain the storage class specifiers with example.
13. What is scope of variable? List the rules for scope of variable.

You might also like