0% found this document useful (0 votes)
13 views25 pages

Ip (Unit-2) - Vit

The document provides an overview of arrays and functions in C programming, detailing array declaration, initialization, and manipulation techniques. It covers the characteristics of arrays, advantages and disadvantages, and various operations such as traversing, insertion, deletion, and sorting. Additionally, it explains the types of arrays including single, double, and multi-dimensional arrays with examples of their declaration and usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views25 pages

Ip (Unit-2) - Vit

The document provides an overview of arrays and functions in C programming, detailing array declaration, initialization, and manipulation techniques. It covers the characteristics of arrays, advantages and disadvantages, and various operations such as traversing, insertion, deletion, and sorting. Additionally, it explains the types of arrays including single, double, and multi-dimensional arrays with examples of their declaration and usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

CSE1022 Introduction to Programming

Module No. 2 Arrays and Functions


Arrays: declaration, initialization, accessing elements- Array manipulation. Functions: The prototype
declaration, Function definition, Function call: Passing arguments to a function, by value, by reference.
Scope of variable names. Recursive function calls.

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

data_type array_name [size1] [size2]...[sizeN];


where N is the number of dimensions.
Example for Array Declaration: If we declare Array with size 5, then the Array is as follows:
int arr[5]; --> declares 'arr' as an array to contain maximum 5 integers.

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};

B.Nagaeswari, VIT-AP Page 1


CSE1022 Introduction to Programming

Array Initialization and Declaration without Size: If we initialize an array using an


initializer list, we can skip declaring the size of the array as the compiler can automatically
deduce the size of the array in these cases. The size of the array in these cases is equal to the
number of elements present in the initializer list as the compiler can automatically deduce the
size of the array.
Syntax: data_type array_name[] = {value1, value 2, value3, value 4, value 5};

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.

Example: int arr[5] = { 15, 25, 35, 45, 55 };


printf(“%d”,a[2]);
//output: 35

Properties (or) Features (or) Characteristics of Array

1. Fixed Size Collection


2. Homogeneous Elements
3. Indexing in Array
4. Dimensions of Array
5. Contiguous Storage
6. Random Access
7. Array name relation with pointer
8. Bound Checking

B.Nagaeswari, VIT-AP Page 2


CSE1022 Introduction to Programming

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.

Advantages and disadvantages of Array

By using Array we have so many advantages compare with normal variables.


Advantages of Array:
1) Code Optimization: Less code to access the data.
2) Time saving: Less time to write coding.
3) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
4) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
5) Random Access: We can access any element randomly using the array.
6) Ease of Searching: The search process can be applied to an array easily.
7) low overhead: Arrays have low overhead for compiler because it uses continuous memory for
storing data.
8) Built-in Functions: C provides a set of built-in functions for manipulating arrays, such as sorting
and searching.
9) complex data: C supports arrays of multiple dimensions, which can be useful for
representing complex data structures like matrices.
10) Merged with other concepts: Arrays can be easily converted to pointers, which allows for
passing arrays to functions as arguments or returning arrays from functions.

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:

B.Nagaeswari, VIT-AP Page 3


CSE1022 Introduction to Programming

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.

Examples of common array manipulation tasks:


 Summing all elements in an array.
 Finding the maximum or minimum element.
 Removing duplicate elements.

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

B.Nagaeswari, VIT-AP Page 4


CSE1022 Introduction to Programming

to starting index number.


9) Merging Operation: we can combine two arrays elements into single array.

various types of Arrays in C Language?

Types of Arrays: There are 3 types of Arrays in C Language. They are:

1) Single Dimensional Arrays


2) Double Dimensional Arrays
3) Multi Dimensional Arrays
1) Single Dimensional Array: It is a collection of same type of number of values. It is a
collection of cells. Each cell is identified by a index. Starting index is ‘0’.
Last index is array size-1.
Declaration of Single Dimensional Array: We can declare an array by specifying its name,
type of its elements, and the size of its dimensions.

Syntax: Datatype variable_name[size];

Example: int a[10];

initialization of Single Dimensional Array: int a[5] =


{1,2,3,4,5};

(or) int a[5];

a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;

/* Progam for array inialization and printing array elements*/


