Ip (Unit-2) - Vit
Ip (Unit-2) - Vit
Array: An array in C is a fixed-size collection of homogeneous data items i.e., similar data
items stored in contiguous memory locations. It can be used to store the collection of
primitive data types such as int, char, float, etc., and also derived and user-defined data types
such as pointers, structures, etc.
Array Declaration: We can declare an array by specifying its name, type of its
elements, and the size of its dimensions. When we declare an array in C, the compiler
allocates the memory block of the specified size to the array name.
Syntax of Array Declaration:
data_type array_name [size];
or
float arr[5]; --> declares 'arr' as an array to contain maximum 5 float numbers.
In 'C' arrays are static in nature, i.e., memory is allocated at the compile time.
Array Initialization: It is the process to assign some initial value to the variable.
When array is declared or allocated memory, the elements of the array contain some
garbage value. So, we need to initialize the array to some meaningful value. There are
multiple ways in which we can initialize an array in C.
1. Array Initialization with Declaration: In this method, we initialize the array along
with its declaration. We use an initializer list to initialize multiple elements of the array. An
initializer list is the list of values enclosed within braces { } separated by a comma.
Syntax:
data_type array_name [size] = {value1, value2, ... valueN};
The size of the above arrays is 5 which is automatically deduced by the compiler.
3. Array Initialization after Declaration (Using Loops):
We initialize the array after the declaration by assigning the initial value to each element
individually. We can use for loop, while loop, or do-while loop to assign the value to each element
of the array.
Syntax: int a[N];
for (int i = 0; i < N; i++) {
array_name[i] = value i;
}
int a[5];
Example: for(int i=0;i<5;i++) {
Scanf(“%d”,&a[i]);
}
Accessing Array Elements: We can access any element of an array by using the
array name and the index number of the element.
array_name [index];
note : indexing in the array always starts with 0, i.e., the first element is at index 0 and the
last element is at N – 1 where N is the number of elements in the array.
1. Fixed Size of an Array: In C, the size of an array is fixed after its declaration. It
should be known
at the compile time and it cannot be modified later in the program.
2. Homogeneous Collection: An array in C cannot have elements of different data types. All the
elements are of the same type.
3. Indexing in an Array: Indexing of elements in an Array starts with 0 instead of 1. It means
that the index of the first element will be 0 and the last element will be (size – 1) where size is
the size of the array.
4. Dimensions of the Array: An array C can be a single dimensional like 1-D array or
multidimensional like a 2-D array, 3-D array, and so on.
5. Contiguous Storage: All the elements in an array are stored at contiguous or consecutive
memory locations. We can verify this property by using pointers.
6. Random Access to the Elements: we can randomly access any element in the array without
touching any other element by using Arrayname with index number.
7. Relationship between Array and Pointers: Arrays are closely related to pointers in the
sense that we can do almost all the operations possible on an array using pointers. The array’s
name itself is the pointer to its first element.
8. Bound Checking: Bound checking is the process in which it is checked whether the
referenced element is present within the declared range of the Array. In C language, array
bound checking is not performed so we can refer to the elements outside the declared range
of the array leading to unexpected errors.
Disadvantages of Array:
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the
limit.
Array Manipulation:
Array manipulation refers to the process of modifying or transforming arrays, which are
fundamental data structures used to store collections of elements. These manipulations can
involve various operations to achieve specific outcomes, such as:
Adding or Removing Elements:
This includes operations like appending elements to the end, inserting elements at specific
positions, or removing elements from the beginning, end, or specific indices.
Modifying Elements:
Changing the value of existing elements at a given index.
Reordering Elements:
Operations like sorting the array in ascending or descending order, reversing the order of
elements, or rotating elements by a certain number of positions.
Searching and Filtering:
Finding specific elements within the array, or creating new arrays containing only elements
that meet certain criteria.
Combining or Splitting Arrays:
Merging multiple arrays into a single one, or dividing a single array into smaller arrays.
Transforming Elements:
Applying a function or operation to each element in the array to create a new array with
transformed values.
Operations on Array?
Operation on Array: Following are the various operations supported by an array.
1) Traversing
2) Insertion
3) Deletion update
4) Sorting
5) Searching
6) Copying
7) Reversing
8) Merging
1) Traverse: In traversing operation of an array, each element of an array is accessed exactly
once for processing. This is also called visiting of an array.
2) Insertion: Insert operation is to insert one or more data elements into an array. Based on
the requirement, new element can be added at the beginning, end or any given index of array.
3) Deletion: Deletion refers to removing an existing element from the array and re-
organizing all elements of an array.
4) Update: We can update new element in the place of existing element of an array.
5) Sorting: Using Sorting operation we can arrange the unsorted elements in array with
ascending or descending order.
6) Searching: You can perform a search for array element based on its value or its index.
7) Copying: we can copy one array of elements to another array. For this the source and
destination array’s size and type must be same.
8) Reversing: we can access array elements in the reverse order by using last index number
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
(or)
int a[2][4];
a[0][0]=1; a[0][1]=2; a[0][2]=3; a[0][3]=4;
a[1][0]=5; a[1][1]=6; a[1][2]=7; a[1][3]=8;
Example: Program for initialization of Double Dimensional array and access the values
#include<stdio.h>
int main() { OUTPUT:
int i, j;
int a[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}}; Matrix is
printf(“Matrix is\n”); 1 2 3
for( i=0; i<3; i++ ) { 4 5 6
for(j=0; j<3; j++) { 7 8 9
printf("%3d",a[i][j]);
}
printf("\n");
}
return 0;
}
Example: Program to read matrix row, column sizes and read the matrix values and display the matrix
#include<stdio.h>
int main() {
int i, j, rows, cols, a[5][5];
printf("Enter the matrix row, col sizes :");
scanf(“%d%d”,&rows,&cols);
printf("Enter a[%d][%d] matrix values :\n",rows, cols);
for( i=0; i<rows; i++ ) {
for( j=0; j<cols; j++ ) { OUTPUT:
scanf("%d",&a[i][j]);
} Enter the matrix row, col sizes : 2
} 3
printf("The Matrix is….. \n"); Enter a[2][3] matrix values :
for( i=0; i<rows; i++ ) { 4
for( j=0; j<cols; j++ ) { 56
printf("%3d",a[i][j]); 58
} 74
printf("\n"); 89
} 23
return 0; The Matrix is…..
} 4 56 58
74 89 23
3)Multi Dimensional Array: It is a collection of double dimension arrays. Each double dimension array is
identified with ‘i’ each array is identified by ‘j’ and each value is identified with ‘k’.
Declaration of Multi Dimensional Array:
};
#include<stdio.h>
int main() {
int i, j, k;
int a[2][3][3] = {{1,2,3}, {4,5,6}, {7,8,9},{1,2,3}, {4,5,6}, {7,8,9}};
printf(“Matrix is\n”);
for( i=0; i<2; i++ ) {
for(j=0; j<3; j++) {
for(k=0; k<3; k++ ) {
printf(“%3d”,a[i][j][k]);
}
printf(“\n”);
}
printf(“\n\n”);
}
return 0;
}
PROGRAMS ON ARRAYS
1. Write a C program to find the min and max of a 1-D integer Array
#include <stdio.h>
OUTPUT:
#define MAX_SIZE 100
int main() {
Enter size of the array: 10
int arr[MAX_SIZE];
Enter elements in the array: 46
int i, max, min, size;
12
printf("Enter size of the array: ");
23
scanf("%d", &size);
36
printf("Enter elements in the array: ");
456
for(i=0; i<size; i++) {
365
scanf("%d", &arr[i]);
89
}
65
max = arr[0];
10
min = arr[0];
87
for(i=0; i<size; i++) {
if(arr[i] > max) {
Maximum element = 456
max = arr[i];
Minimum element = 10
}
if(arr[i] < min) {
min = arr[i];
} }
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
return 0; }
Algorithm: Linear_Search
for i = 0 to last index of A: OUTPUT:
if A[i] equals key:
Enter number of elements in array : 6
return i
Enter 6 integers
#include <stdio.h> 23
int main() { 14
int array[100], search, i, n; 58
printf("Enter number of elements in array :"); 94
scanf("%d",&n); 76
printf("Enter %d integers\n", n); 35
for(i=0;i<n;i++)
scanf("%d", &array[i]); Enter a number to search : 94
printf("Enter a number to search : "); 94 is present at location 4.
scanf("%d", &search);
for (i=0;i<n;i++) {
if(array[i]==search) {
printf("%d is present at location %d.\n", search, i+1);
break;
}
}
if(i==n)
printf("%d is not present in the array.\n", search);
return 0;
}
}
printf("\n");
}
printf("\n\n");
printf("Second Matrix is: \n");
for (i = 0; i < m; i++) {
for (j = 0 ;j < n; j++) {
printf("%d ", second[i][j]);
}
printf("\n");
}
printf("\n\n");
printf("Sum of Two matrices is:-\n");
for (i = 0; i < m; i++) {
for (j = 0 ;j < n; j++) {
sum[i][j] = first[i][j] + second[i][j];
printf("%d\t", sum[i][j]);
}
printf("\n");
}
return 0; }
6. Write a C program for Multiplication of Two Matrices of size 3 x 3
#include<stdio.h>
int main() { OUTPUT:
int a[3][3], b[3][3], c[3][3], i,j,k;
enter first matrix elements:
printf("enter first matrix elements:\n");
1
for(i=0;i<3;i++) {
2
for(j=0;j<3;j++) {
3
scanf("%d",&a[i][j]);
} 4
} 5
printf("enter second matrix elements:\n"); 6
for(i=0;i<3;i++) { 7
for(j=0;j<3;j++) { 8
scanf("%d",&b[i][j]); 9
} enter second matrix elements:
} 9
printf("First Matrix is: \n"); 8
for (i = 0; i < 3; i++) { 7
for (j = 0 ;j < 3; j++) { 6
printf("%d ", a[i][j]); 5
} 4
printf("\n"); 3
} 2
printf("\n\n"); 1
printf("Second Matrix is: \n");
First Matrix is:
for (i = 0; i < 3; i++) { 123
for (j = 0 ;j < 3; j++) { 456
printf("%d ", b[i][j]); 789
}
printf("\n");
Second Matrix is:
B.Nagaeswari, VIT-AP Page 11
9 8 7
6 5 4
3 2 1
CSE1022 Introduction to Programming
}
printf("\n\n");
} printf("\n\n");
printf("Second Matrix is: \n");
for (i = 0; i < r2; i++) {
for (j = 0 ;j < c2; j++) {
printf("%d ", b[i][j]);
} printf("\n");
} printf("\n\n");
printf("Product of Two matrices is:-\n");
for (i = 0; i < r1; i++) {
for (j = 0 ;j < c2; j++) {
c[i][j]=0;
for (k = 0 ;k < r2;k++) {
c[i][j] = c[i][j] + a[i][k]* b[k][j] ;
} } }
for(i=0;i<r1;i++) {
for(j=0;j<c2;j++) {
printf("%d\t",c[i][j]);
}
printf("\n"); } return 0; }
#include<stdio.h> OUTPUT:
int main() {
int i,j; $ $ $ $ $ $ $ $
for(i=0;i<5;i++) {
$ $ $ $ $ $ $ $
for(j=0;j<8;j++) {
printf(" $ "); $ $ $ $ $ $ $ $
}
printf("\n"); $ $ $ $ $ $ $ $
}
return 0; $ $ $ $ $ $ $ $
}
for(k=1;k<=i;k++)
printf(" %d", k);
for(k=i-1;k>0;k--)
printf(" %d", k);
}
return 0;
}
Functions:
The prototype declaration, Function definition
When we write a program to solve a larger problem, we divide that larger problem into
smaller subproblems and are solved individually to make the program easier. In C, this
concept is implemented using functions. Functions are used to divide a larger program into
smaller subprograms such that program becomes easy to understand and easy to implement. A
function is defined as follows...
Definition: Function is a subpart of program used to perform specific task and is
executed individually.
Every C program must contain atleast one function called main(). However a program may
also contain other functions.
Every function in C has the following...
1. Function Declaration (Function Prototype)
2. Function Definition
3. Function Call
1. Function Declaration: The function declaration tells the compiler about
function name, datatype of the return value and parameters. The function declaration is also
called as function prototype. The function declaration is performed before main function or
inside main function or inside any other function.
Function declaration syntax:
returnType functionName(parametersList);
In the above syntax, returnType specifies the datatype of the value which is sent as a return
value from the function definiton. The functionName is a user defined name used to identify
the function uniquely in the program. The parametersList is the data values that are sent to the
function definition.
B.Nagaeswari, VIT-AP Page 15
CSE1022 Introduction to Programming
3. Function Call: The function call tells the compiler when to execute the function
definition. When a function call is executed, the execution control jumps to the function
definition where the actual code gets executed and returns to the same functions call once
the execution completes. The function call is performed inside main function or inside any
other function or inside the function itself.
Function call syntax:
functionName(parameters);
Advantages of Functions:
1. Using funcions we can implement modular programming.
2. Functions makes the program more readable and understandable.
3. Using functions the program implementation becomes easy.
4. Once a function is created it can be used many times (code re-usability).
5. Using functions larger program can be divided into smaller modules.
Types Of Functions:
In C Programming Language, based on providing the function definition, functions are
divided into two types. Those are as follows...
1. System Defined Functions
2. User Defined Functions
1. System Defined Functions: The C Programming Language provides pre-
defined functions to make programming easy. These pre-defined functions are known as
syatem defined functions. The system defined function is defined as follows...
Definition: The function whose definition is defined by the system is called as system
defined function.
Library Functions in Different Header Files and their functions…
C Header Files
Example:
#include<stdio.h>
#include<conio.h>
int main() {
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
return 0;;
}
Example:
#include<stdio.h>
#include<conio.h>
int main() {
int num1, num2 ;
void addition(int, int) ; // function declaration
printf("Enter any two integer numbers : ")
; scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
return 0 ;
}
Example:
#include<stdio.h>
#include<conio.h>
int main() {
int result ;
int addition() ; // function declaration
result = addition() ; // function call
printf("Sum = %d", result)
; getch() ;
}
Example:
#include<stdio.h>
#include<conio.h>
int main() {
int num1, num2, result ;
int addition(int, int) ; // function declaration ) ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition(int a, int b) { // function definition
return (a+b) ;
}
Call By Value and Call By Reference
CALL BY VALUE: If we pass the values to function, in call by value if any changes
occurred in function not reflected to main function variables. If any changes or occurred
in formal parameters it will not reflected to actual parameters. This concept is called as
Call By value.
Example: Program for CALL BY VALUE
#include<stdio.h>
void swap(int x, int y);
int main() {
int a, b;
a=10, b=20;
printf(“Before swapping a=%d, b=%d\n”,a,b);//a=10, b=20
swap(a,b);
printf(“After swapping a=%d, b=%d\n”,a,b); //a=10,b=20 return 0;
}
void swap( int a, int b ) {
int temp = a;
a = b;
b = temp;
printf(“After swapping a=%d, b=%d\n”,a,b); //a=20,b=10
}
printf("num1=%d, num2=%d",num1,num2) ;
addition() ;
return 0 ;
}
void addition() {
int result ;
result=num1+num2;
printf("\naddition=%d",result) ;
}
In the above example program, the variables num1 and num2 are declared as global
variables. They are declared before the main() function.
So, they can be accessed by function main() and other functions that are defined after
main(). In the above example, the functions main(), addition(), can access the variables
num1 and num2.
2)Inside the function or block (Local Declaration): Declaring a variable inside the
function or block is called local declaration. The variable declared using local declaration
is called local variable. The local variable can be accessed only by the function or block in
which it is declared. That means the local variable can be accessed only inside the
function or block in which it is declared.
Example Program:
#include<stdio.h>
int main() {
void addition() ;
int num1,num2 ;
num1=10 ;
num2=20 ;
printf("num1=%d, num2=%d",num1,num2) ;
addition() ;
return 0;
}
void addition() {
int sumResult ;
sumResult=num1+num2; printf("\
naddition=%d",sumResult) ;
}
The above example program shows an error because, the variables num1 and num2 are
declared inside the function main(). So, they can be used only inside main() function and
not in addition() function.
In the function definition parameters (Formal Parameters): The variables declared in
function definition as parameters have a local variable scope. These variables behave like
local variables in the function. They can be accessed inside the function but not outside the
function.
Example:
#include<stdio.h>
int main(){
void addition(int,int) ;
int num1,num2 ;
num1=10 ; num2=20 ;
addition(num1,num2) ;
return 0 ;
}
void addition(int a, int b) {
int sumResult;
sumResult=a+b;
printf("\naddition=%d",sumResult) ;
}
In the above example program, the variables a and b are declared in function
definition as parameters. So, they can be used only inside the addition() function.
Recursion:
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called as recursive function. Using recursive
algorithm, certain problems can be solved quite easily. Examples of such problems
are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals , DFS of
Graph, etc.
There are two important conditions that must be satisfied by any recursive
procedure
a. Each time a procedure calls itself it must be nearer in some sense to a solution
b. There must be a decision criterion for stopping the process or computation
/*the prog calculate factorial using recursion*/
#include<stdio.h>
long factorial(int n) {
if (n == 0)
OUTPUT:
return 1;
else Enter a number: 6
return(n * factorial(n-1));
} Factorial of 6 is 720
int main() {
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}
Towers of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The
objective of the puzzle is to move the entire stack to another rod, obeying the following
simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
Approach :
Take an example for 2 disks :
Input : 2
Output : Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C
Input : 3
Output : Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C