Unit 7
Unit 7
UNIT III
ARRAY INTRODUCTION
An array is a group of related data items that share a common name. The value is indicated by
writing a number called index number or subscript in brackets after the array name.
Example:
int salary[10];
PROPERTIES OF AN ARRAY
All the elements of an array share the same name and they are distinguished from one
another with the help of an element number.
The element number in an array plays major role for calling each element.
The type of an array is the data type of its elements.
The array elements are stored in continuous memory locations.
The location of an array is the location of its first element.
The length of an array is the no. of data elements in the array.
The size of an array is the length of the array times the size of an elements.
TYPES OF ARRAY
(i) One dimensional array
(ii) Two dimensional array
(iii) Multi dimensional array
Example:
int number[5];
INITIALIZATION OF ARRAYS
We can also initialize the elements of arrays like an ordinary variable initialization.
An array can be initialized in two way, they are
a) Compile time initialization.
b) Run time initialization.
Syntax:
datatype array-name[size] = {list of values};
Example:
int rollno[3] = {26,32,12};
We can use the word ‘static’ before type declaration. This declares the variable as a static
variable.
Example:
static int counter[] = {1,1,1};
for(i =0; i < 100; i = i+1)
U23CSTC01–Programming In C Regulation 2023
{
if (i < 50) sum[i] = 0.0; else
sum[i] = 1.0;
}
……….
……….
type variable-name[size];
static type array-name[size] = {list of values};
b) Run time Initialization
When the users have to initialize more number of elements means it is difficult to use
compile time initialization. To avoid this situation the user can initialize elements in run time.
Program
/*Program showing one-dimensional array*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],sum=0,i,n;
clrscr();
printf(“Enter no. of terms:”);
scanf(“%d”,&n);
printf("Enter %d integer numbers\n",n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("The sum of given numbers is : %d\n",sum);
getch();
}
U23CSTC01–Programming In C Regulation 2023
The entire sorting & searching algorithm must use the one-dimensional array.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i,n,large,small;
clrscr();
printf("Enter size of the array");
scanf("%d",&n);
printf("Enter elements in the array:");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
large=small=a[0];
for(i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("\nLarge element = %d",large);
printf("\nSmall element =%d",small);
getch();
}
Output
Enter size of the array: 10
Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10 Large element = 100
Small element = -10
U23CSTC01–Programming In C Regulation 2023
DECLARATION OF ARRAYS
Synatx:
type variable-name[size];
The type specifies the type of element, such as int, float, or char.
The size indicates the maximum number of elements that can be stored inside the
array.
Example:
float height[50];int
group[10]; char
name[10];
TWO-DIMENSIONAL ARRAYS
Arrays whose elements are specified by two subscripts are called Two-
dimensional arrays (or) double-subscripted arrays.
Syntax:
datatype array-name[row_size][column_size];
Example:
int a[3][3];
}
printf("Transpose Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d\t",a[j][i]);
}
printf(“\n”);
}
getch();
}
Output
Enter the First Matrix
123
2 3 4
5 8 7
Transpose Matrix
125
2 3 8
3 4 7
U23CSTC01–Programming In C Regulation 2023
}
printf("Enter the Second Matrix");
for(i=1;i<=3;i++)
for(j=1;j<=3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
U23CSTC01–Programming In C Regulation 2023
Output
Enter the First Matrix
1 2 3
2 1 2
3 1 1
Enter the second Matrix
1 2 3
2 1 2
3 1 1
Display Addition matrix
2 4 6
4 2 4
6 2 2
#include<stdio.h>
#include<conio.h>
void main( )
U23CSTC01–Programming In C Regulation 2023
{
int a[2][2], b[2][2],c[2][2],i,j;
int i,j,k;
clrscr();
printf("Enter first matrix:\n" );
for( i=1;i<=3;i++)
{
for( j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter second matrix:\n");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
c[i][j]=0; for(k=1;k<=3;k++)
{
c[i][j] =c[i][j]+a[i][k]*b[k][j];
}
}
U23CSTC01–Programming In C Regulation 2023
}
printf("Matrix Multiplication Is: \n");
for(i=1;i<=3;i++)
{
for (j=1;j<=3;j++)
{
printf("%d\n",c[i][j]);
}
}
getch();
}
Output
Enter the First Matrix
1 2 3
4 5 6
7 8 9
Enter the second Matrix
2 4 1
6 7 4
3 5 7
Matrix Multiplication
23 33 30
56 81 66
89 129 102
10 20
30 40
50 60
MULTIDIMENSIONAL ARRAY
C allows arrays of three or more dimensions. The exact limit is determined by the
compiler. The general form of a multidimensional array is
U23CSTC01–Programming In C Regulation 2023
Syntax:
datatype array_name[s1][s2][s3]…s[m];
Example:int s[3][5][12];
float t[5][4][5][3];
Advantages of arrays
It is capable of storing many elements at a time.
It allows random access of elements.
Disadvantages of arrays
The elements in the array must be same data type.
Predetermining the size of array is must.
Memory wastage will be there, if the array of large size is defined. To delete
an element of an array we need to traverse throughout array.
Employees[tables][rows][columns]);
}
}
}
return 0;
}
STRINGS
Introduction
The group of character, digits and symbols enclosed within quotation marks
are called as string; otherwise strings are array of characters. Null character (‘\0’)
is used to mark the end of the string.
Example:
char name[]={‘g’,’o’,’o’,’d’,’\0’};
Each character is stored in one byte of memory.
Example:
String G o o d \0
Address 1004 1005 1006 1007 1008
Example:
char city[10];
char name[30];
Reading Words
The familiar input function scanf() can be used with %s format specification to
read in a string of characters.
Example:
char address[15];
scanf(“%s”,address);
Program
/*Reading a series of words using scanf function*/
U23CSTC01–Programming In C Regulation 2023
#include<stdio.h>
#include<conio.h>
main()
{
char w1[40],w2[40],w3[40],w4[40];
clrscr();
printf(“Enter text:\n”);
scanf(“%s%s%s%s”,w1,w2,w3,w4); printf(“\n”);
printf(“word1 = %s \n word2 = %s \n”,w1, w2);
printf(“word3 = %s \n word4 = %s \n”,w3, w4);
getch();
}
Output
Enter text:
Hello How are you
word1=Hello
word2=How
word3=are
Note: scanf() function terminates its input on the first white space it finds.
Reading a Line of Text
It is not possible to use scanf function to read a line containing more than one
word.
This is because the scanf terminates reading as soon as a space is encountered
in the input.
We can use the getchar() function repeatedly to read single character from
the terminal, using the function getchar(). Thus an entire line of text can be read
and stored in an array.
We have used extensively the printf() function with %s format to print strings
to the screen. The format %s can be used to display an array of characters that is
terminated by the null character.
Example:
printf(“%s”, name);
U23CSTC01–Programming In C Regulation 2023
STRING FUNCTIONS
C library supports a large number of string-handling functions that can be used to carry outmany of the
string manipulation activities.
#include <stdio.h>
#include <string.h>
int main () {
SORTING
Arranging in an ordered sequence is called "sorting". Sorting is a common
operation in many applications, and efficient algorithms to perform it have been
developed.
Common sorting algorithms
Bubble/Shell sort: Exchange two adjacent elements if they are out of order.
Repeat until array is sorted.
Insertion sort: Scan successive elements for an out-of-order item, then insert
the item in the proper place.
Selection sort: Find the smallest (or biggest) element in the array, and put it
in the proper place. Swap it with the value in the first position. Repeat until array is
sorted.
Quick sort: Partition the array into two segments. In the first segment, all
elements are less than or equal to the pivot value. In the second segment, all
elements are greater than or equal to the pivot value. Finally, sort the two segments
recursively.
Merge sort: Divide the list of elements in two parts, sort the two parts
individually and then merge it.
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps
them if they are not in the intended order.
U23CSTC01–Programming In C Regulation 2023
Example:
#include<stdio.h>
void main()
{
int a[20], n, temp, i, j;
printf("Enter the number of terms: ");
scanf("%d",&n);
printf("Enter the elements of the array:");
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;
}
}
U23CSTC01–Programming In C Regulation 2023
}
printf("After Sorting:\n");
for(i=0; i<n; i++)
{
printf("%d\t", a[i]);
}
}
Output
After Sorting:
5 10 12 14 16
SEARCHING :
It check for an element or retrieve an element from any data structure where the data is
stored. Based on the type of search operation, there are generally two algorithms defined in C:
Linear Search or Sequential Search
Binary Search
Linear Search or Sequential Search - Find whether a value is exist in a given array. If it is
exist then return the current position. In this algorithm we check the value one by one in
given list.
Binary Search - Search in the given sorted elements. In this algorithm we divide sorted elements
frommiddle and check the lie between which part. Same process we try until the all element not
read.
U23CSTC01–Programming In C Regulation 2023
Example:
#include<stdio.h>
#inlcude<conio.h>
main()
{
int i,n,a[30],key,flag=100;
clrscr();
printf(“Enter the no. of terms:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“Enter the search element:”);
scanf(“%d”,&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf(“The searching element is %d present in location %d”,key,i);
flag=i;
}
}
U23CSTC01–Programming In C Regulation 2023
if(flag==i)
printf(“The searching element is not present”);
getch();
}
Output 1
Enter the no. of terms:5
10 12 14 16 18
Enter the search element:18
The searching element is 18 present in location 5
FUNCTIONS:
INTRODUCTION
The C language is allows the use of functions, self contained "modules"
of code that take inputs (raw data), do a computation, and produce a new piece of
information based on the parameter information.
“Function is a block of statement that is used to execute for a specific
task which repeatedly occurs in the main program. This is known as function”.
➢ To improve re-usability
Example for pre defined functions are sqrt(), pow(), tan() and etc…. Let see about
user defined function in details.
Example:
U23CSTC01–Programming In C Regulation 2023
#include<stdio.h>
int sum(int, int);/* Function prototype*/
void main()
{
int a,b,c;
printf(“\nEnter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);
c=sum(a,b); /* Function Call */ Actual arguments
printf(“\nAnswer is%d”,c); getch();
}
int sum(int x, int y) /* Called Function */
{ Formal arguments
int z; z=x+y;;
return(z); /* Return statement */
}
A function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division is such that each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to another
location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
U23CSTC01–Programming In C Regulation 2023
FUNCTION DEFINITION
Defining a Function
The general form of a function definition in C programming language is as follows −
return result;
}
FUNCTION DECLARATIONS
A function declaration tells the compiler about a function name and how to call the function. The
U23CSTC01–Programming In C Regulation 2023
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the
following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling
the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name,
and if the function returns a value, then you can store the returned value. For example −
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
U23CSTC01–Programming In C Regulation 2023
return result;
}
We have kept max() along with main() and compiled the source code. While running the final
executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
1 Call by value
This method copies the actual value of an argument into the formal parameter of the function.
In this case, changes made to the parameter inside the function have no effect on the
argument.
2 Call by reference
This method copies the address of an argument into the formal parameter. Inside the function,
the address is used to access the actual argument used in the call. This means that changes
made to the parameter affect the argument.
While calling a function, there are two ways in which arguments can be passed to a function −
U23CSTC01–Programming In C Regulation 2023
By default, C uses call by value to pass arguments. In general, it means the code within a function
cannot alter the arguments used to call the function.
PASS BY VALUE
Pass by value is a way to pass a variable to a function. The variable is passed by value, not
by reference. This means that the function does not have access to the variable’s memory address.
The function can only access the variable’s value.
In the case of pass by value, the space allocated for the variable is copied to the function’s
memory space. This means that the function can modify the variable’s value without affecting the
variable’s memory address.
/*
* C program to demonstrate pass by Value.
*/
#include <stdio.h>
void swap (int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main ()
{
int a = 10;
int b = 20;
printf ("Before swap, a = %d, b = %d\n", a, b);
swap (a, b);
printf ("After swap, a = %d, b = %d\n", a, b);
return 0;
}
Program Output
Before swap, a = 10, b = 20
After swap, a = 20, b = 10
U23CSTC01–Programming In C Regulation 2023
PASS BY REFERENCE
In pass by reference, we pass the address of the variable instead of passing the value
of the variable and access the variable using the pointers in the Function. All the changes
made to variable in the function will be reflected in the main Program
Program Output
Enter two numbers: 1 2
Numbers Before Swapping: 1 and 2
Numbers After Swapping: 2 and 1
U23CSTC01–Programming In C Regulation 2023
RECURSIVE FUNCTION
Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function; otherwise
it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600