#include <stdio.h>
int main() { OUTPUT:
int a[5]={10,20,30,40,50};
printf("%d ",a[0]) ; 10 20 30 40 50
printf("%d ",a[1]) ;
printf("%d ",a[2]) ;
printf("%d ",a[3]) ;
printf("%d ",a[4]) ;
return 0;
}

B.Nagaeswari, VIT-AP Page 5


CSE1022 Introduction to Programming

/* Progam to read elements in to array and printing them*/

#include <stdio.h> OUTPUT:


int main() {
int arr[100],i,n ;
printf("Enter no.of elements :",n ) ;
scanf("%d", &n) ;
printf("Enter %d Elements ",n);
for(i=0;i<n;i++){
scanf("%d", &arr[i]) ;
}
printf("Array Elements are: :");
for(i=0;i<n;i++){
printf("%d ", arr[i]) ;
}
return 0;
}
2)Double Dimensional Array: It is a collection of single dimension arrays. It is a collection of rows and
columns. It is also called as Matrix. Each array is identified by with ‘i’ i.e row position and each column is
identified with ‘j’ i.e. column position.
Declaration of Double Dimensional Array:
Syntax:
Datatype variable[row_size][col_size];
Example: int a[2][4];

Initialization of Double Dimensional array:


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

(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");
}

B.Nagaeswari, VIT-AP Page 6


CSE1022 Introduction to Programming

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:

Syntax: Datatype variable[no_of_dd_arrays][row_size][col_size];

Example: int a[2][3][3];


Initialization of Multi Dimensional Array:
int a[2][3][3] ={
{ {1,2,3},
{4,5,6},
{7,8,9}
};
{
{1,2,3},
{4,5,6},
{7,8,9}
},
};
(or)
int a[2][3][3] ={
{ {1,2,3}, {4,5,6}, {7,8,9} };
{ {1,2,3}, {4,5,6}, {7,8,9} };

B.Nagaeswari, VIT-AP Page 7


CSE1022 Introduction to Programming

};

Example: Program to initialize and print the 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; }

B.Nagaeswari, VIT-AP Page 8


CSE1022 Introduction to Programming

2. Write a C program to reverse of a 1-D integer Array


#include <stdio.h>
#define N 1000
int main() { OUTPUT:
int arr[N],n,i; Enter the size of the array: 7
printf("Enter the size of the array: "); Enter 7 elements in to array: 25
scanf("%d", &n); 63
printf("Enter %d elements in to array: ",n); 78
for (int i = 0; i < n; i++) { 98
scanf("%d", &arr[i]); 65
} 45
int rarr[N]; 25
for (i = 0; i<n; i++) {
rarr[i] = arr[n-i-1]; Reversed array: 25 45 65 98 78 63 25
}
printf("Reversed array: ");
for (i = 0; i<n; i++) {
printf("%d ", rarr[i]);
}
return 0;
}

3. Write a C program to perform linear search on 1-D Array


Linear/Sequential Search
 Searching is the process of finding an item from a collection of items.
 linear search or sequential search is a method for finding a particular value in a list by
checking every one of its elements, one at a time and in sequence, until the desired one is found.
 Linear search is the simplest search algorithm.

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;
}
}

B.Nagaeswari, VIT-AP Page 9


CSE1022 Introduction to Programming

if(i==n)
printf("%d is not present in the array.\n", search);
return 0;
}

4. Write a C program to eliminate duplicate elements in an Array


#include <stdio.h>
#define N 100 OUTPUT:
int main () {
int arr[N], i, j, k, size;
printf (" Define the number of elements in an array: ");
scanf (" %d", &size);
printf (" \n Enter %d elements of an array: \n ", size);
for ( i = 0; i < size; i++) {
scanf (" %d", &arr[i]);
}
for ( i = 0; i < size; i ++) {
for ( j = i + 1; j < size; j++) {
if ( arr[i] == arr[j]) {
for ( k = j; k < size - 1; k++) {
arr[k] = arr [k + 1];
}
size--;
j--;
}
}}
printf (" \n Array elements after deletion of the duplicate elements: ");
for ( i = 0; i < size; i++) {
printf (" %d \t", arr[i]);
}
return 0;
}

5. Write a C program for Addition of Two Matrices


