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

POP Unit 3 Part 2

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)
13 views87 pages

POP Unit 3 Part 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

PRINCIPLES OF

PROGRAMMING IN C
22CS2ESPOP - UNIT 3 PART 2
Prof. SNEHA S BAGALKOT
Assistant Professor, Dept. of CSE
UNIT – 3: Functions and Arrays
▪ Arrays: Introduction
▪ Declaration of Arrays
▪ Accessing the elements of an Array
▪ Storing values in Arrays
▪ Operations on Arrays (Insertion, Deletion, Searching)
▪ Two-Dimensional Arrays
▪ Transpose of a Matrix
▪ Example Programs.
Arrays: Introduction
• To process large amounts of data, we need a data structure known as Array.

• An array is a collection of similar data elements.

• These data elements have the same data type.

• The elements of the array are stored in consecutive memory locations and
are referenced by an index (also known as the subscript).

• Subscript is an ordinal number that is used to identify an element of the


array.
Need of Arrays
• In C programming, one of the frequently arising problems is to handle
similar types of data.
• For example: If the user wants to store marks of 100 students. This can be
done by creating 100 variables individually but, this process is rather
tedious and impracticable. This type of problem can be handled in C
programming using arrays.
• An array variable can store more than one value of same data type, where
an individual variable can store only one value of any data type defined.
Definition
• Array is the derived data type.
• Array is the homogeneous collection of data items.
• The elements of an array are of same data type and each item can be
accessed using the same name.
• All the data items of an array are stored in consecutive memory locations
in RAM.
Note: An array is a derived data type because it cannot be defined on its
own; it is a collection of basic data types such as char, integer, double, and
float.
Classification of arrays

• Single Dimension Array


• Multi Dimension Array

Single Dimension Array (1D - Array)


• A single-dimensional array is a linear list containing the data items of
the same type and stored in continuous memory location.
Declaration of 1D Array
Syntax: Data_type Array_name[Array_size];
• Data_type –general data types like - int, char, float, double.
• Array_name – valid identifier.
• Array_size - maximum number of elements.
• Example: 1. int arr [20] ;
2. float arr1 [30] ;
3. double arr2 [30] ;
In C, the array index starts from zero.
Pictorial Representation of Single Dimensional array
• Representation of an array int arr[5], with five integers array
elements and by assuming the memory location starting from 1024 –
• “arr” is an array which can store maximum of five integer values.
• The array elements are arranged in continuous memory location
starting from 1024 (assumed memory) has an incrementing of 4 bytes
for integer values.
• The memory allocated = size of data type * array_size.
• For the above representation total memory is 20 bytes (4 bytes *5
elements).
• The array Index/ Subscript starts from 0 and the maximum Index /
Subscript will be Array_size -1.
Accessing the elements of an Array
• Elements of the array is represented using array name with Subscript / Index
as follows:
Representation Array Element
a[0] 10
a[1] 5
a[2] 2
a[3] 15
a[4] 20
• Note: The array values may be of any data type but the size and index
should be integer only.
• Example: 1. int arr[5] – valid
2. int arr[10.5] - invalid
Accessing the Elements of an Array
• For accessing an individual element of the array, the array subscript must be
used. For example, to access the 4th element of the array, we must write arr[3].
• The subscript must be an integral value or an expression that evaluates to an
integral value.
• To access all the elements of the array, we must use a loop. That is, we can access
all the elements of the array by varying the value of the subscript into the array.

• Example: To set each element of the array to -1


int i, marks[10];
for(i=0; i<10; i++)
marks[i] = -1;
• The above code accesses every individual element of the array and sets its
value to -1.
Storing Values in Arrays

Initialize the elements


during declaration

Input values for the


Store values in an elements from the
array keyboard

Assign values to
individual elements
Initializing Arrays during Declaration
• Arrays are initialized by writing,
type array_name[size]={list of values};
• Example: int marks[5]={90, 82, 78, 95, 88};
• When initializing the array at the time of declaration, size of the
array can be omitted.
• Example: int marks[ ]={90, 82, 78, 95, 88};
int marks[5]={90, 82};
int marks[5]={0};
Inputting Values from the Keyboard
Code for inputting each element of the array

int i, marks[10];
for(i=0; i<10; i++)
scanf(“%d”, &marks[i]);
Assigning Values to Individual Elements
Code to copy an array at the individual element level

