Unit-4 array computer programming
Unit-4 array computer programming
Array
Concept of one dimensional and multi – dimensional array: Array is a linear data
structure where all elements are arranged sequentially. It is a collection of elements of same
data type stored at contiguous memory locations.
The main advantage of the array is random access and cache friendliness. There are mainly
three types of the array:
One Dimensional (1D) Array
Two Dimension (2D) Array
Multidimensional Array
One Dimensional Array:
It is a list of the variable of similar data types.
It allows random access and all the elements can be accessed with the help of their index.
The size of the array is fixed.
For a dynamically sized array, vector can be used in C++.
Representation of 1D array:
Difference Table:
int arr[5]; //an array with int arr[2][5]; //an array with two rows
one row and five columns and five columns will be created.
Example
will be created. a b c d e
{a , b , c , d , e} f g h i j
Applications of Arrays:
2D Arrays are used to implement matrices.
Arrays can be used to implement various data structures like a heap, stack, queue, etc.
They allow random access.
They are cache-friendly.
return 0;
}
Example:
// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };
return 0;
}
Output
Elements in Array: 10 20 100 40 50
Example of 1D Array in C
// C Program to illustrate the use of 1D array
#include <stdio.h>
int main()
{
// 1d array declaration
int arr[5];
return 0;
}
Output
Elements of Array: 1 0 1 4 9
Example of 2D Array in C
// C Program to illustrate 2d array
#include <stdio.h>
int main()
{
printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}
Output
2D Array:
10 20 30
40 50 60
B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A
3D array has exactly three dimensions. It can be visualized as a collection of 2D arrays stacked
on top of each other to create the third dimension.
Syntax of 3D Array in C
array_name [size1] [size2] [size3];
Example of 3D Array
// C Program to illustrate the 3d array
#include <stdio.h>
int main()
{
// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };
// printing elements
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n \n");
}
return 0;
}
Output
10 20
30 40
50 60
00
Inserting an Element into an Array
Insertion is the process of adding a new element at a specified position in the array. Here’s how
we can achieve this in C.
Example Code
#include <stdio.h>
arr[pos] = value;
(*n)++;
int main() {
int n = 4;
int pos = 2;
int value = 3;
return 0;
Explanation
This line includes the standard input-output header file necessary for using printf and other
standard I/O functions.
arr[pos] = value;
(*n)++;
Example Code
#include <stdio.h>
(*n)--;
int main() {
int n = 5;
int pos = 2;
return 0;
Explanation
(*n)--;
Example Code
#include <stdio.h>
printf("\n");
int main() {
int n = 5;
traverse(arr, n);
return 0;
Explanation
1. Traverse Function Definition
void traverse(int arr[], int n) {
printf("\n");
}
return res;
}
int main() {
int arr1[] = {1, 3, 5};
int arr2[] = {2, 4, 6};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
return 0;
}
Output
135246
int main()
{
int arr[] = { 12, 3, 4, 15 };
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
#include <stdio.h>
return max;
}
int main() {
int arr[] = { 10, 324, 45, 90, 9808 };
int n = sizeof(arr) / sizeof(arr[0]);
Sorting: Sorting refers to ordering data in an increasing or decreasing manner according to some
linear relationship among the data items. ordering: arranging items in a sequence ordered by
some criterion; categorizing: grouping items with similar properties.
Bubble sort: Bubble Sort is a comparison based simple sorting algorithm that works by
comparing the adjacent elements and swapping them if the elements are not in the correct
order. It is an in-place and stable sorting algorithm that can sort items in data structures such as
arrays and linked lists.
Bubble Sort Algorithm:
Compare and swap the adjacent elements if they are in the wrong order starting from the
first two elements.
Do that for all elements moving from left to right. We will get the largest element at the
right end.
Start compare and swap again from the start but this time, skip the last element as its
already at correct position.
The second last element will be moved at the right end just before the last element.
Repeat the above steps till all the elements are sorted.
int main() {
int arr[] = { 6, 0, 3, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
Output
0356
Merge sort: It is a comparison-based sorting algorithm that works by dividing the input array
into two halves, then calling itself for these two halves, and finally it merges the two sorted
halves.
It is based on the three principles: divide, conquer and combine which is better implemented
using recursion using two functions:
1. mergeSort() – For Divide
2. merge() – For Conquer and Combine
int main() {
int arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
Output
Given array is
12 11 13 5 6 7
Insertion sort: It is a simple sorting algorithm used to sort a collection of elements in a given
order. It is less efficient on large lists than more advanced algorithms such as quicksort, heap
sort, or merge sort but it is simple to implement and is suitable to sort small data lists.
Insertion Sort Algorithm in C
Start with the second element (index 1) as the key.
Compare the key with the elements before it.
If the key is smaller than the compared element, shift the compared element one position
to the right.
Insert the key where the shifting of elements stops.
Repeat steps 2-4 for all elements in the unsorted part of the list.
int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
return 0;
}
Output
Unsorted array: 12 11 13 5 6
Sorted array: 5 6 11 12 13
Character array and string: String is a sequence of characters that are treated as a single data
item and terminated by a null character '\0'. Remember that the C language does not support
strings as a data type. A string is actually a one-dimensional array of characters in C language.
These are often used to create meaningful and readable programs.
// valid
// Illegal
char str[4];
str = "hello";
Code example:
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);
We can also ue gets function to get the string as input.
char text[20];
gets(text);
printf("%s", text);
C language supports a large number of string handling functions that can be used to carry out
many of the string manipulations. These functions are packaged in the string.h library. Hence,
you must include string.h header file in your programs to use these functions.
The following are the most commonly used string handling functions.
Method Description
There are many more String functions, but in this tutorial we will learn how to use the above
mentioned string functions.
1. strcat() function
Syntax is:
strcat("hello", "world");
strcat() will add the string "world" to "hello" i.e ouput = helloworld.
int j = strlen("studytonight");
printf("%d %d",j,i);
12 -1
3. strcpy() function
It copies the second string argument to the first string argument.
#include<stdio.h>
#include<string.h>
int main()
strcpy(s1, "StudyTonight");
strcpy(s2, s1);
printf("%s\n", s2);
return(0);
StudyTonight
4. strrev() function:
It is used to reverse the given string expression.
#include <stdio.h>
int main()
{
char s1[50];
gets(s1);
return(0);
Example:
#include <stdio.h>
int main()
{
char ch1 = 125, ch2 = 10;
printf("%d\n", ch1);
return 0;
Output
-121
y
ex.
#include <stdio.h>
int main()
char a = 'A';
char b = 'B';
return 0;
Output
a=A
b=B
a+b=â
String handling function: The C string functions are built-in functions that can be used for
various operations and manipulations on strings. These string functions make it easier to perform
tasks such as string copy, concatenation, comparison, length, etc. The <string.h> header file
contains these string functions.
strcpy() Copies a string from the source to the destination. strcpy(dest, src);
sprintf(s, format,
Format a string and store it in a string buffer.
sprintf() …);
Applications of pointers: Pointers in C are variables that are used to store the memory address
of another variable. Pointers allow us to efficiently manage the memory and hence optimize
our program.
C Pointers Application
The following are some major applications of pointers in the C programming language:
1. Passing Arguments by Reference
Passing arguments by reference serves two purposes:
i.) to modify the variable in another function.
Example
The below example demonstrates the use of pointers by swapping two numbers.
// C program to demonstrate that we can change
// local values of one function in another using pointers.
#include <stdio.h>
int main()
{
int x = 10, y = 20;
swap(&x, &y);
printf("%d %d\n", x, y);
return 0;
}
Output
20 10
ii.) For Efficiency Purpose
Example
The below example demonstrates the use of pointers to write efficient code.
#include <stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
printArray(arr, 5);
return 0;
}
Output
12345
Note: Passing large structure without reference would create a copy of the structure (hence
wastage of space).
2. For Accessing Array Elements
Compiler internally uses pointers to access array elements. We can also use these pointers to
access and modify the elements of the given array.
Example
The below example demonstrate the use of pointers to access elements of an array.
// C program to demonstrate that compiler
// internally uses pointer arithmetic to access
// array elements.
#include <stdio.h>
int main()
{
int arr[] = { 100, 200, 300, 400 };
return 0;
}
Output
300 300
3. To Return Multiple Values
The functions in C can only return a single value, but we can use pointers to return multiple
values from a C function.
Example
The below example demonstrates the use of pointers to return square and square root of
numbers using pointers.
// C program to demonstrate that using a pointer
// we can return multiple values.
#include <math.h>
#include <stdio.h>
int main()
{
int n = 100;
int sq;
double sq_root;
fun(n, &sq, &sq_root);
#include <stdio.h>
#include <stdlib.h>
int* createArr(int n)
{
int* arr = (int*)(malloc(n * sizeof(int)));
return arr;
}
int main()
{
int* pt = createArr(10);
return 0;
}
In C programming, you can pass an entire array to functions. Before we learn that, let's see how
you can pass individual elements of an array to functions.
int main() {
int ageArray[] = {2, 8, 4, 12};
Output
Here, we have passed array parameters to the display() function in the same way we pass
variables to a function.
We can see this in the function definition, where the function parameters are individual
variables:
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
return sum;
}
Run Code
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(num);