#include <stdio.h>
int main() {
int m, n, i, j, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);
printf("Enter the elements of second matrix\n");
for (i = 0; i < m; i++)
for (j = 0 ;j < n; j++) OUTPUT:
scanf("%d", &second[i][j]); Enter the number of rows and columns of matrix
printf("First Matrix is: \n"); 33
for (i = 0; i < m; i++) { Enter the elements of first matrix
for (j = 0 ;j < n; j++) { 123456789
printf("%d ", first[i][j]); Enter the elements of second matrix
248914637
B.Nagaeswari, VIT-AP Page 10
First Matrix is:
123
456
789
CSE1022 Introduction to Programming

}
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("Product of Two matrices is:-\n");


for (i = 0; i < 3; i++) {
for (j = 0 ;j < 3; j++) {
c[i][j]=0;
for (k = 0 ;k < 3;k++) {
c[i][j] = c[i][j] + a[i][k]* b[k][j] ;
}
}
}
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("%d\t",c[i][j]);
}
printf("\n");
}
return 0;
}
7. C program for Multiplication of Two Matrices by reading row, column size
#include<stdio.h>
int main() {
int a[10][10], b[10][10], c[10][10]; OUTPUT:
int r1,r2,c1,c2,i,j,k; Enter rows and columns for the first
printf("Enter rows and columns for the first matrix: "); matrix: 2
scanf("%d%d",&r1,&c1); 3
printf("Enter rows and columns for the second matrix: "); Enter rows and columns for the
scanf("%d%d",&r2,&c2); second matrix: 2
while (c1 != r2) { 3
printf("Error! Enter rows and columns again.\n"); Error! Enter rows and columns again.
printf("Enter rows and columns for the first matrix: "); Enter rows and columns for the first
scanf("%d %d", &r1, &c1); matrix: 2
printf("Enter rows and columns for the second matrix: "); 3
scanf("%d %d", &r2, &c2); Enter rows and columns for the
} second matrix: 3
2
printf("enter first matrix elements:\n");
enter first matrix elements:
for(i=0;i<r1;i++) {
1
for(j=0;j<c1;j++) {
scanf("%d",&a[i][j]); 2
} } 4
printf("enter second matrix elements:\n"); 3
for(i=0;i<r2;i++) { 6
for(j=0;j<c2;j++) { 5
scanf("%d",&b[i][j]); enter second matrix elements:
} } 1
printf("First Matrix is: \n"); 2
for (i = 0; i < r1; i++) { 4
for (j = 0 ;j < c1; j++) { 3
printf("%d ", a[i][j]); 5
} printf("\n"); 1

B.Nagaeswari, VIT-AP Page 12 First Matrix is:


1 2 4
3 6 5
CSE1022 Introduction to Programming

} 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; }

8. Write a C program to Sort an array of elements using Bubble Sort


#include<stdio.h>
OUTPUT:
int main() {
-------Bubble sort ------
int a[100],n,i,j,temp; enter no of elements : 10
printf("\n \t\t-------Bubble sort ------ \n");
printf("\n enter no of elements : "); enter 10 integers
scanf("%d",&n); Enter 1 element : 56
printf("\n enter %d integers \n",n); Enter 2 element : 47
for(i=0;i<n;i++) { Enter 3 element : 96
printf(" Enter %d element : ",i+1); Enter 4 element : 54
scanf("%d",&a[i]); Enter 5 element : 23
} Enter 6 element : 14
for(i=0;i<n;i++) { Enter 7 element : 85
Enter 8 element : 63
for(j=0;j<n-i-1;j++) {
Enter 9 element : 73
if(a[j]>a[j+1]) { Enter 10 element : 37
temp=a[j];
a[j]=a[j+1]; sorted list in ascending order :
a[j+1]=temp; 14
} } } 23
printf("\n\t\t sorted list in ascending order : "); 37
for(i=0;i<n;i++) 47
printf("\n%d",a[i]); 54
return 0; 56
} 63
73
85
96

B.Nagaeswari, VIT-AP Page 13


CSE1022 Introduction to Programming

9. Write a C program to merge two Arrays


#include <stdio.h>
int main() {
int arr1size = 5, arr2size = 5, arr_resultsize, i, j;
int a[5] = { 1, 2, 3, 4, 5 };
int b[5] = { 6, 7, 8, 9, 10 }; OUTPUT:
int c[20]; Merged Array:
arr_resultsize = arr1size + arr2size; 1 2 3 4 5 6 7 8 9 10
c[arr_resultsize];
for (i = 0; i < arr1size; i++) {
c[i] = a[i];
}
for (i = 0, j = arr1size;j < arr_resultsize && i < arr2size; i++, j++) {
c[j] = b[i];
}
printf("Meged Array:\n");
for (i = 0; i < arr_resultsize; i++) {
printf("%d ", c[i]);
}
return 0;
}