int i, arr1[10], arr2[10];


for(i=0; i<10; i++)
arr2[i] = arr1[i];
Write a program to read and display n numbers using an array.
#include<stdio.h>
int main()
{ int i=0, n, arr[20]; Output:
printf(“\n Enter the number of elements:“); Enter the number of elements:3
scanf(“%d”, &n); Arr[0] = 10
for(i=0; i<n; i++) Arr[1] = 20
Arr[2] = 30
{ The array elements are
printf(“\n Arr[%d] = “, i); Arr[0] = 10
scanf(“%d”, &arr[i]); Arr[1] = 20
} Arr[2] = 30
printf(“\n The array elements are\n“);
for(i=0; i<n; i++)
printf(“Arr[%d] = %d\n”, i, arr[i]);
return 0;
}
Operations on Arrays

• There are a number of operations that can be performed on arrays.

• These operations include the following:


Inserting an element in an array
Deleting an element from an array
Searching an element in an array
Program to read and print marks of n students
void main()
{
int i, n;
printf("enter the number of students");
scanf("%d", &n);
int mark[n];
for(i=0; i<n; i++)
{
printf("enter student %d marks",i+1);
scanf("%d", &mark[i]);
}
for(i=0; i<n; i++)
{
printf("\n marks of student %d is : %d", i+1, mark[i]);
}
}
Program to add all the elements of 1D array
void main()
{
int n, sum=0;
printf("enter size of array");
scanf("%d", &n);
int a[n];
printf("enter array elements");
for(int i=0; i<n; i++)
scanf("%d", &a[i]);
for(int i=0; i<n; i++)
{
sum=sum + a[i];
}
printf("\n sum is %d", sum);
}
Using Functions
Algorithm
1. Start
2. Declare an array.
3. Ask the user to initialize the array.
4. Call a function that will calculate the sum and percentage of all the
elements(marks) in an array.
5. Declare a sum variable there and initialize it to 0.
6. Update the sum in each iteration.
7. Print the sum.
8. Calculate the percentage.
9. Print the percentage scored.
10. Stop.
Program to copy elements of one array to another
void main()
{
int n, sum=0;
printf("enter size of array");
scanf("%d", &n);
int a[n], b[n];
printf("enter array elements");
for(int i=0; i<n; i++)
scanf("%d", &a[i]);
for(int i=0; i<n; i++)
{
b[i] = a[i];
}
//Print array b
}
Write a program to print smallest number and its
position in an array of size n
#include<stdio.h>
small = a[0];
void main() for(i=1; i<n; i++)
{ {
int i, n, small, pos=0; if(a[i] < small)
printf("enter the size of array"); {
scanf("%d", &n); small = a[i];
pos = i;
int a[n];
}
printf("enter the elements"); }
for(i=0; i<n; i++) printf("the smallest element is %d \n its
{ position is %d", small, pos);
}
scanf("%d", &a[i]);
}
Program to find if there are duplicates in the array
#include<stdio.h> for(i=0; i<n; i++)
void main() {
{ for(int j=i+1; j<n; j++)
int i, n, small, pos; {
printf("enter the size of array"); if(a[i] == a[j] && i != j)
scanf("%d", &n); {
flag=1;
int a[n],flag=0;
printf("\n Duplicate number
printf("enter the elements"); found at location %d and %d", i, j);
for(i=0; i<n; i++) }
{ }
scanf("%d", &a[i]); }
} }
Inserting an element at a specific position in an array
Expected Output

• pos, as this is now empty.


Algorithm
Step 1: Start
Step 2: Declare and initialize an array a[n] , Where n is number of elements in the
array
Step 3: Read the number to be inserted and position to be inserted into
Step 4: Set i=n-1
Step 5: While i >= pos
Set a[i+1]=a[i]
i=i-1;
Step 6 : Set a[pos] = num;
Step 7: Set n=n+1;
Step 8: Display the array
Step 9 :Stop
void main()
{
int pos, n, num, i;
printf("enter the size of array :");
scanf("%d", &n);
int a[n];
printf("enter the elements : ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
printf("enter number to be inserted : ");
scanf("%d", &num);
printf("enter position to insert : ");
scanf("%d", &pos);
for(i=n-1; i>=pos; i--)
{
a[i+1] = a[i];
}
a[pos] = num;
n++;
printf("\n The array after insertion is : ");
for(i=0; i<=n-1; i++)
printf(" %d \t", a[i]);
}
Program to delete an element in a specific position
in an array
Algorithm
Step 1: Start
Step 2: Declare and initialize an array a[n] , where n is number of elements
in the array
Step 3: Read position at which number should be deleted
Step 4: Set i=pos
Step 5: While i < n-1
Set a[i] = a[i+1]
i = i + 1;
Step 6: Set n = n - 1;
Step 7: Display the array
Step 8 :Stop
void main()
{
int pos, n, num, i;
printf("enter the size of array :");
scanf("%d", &n);
int a[n];
printf("enter the elements : ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
printf("enter position from which element should be deleted : ");
scanf("%d", &pos);
for(i=pos; i<n-1; i++)
{
a[i] = a[i+1];
}
n--;
printf("\n The array after deletion is : ");
for(i=0; i<=n-1; i++)
printf(" %d \t", 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.


Program to demonstrate Linear search
Expected Output
Algorithm
Step 1: Start
Step 2: Declare and Initialise an array a[n] where n is the size of array
Step 3: Read the number that has to be searched - key
Step 4: Set i = 0
Step 5: while i < n
if a[i] = key
print that the element is found in position i
exit from loop – go to step 7
i = i + 1;
Step 6: if end of array is reached
then print that the element is not found in the array
Step 7: Stop
void main()
{
int a[100], key, i, n;
printf("Enter number of elements in array: ");
scanf("%d", &n);
printf("\n Enter elements of the array: ");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\n Enter a number to search: \n");
scanf("%d", &key);
for (i = 0; i < n; i++)
{
if (a[i] == key)
{
printf("%d is present at location %d \n", key, i+1);
break;
}
}
if (i == n)
printf("%d isn't present in the array\n", key);
}
Program to demonstrate Binary search
Expected Output
Algorithm
Step 1: Start
Step 2: Declare and Initialise the array a[n] where n is the size of array. The array elements need to
be in ascending order
Step 3: Read the number that has to be searched – key
Step 4: Set low = 0 and high = n-1
Step 5: Compute mid = (low + high) / 2
Step 6: while low <= high
if(array[mid] < key)
set low = mid + 1;
else if (array[mid] == key)
Print key found at location mid+1
Exit loop -go to step 9
else
Set high = mid - 1;
Step 7 : compute mid = (low + high) / 2 and repeat step 6
Step 8: if(low > high)
Print element Not found
Step 9: Stop
void main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elements in the array");
scanf("%d", &n);
printf("Enter the array elements");
for(i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter value to be searched ");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low + high) / 2;
while (low <= high) {
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key) {
printf("\n %d found at location %d", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list", key);
}
PART B: LAB PROGRAM 1

Develop a C program to search a Book ID from an


organized bookshelf that has N number of
books using appropriate searching technique.
#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of books in the shelf\n");
scanf("%d", &n);
printf("Enter %d BookIds\n", n);
for(i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter BookID(number) to find\n");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low + high) / 2;
while (low <= high)
{
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key)
{
printf("BookId=%d is found at location %d\n", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high) / 2;
}
if(low > high)
printf("BookID Not found! %d isn't present in the Book Shelf\n", key);
return 0;
}
Output
Two Dimensional Arrays
• A two-dimensional array is specified using two subscripts where one subscript
denotes row and the other denotes column.
• C considers the two-dimensional array as an array of a one-dimensional array.
• Figure below shows a two-dimensional array which can be viewed as an array
of arrays.
First Dimension

Second Dimension
Declaring Two-dimensional array
• A two-dimensional array is declared as:
data_type array_name[row_size][column_size];

• Therefore, a two-dimensional mXn array is an array that contains m*n


data elements and each element is accessed using two subscripts, i and j
where i<=m and j<=n.

• Example: int marks[3][5]


Rows/Columns Col 0 Col 1 Col2 Col 3 Col 4
Row 0 Marks[0][0] Marks[0][1] Marks[0][2] Marks[0][3] Marks[0][4]
Row 1 Marks[1][0] Marks[1][1] Marks[1][2] Marks[1][3] Marks[1][4]
Row 2 Marks[2][0] Marks[2][1] Marks[2][2] Marks[2][3] Marks[2][4]
Initializing Two-dimensional Arrays
• Arrays are initialized by writing,
type array_name[size][size]={list of values};
Example:
• int marks[2][3] = {90, 87, 78, 68, 62, 71};
• The initialization of two-dimensional array is done row by row.
• int marks[2][3] = {{90, 87, 78}, {68, 62, 71}};
• int marks[ ][3] = {{90, 87, 78}, {68, 62, 71}}; //Only size of 1st dimension can be omitted.
• int marks[2][3] = {0}; //Entire 2D array is initialized to zero.
• int marks[ ][3] = {{90, 87, 78}}; //Elements of 2nd row will be initialized to zero.
Code to input the values from the keyboard into 2D array
int i, j, marks[2][3];
for(i=0; i<2; i++)
for(j=0; j<3; j++)
scanf(“%d”, &marks[i][j]);
Write a program to read and print the elements of a
2D array.
#include <stdio.h>
void main()
{
int i, j, arr[2][2];
printf("Enter the array elements\n");
for(i=0; i<2; i++)
for(j=0; j<2; j++)
scanf("%d", &arr[i][j]);
printf(" The 2D array elements are:\n");
for(i=0; i<2; i++)
{
printf("\n");
for(j=0; j<2; j++)
printf("%d\t", arr[i][j]);
}
}
Operations on Two-dimensional Arrays
Following operations can be performed on an m X n matrix.
• Transpose:
Transpose - m X n matrix A is given as n X m matrix B where, Bi,j =Aj,i
• Sum:
Two compatible matrices – added – storing result - third matrix. Two matrices are
compatible when they have same number of rows and columns. Elements of the
matrices - added by writing: Ci,j = Ai,j + Bi,j
• Difference:
Two compatible matrices - subtracted – storing result - third matrix. Elements of
the matrices can be subtracted by writing: Ci,j = Ai,j – Bi,j
• Product:
Two matrices - multiplied - if number of columns - first matrix = number of rows -
second matrix. Therefore, m X n matrix A - multiplied with p X q matrix if n = p.
Elements of the matrices can be multiplied by writing:
Ci,j =∑ Ai,k Bk,j for k=1 to k < n
Write a C program to find sum of two matrices
#include <stdio.h>
int main() printf("Sum of entered matrices:-\n");
{
for(c=0; c<m; c++)
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
{
printf("Enter the number of rows and columns of
matrix\n"); for(d=0; d<n; d++)
scanf("%d%d", &m, &n); {
printf("Enter the elements of first matrix\n"); sum[c][d] = first[c][d] + second[c][d];
for(c=0; c<m; c++) printf("%d\t", sum[c][d]);
for(d=0; d<n; d++) }
scanf("%d", &first[c][d]); printf("\n");
printf("Enter the elements of second matrix\n"); }
for(c=0; c<m; c++)
return 0;
for(d=0; d<n; d++)
}
scanf("%d", &second[c][d]);
OUTPUT
Write a C program to find product of two matrices
#include<stdio.h>
void main() printf("Product of the matrix=\n");
{ for(i=0; i<r; i++)
{
Output:
int a[10][10], b[10][10], mul[10][10], r, c, i, j, k; enter the number of rows=3
printf("enter the number of rows="); for(j=0; j<c; j++)
{ enter the number of columns=3
scanf("%d", &r);
printf("enter the number of columns="); mul[i][j] = 0; enter the first matrix element=
scanf("%d", &c); for(k=0; k<c; k++) 123
printf("enter the first matrix element=\n"); { 456
for(i=0; i<r; i++) mul[i][j] += a[i][k] * b[k][j]; 789
{ }
} enter the second matrix element=
for(j=0; j<c; j++)
} 234
{
scanf("%d", &a[i][j]); //for printing result 567
} for(i=0; i<r; i++) 891
} { Product of the matrix=
printf("enter the second matrix element=\n"); for(j=0; j<c; j ++)
36 42 21
for(i=0; i<r; i++) {
printf("%d\t", mul[i][j]); 81 96 57
{
} 126 150 93
for(j=0; j<c; j++)
{ printf("\n");
scanf("%d", &b[i][j]); }
} }
}
Output:
enter the number of rows=3
enter the number of columns=3
enter the first matrix element=
123
456
789
enter the second matrix element=
234
567
891
Product of the matrix=
36 42 21
81 96 57
126 150 93
PART B: LAB PROGRAM 2

Develop a C program to find the Transpose


of a Matrix.
#include <stdio.h>
void main()
{
int m, n, i, j, matrix[10][10], transpose[10][10];
printf("Enter rows and columns :\n"); Output
scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");
for (i= 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];
printf("Transpose of the matrix:\n");
for (i = 0; i< n; i++)
{
for (j = 0; j < m; j++)
printf("%d\t", transpose[i][j]);
printf("\n");
}
}
FLOWCHART
#include <stdio.h>
void main()
{
int m, n, i, j, matrix[10][10], transpose[10][10];
printf("Enter rows and columns :\n");
scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");
for (i= 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];
printf("Transpose of the matrix:\n");
for (i = 0; i< n; i++)
{
for (j = 0; j < m; j++)
printf("%d\t", transpose[i][j]);
printf("\n");
}
}
PART B: LAB PROGRAM 4

Parameter Passing techniques: Call by Value


and Call by reference
Develop a C program to swap two integer
numbers using call by value and call by
reference parameter passing technique.
#include <stdio.h>
void swap_call_by_val(int x, int y);
void swap_call_by_ref(int *ptrx, int *ptry);
int main()
{
int x, y;
printf(“ Enter Value of x ");
scanf("%d", &x);
printf("\n Enter Value of y ");
scanf("%d", &y);
swap_call_by_val(x, y);
swap_call_by_ref(&x, &y);
return 0;
}
void swap_call_by_val(int x, int y)
{
int temp = x;
x = y;
y = temp;
printf("\n After Swapping using call by value: x = %d, y = %d", x, y);
}
void swap_call_by_ref(int *ptrx, int *ptry)
{
int temp = *ptrx;
*ptrx = *ptry;
*ptry = temp;
printf("\n After Swapping using call by reference: x = %d, y = %d", *ptrx, *ptry);
}
Output
PASSING ARRAYS TO FUNCTIONS

•In large programs that use functions we can pass Arrays as


parameters. Two ways of passing arrays to functions are:
• Pass individual elements of array as parameter

• 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.
• 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
Question
Write a C Program to read a Matrix as input and find:

1. Row sum

2. Column sum

3. Diagonal sum
Example Programs
Merging
#include <stdio.h> printf("\n The unique elements found in the array are: \n");
for (i = 0; i < n; i++)
void main()
{
{ ctr = 0;
int arr1[100], n, ctr = 0; for (j = 0, k = n; j < k + 1; j++)
{
int i, j, k; if (i != j)
printf(“\n Input the number of elements to be {
stored in the array: "); if (arr1[i] == arr1[j])
{
scanf("%d", &n); ctr++; // Increment the counter when the search value is duplicate
printf("Input %d elements in the array :\n", n); }
}
for (i = 0; i < n; i++)
}
{ if (ctr == 0)
printf("element - %d : ", i); {
printf("%d ", arr1[i]); // Print the unique element
scanf("%d", &arr1[i]); }
} }
}
Example Programs
1. Write a C- Program to read a 1D - array with n elements and to print the same.
2. Write a C- Program to find the sum and average of all the elements in the
array.
3. Write a C- Program to find the largest element and its position in the array.
4. Write a C- Program to generate the Fibonacci series using arrays.
5. Write a C- Program to find the sum of odd elements and even elements stored
in an array.
6. Write a C- Program to print the twin primes up to specified limit.
7. Write a C- Program to generate 100 random integers in the range 1-100, store
them in an array and print the average.
8. Write a C- Program to print the average of the given numbers and also the
numbers greater than the average.
9. Write a C- Program to convert the decimal value to binary value.
10. Write a C- Program to convert the binary value to decimal value.
Example Programs
11. Write a C- Program to find the smallest and largest element in the array.
12. Write a C- Program to evaluate the Polynomial using a0x0+a1x1+a2x2+….+anxn Horner’s method.
13. Write a C- Program to swap the content of two arrays.
14. Write a C- Program to compute the following:
C[0]=a[0]+b[9]
C[1]=a[1]+b[8]
C[2]=a[2]+b[7]
C[3]=a[3]+b[6]
C[4]=a[4]+b[5]
C[5]=a[5]+b[4]
C[6]=a[6]+b[3]
C[7]=a[7]+b[2]
C[8]=a[8]+b[1]
C[9]=a[9]+b[0]

15. Write a C- Program to delete the duplicate elements from an array.


THANK
YOU

You might also like