10. Write a C program to generate series in the following format

#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; $ $ $ $ $ $ $ $
}

11. Write a C program to generate pyramid up to n value in the following format


#include<stdio.h>
int main() { 1
int i,j,k,n; 1 2 1
printf("Enter Range : "); 1 2 3 2 1
scanf("%d", &n); 1 2 3 4 3 2 1
for(i=1;i<=n;i++) { 1 2 3 4 5 3 2 1
printf("\n\t\t");
for(j=1;j<n;j++)
printf(" ");

B.Nagaeswari, VIT-AP Page 14


CSE1022 Introduction to Programming

for(k=1;k<=i;k++)
printf(" %d", k);
for(k=i-1;k>0;k--)
printf(" %d", k);
}
return 0;
}

12. Write a C program to generate pyramid up to n value in the following format


#include<stdio.h>
int main() {
int i,j,k,n;
printf("Enter no.of rows : ");
OUTPUT:
scanf("%d", &n);
Enter no.of rows : 5
k=n-1;
1
for(i=1;i<=n;i++) {
12
for(j=1;j<=k;j++) 123
printf(" "); 1234
for(j=1;j<=i;j++) 12345
printf(" %d", j);
printf("\n");
}
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

2. Function Definition: The function definition provides the actual code of


that function. The function definition is also known as body of the function. The actual task of
the function is implemented in the function definition. That means the actual instructions to
be performed by a function are written in function definition. The actual instructions of a
function are written inside the braces "{ }". The function definition is performed before main
function or after main function.
Function definition syntax:
returnType functionName(parametersList) {
Actual code...
}

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…

B.Nagaeswari, VIT-AP Page 16


CSE1022 Introduction to Programming

C Header Files

<ctype.h> Character type functions Ex: isalpha(), islower(), isupper()…

<math.h> Mathematics functions Ex: pow(), sqrt(), ceil(), floor(),..

Standard Input/Output Ex: printf(), scanf(), putc(), getc(),..


<stdio.h>
functions

Standard Utility Ex: free(), abort(), exit(),….


<stdlib.h>
functions

<string.h> String handling functions Ex: strcat(), strcmp(), strcpy(), strlen()


Points to be Remembered:
 System defined functions are declared in header files
 System defined functions are implemented in .dll files. (DLL stands for Dynamic
Link Library).
 To use system defined functions the respective header file must be included.

2. User Defined Functions: In C programming language, users can also


create their own functions. The functions that are created by users are called as user defined
functions. The user defined function is defined as follows...
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 ;
}
In the above example program, the function declaration statement "int
addition(int,int)" tells the compiler that there is a function with name addition which takes two
integer values as parameters and returns an integer value. The function call statement takes the
execution control to the additon() definition along with values of num1 and num2.
Then function definition executes the code written inside it and comes back to the
function call along with return value.
Based on the data flow between the calling function and called function, the functions
are classified as follows...
1. Function without Parameters and without Return value
B.Nagaeswari, VIT-AP Page 17
CSE1022 Introduction to Programming

2. Function with Parameters and without Return value


3. Function without Parameters and with Return value
4. Function with Parameters and with Return value
1. Function without Parameters and without Return value:
In this type of functions there is no data transfer between calling function and called function.
Simply the execution control jumps from calling function to called function and executes
called function, and finally comes back to the calling function.

Example:
#include<stdio.h>
#include<conio.h>
int main() {
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
return 0;;
}

void addition() { // function definition


int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}

2. Function with Parameters and without Return value:


In this type of functions there is data transfer from calling function to called function
(parameters) but there is no data transfer from called function to calling function (return
value). The execution control jumps from calling function to called function along with the
parameters and executes called function, and finally comes back to the calling function.

B.Nagaeswari, VIT-AP Page 18


CSE1022 Introduction to Programming

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 ;
}

void addition(int a, int b) { // function definition


printf("Sum = %d", a+b ) ;

3. Function without Parameters and with Return value:


In this type of functions there is no data transfer from calling function to called function
(parameters) but there is data transfer from called function to calling function (return value).
The execution control jumps from calling function to called function and executes called
function, and finally comes back to the calling function along with a return value.

Example:
#include<stdio.h>
#include<conio.h>
int main() {
int result ;
int addition() ; // function declaration
result = addition() ; // function call
printf("Sum = %d", result)
; getch() ;
}

int addition() { // function definition


int num1, num2 ;

printf("Enter any two integer numbers : ") ;


scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
B.Nagaeswari, VIT-AP Page 19
CSE1022 Introduction to Programming

4. Function with Parameters and with Return value:


In this type of functions there is data transfer from calling function to called function
(parameters) and also from called function to calling function (return value). The execution
control jumps from calling function to called function along with parameters and executes
called function, and finally comes back to the calling function along with a return value.

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
}

B.Nagaeswari, VIT-AP Page 20


CSE1022 Introduction to Programming

CALL BY Reference(Modifying parameters inside functions using pointers): If we


pass the values to function, in call by reference if any changes occurred in function it will
reflected to main function variables. If any changes or occurred in formal parameters
changes will reflected to actual parameters. This concept is called as Call By Reference. In
call by reference we pass the actual variable addresses to calling function.
Example: Program for CALL BY REFERENCE
#include<stdio.h>
void swap( int *a, int *b );
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=20,b=10
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
}
scope of variables?
When we declare a variable in a program, it can not be accessed against the scope
rules. Variables can be accessed based on their scope. The scope of a variable decides the
portion of a program in which the variable can be accessed. The scope of the variable is
defined as follows... “Scope of a variable is the portion of the program where a defined
variable can be accessed.”
The variable scope defines the visibility of variable in the program. Scope of a
variable depends on the position of variable declaration.
In C programming language, a variable can be declared in three different positions and
they are as follows...
1) Before the function definition (Global Declaration)
2) Inside the function or block (Local Declaration)
3) In the function definition parameters (Formal Parameters)
1) Before the function definition (Global Declaration): Declaring a variable before the
function definition (outside the function definition) is called global declaration. The
variable declared using global declaration is called global variable. Tha global variable
can be accessed by all the functions that are defined after the global declaration. That
means the global variable can be accessed any where in the program after its
declaration. The global variable scope is said to be file scope.
Example Program:
#include<stdio.h>
int num1, num2;
int main() {
void addition() ;
num1=10;
num2=20;

B.Nagaeswari, VIT-AP Page 21


CSE1022 Introduction to Programming

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 ;

B.Nagaeswari, VIT-AP Page 22


CSE1022 Introduction to Programming

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 :

B.Nagaeswari, VIT-AP Page 23


CSE1022 Introduction to Programming

Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.


Step 1 : Shift first disk from 'A' to 'B'.
Step 2 : Shift second disk from 'A' to 'C'.
Step 3 : Shift first disk from 'B' to 'C'.
The pattern here is :
Shift 'n-1' disks from 'A' to 'B'.
Shift last disk from 'A' to 'C'.
Shift 'n-1' disks from 'B' to 'C'.

Recursive function for Towers of hanoi


void TOH(int num,char S,char D,char I) {
if(num>0) {
TOH(num-1,S,I,D);
printf("\n %c --> %c",S,D);
TOH(num-1,I,D,S);
}}

Image illustration for 3 disks :

C program for Towers of hanoi


#include<stdio.h>
void TOH(int num,char A,char C,char B);
int main() {
int num;
printf("\n enter no of discs : ");
scanf("%d",&num);
TOH(num,'A','C','B');
return 0;
}

B.Nagaeswari, VIT-AP Page 24


CSE1022 Introduction to Programming

void TOH(int num,char A,char C,char B) {


if(num>0) {
TOH(num-1,A,B,C);
printf("\n %c --> %c",A,C);
TOH(num-1,B,C,A);
}
}

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

Difference between recursion and iteration


Iteration Recursion
In iteration, a problem is converted into a Recursion is like piling all of those steps on
train of steps that are finished one at a top of each other and then quashing them
time, one after Another all into the solution.
With iteration, each step clearly leads In recursion, each step replicates itself at a
onto the next, like stepping stones across smaller scale, so that all of them combined
a river together
eventually solve the problem.
Any iterative problem is solved recursively Not all recursive problem can solved by
iteration
It does not use Stack It uses Stack

B.Nagaeswari, VIT-AP Page 25

You might also like