0% found this document useful (0 votes)
14 views27 pages

Module03 DerivedDataTypes

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

Module 3: Derived data types

Arrays - declaration, initialization and access of one-dimensional and two-dimensional arrays.


programs using one- and two-dimensional arrays, sorting and searching arrays. Strings:
Declaring and initializing string variables, reading strings from terminal, writing strings to
screen, Arithmetic operations on characters, String handling functions - strlen, strcmp, strcpy,
strstr and strcat; Character handling functions - toascii, toupper, tolower, isalpha, isnumeric;
Mathematical functions Pointers: Understanding pointers, accessing the address of a variable,
declaring and initializing pointers, accessing a variable through its pointer, pointer expression,
pointer increments and scale factor, pointers and arrays, pointer and strings.

ARRAYS:
 An array in C is a fixed-size collection of similar data items stored in contiguous
memory locations.
 Array is one of the most used data structures in C programming. It is a simple
and fast way of storing multiple values under a single name.
 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.

Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit.

Array Declaration
 We can declare an array by specifying its name, the 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.


NOTE:
 Arrays are static in nature, i.e., they are allocated memory at the compile time.

Example of Array Declaration:

// C Program to illustrate the array declaration


#include <stdio.h>

int main()
{
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];
return 0;
}

Array Initialization
 Initialization in C is the process to assign some initial value to the variable.
When the 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 b a comma.

data_type array_name [size] = {value1, value2, ... valueN};


2. Array Initialization with 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.

data_type array_name[] = {1,2,3,4,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.
Example:
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Example of Array Initialization

// C Program to demonstrate array initialization


#include <stdio.h>

int main()
{

// array initialization using initializer list


int arr[5] = { 10, 20, 30, 40, 50 };

// array initialization using initializer list without


specifying size
int arr1[] = { 1, 2, 3, 4, 5 };

// array initialization using for loop


float arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = (float)i * 2.1;
}
return 0;
}
Access Array Elements
We can access any element of an array in C using the array subscript operator [ ] and
the index value i of the element.
Syntax:
array_name [index];
NOTE:
The 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 1: Array Input/Output
// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array

#include <stdio.h>

int main() {

int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");


// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
Output

Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

Example 2: Calculate Average


// Program to find the average of n numbers using arrays
#include <stdio.h>
int main() {
int marks[10], i, n;
double sum = 0;
double average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i < n; ++i) {
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum =sum+marks[i];
}
average = sum / n;
printf("Average = %.2lf", average);
return 0;
}

Output

Enter number of elements: 5


Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39.60
Types of Array
There are two types of arrays based on the number of dimensions it has. They are
as follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays
1. One Dimensional Array
 The One-dimensional arrays, also known as 1-D arrays .Those arrays that
have only one dimension.
 Syntax of 1D Array
data_type array_name [size];
2.Multidimensional Array
 A multidimensional array is an array with more than one dimension,
allowing you to create complex data structures to store and manipulate data
efficiently.
 Some of the popular multidimensional arrays are 2D arrays and 3D arrays.
1. Two-Dimensional Array
 A Two-Dimensional array or 2D array in C is an array that has exactly two
dimensions.
 Two Dimensional Arrays can be thought of as an array of arrays
 A 2D array is also known as a matrix (a table of rows and columns).
 They can be visualized in the form of rows and columns organized in a
two-dimensional plane.

 Syntax of 2D Array
data_type array_name[size1][size2];
Here,
size1: Size of the first dimension.
size2: Size of the second dimension.
Declaration of two dimensional Array
data_type array_name[i][j];
Here i and j are the size of the two dimensions, i.e., i denotes the number of rows
while j denotes the number of columns.
Example:
int A[10][20];
Here we declare a two-dimensional array, named A, which has 10 rows and 20
columns.
Initialization of 2D Array in C
We can initialize a two dimensional array in any one of the following two ways:
Method 1
To initialize a two dimensional array of size x * y, without using any nested
brace, we can use the syntax below.
data_type Arr[x][y] = {element 1, element 2, ... element xy};
Example:
int A[2][3] = {3, 2, 1, 8, 9, 10}
Method 2
Two dimensional array in C can also be initialized using nested braces, which
makes the visualization of each row and column a bit more easier.
The syntax is as follows-
data_type Arr[x][y] ={{ele 1, ele 2, .. ele y} ,{......},{...,ele xy-1, ele xy}};

Example
int A[2][3] = {{3, 2, 1}, {8, 9, 10}};

// C Program to illustrate 2d array


#include <stdio.h>
int main()
{
// declaring and initializing 2d array
int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
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

Properties of Arrays
It is very important to understand the properties of the array so that we can avoid
bugs while using it.
1. Fixed Size
The array is a fixed-size collection of elements. The size of the array must be
known at the compile time and it cannot be changed once it is declared.
2. Homogeneous Collection
We can only store one type of element in an array. There is no restriction on the
number of elements but the type of all of these elements must be the same.
3. Indexing in Array
The array index always starts with 0 . It means that the index of the first element
of the array will be 0 and the last element will be N – 1.
4. Dimensions of an Array
A dimension of an array is the number of indexes required to refer to an element
in the array. It is the number of directions in which you can grow the array size.
5. Contiguous Storage
All the elements in the array are stored continuously one after another in the
memory. It is one of the defining properties of the array which is also the reason
why random access is possible in the array.
6. Random Access
The array provides random access to its element that is we can get to a random
element at any index of the array in constant time complexity just by using its
index number.
Example : Sum of two matrices

// C program to find the sum of two matrices of order 2*2

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}
OUTPUT:

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0
SORTING:

 Bubble Sort is a simple sorting algorithm commonly used to sort elements in a list or array
 It works by repeatedly comparing adjacent elements and swapping them if they are in the
wrong order.
 The algorithm iterates through the list multiple times until no more swaps are needed, resulting
in a sorted sequence.

Example: Sorting an array

In the following program, we are using bubble sort method to sort the array in ascending order.

#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
ARRAY TRAVERSAL:
Traversing basically means the accessing the each and every element of the array at least once.
Traversing is usually done to be aware of the data elements which are present in the array.

A program to traverse or read a 1-D array


#include<stdio.h>
#include<conio.h>
void main()
{
int a[7], i=0;
clrscr();
printf("Enter the elements of the array :");
for (i=0;i<=6 ;i++ )
{
scanf("%d\n", &a[i]); /* taking input array from the user */
}
printf("\nThe elements of the array you have enetered are as follows :")
for(i=0; i<=6; i++)
{
printf("%d", a[i]); /* printing the array elements or traversing the array */
}
getch();
}

Search an element in an Array


Searching is the process of finding the location of the specified element in a list. The specified element
is often called the ‘search key’. If the process of searching finds a match of the search key with a list
element value, the search said to be successful, otherwise it is unsuccessful. The most commonly used
search techniques are:- sequential search ,Binary search
#include <stdio.h>

#define MAX_SIZE 100 // Maximum array size


int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;

/* Input size of array */


printf("Enter size of array: ");
scanf("%d", &size);

/* Input elements of array */


printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter element to search: ");
scanf("%d", &toSearch);

/* Assume that element does not exists in array */


found = 0;

for(i=0; i<size; i++)


{
/* If element is found in array then raise found flag and terminate from loop.*/
if(arr[i] == toSearch)
{
found = 1;
break;
}
}

/* If element is not found in array */


if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array", toSearch);
}

return 0;
}

Enter size of array: 10

Enter elements in array: 10 12 20 25 13 10 9 40 60 5

Enter element to search: 25

25 is found at position 4
Strings :
 In C programming, a string is a sequence of characters terminated with a null character \0
 The C String is stored as an array of characters.
 The difference between a character array and a C string is that the string is terminated with
a unique character ‘\0’.
 Each character in the array occupies one byte of memory, and the last character must always
be 0.

There are two ways to declare a string in c language.

1. By char array
2. By string literal

example of declaring string by char array


1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

While declaring string, size is not mandatory. So we can write the above code as given below:

char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

We can also define the string by the string literal in C language. For example:

char ch[]="javatpoint";
String Initialization:
We can initialize strings in a number of ways.

char c[] = "abcd";


char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Example 1: scanf() to read a string

#include <stdio.h>int main(){


char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Output

Enter name: Dennis Ritchie


Your name is Dennis.

NOTE:
we do not need to use address of (&) operator in scanf() to store a string since string s is an array
of characters and the name of the array, i.e., s indicates the base address of the string (character
array) therefore we need not use & with it.
o Instead of using scanf(), we may use gets() which is an inbuilt function defined in a header
file string.h. The gets() is capable of receiving only one string at a time.

String Input/Output Functions


• C provides two basic ways to read and write strings.
• First, we can read and write strings with the formatted input/output functions, scanf/fscanf and
printf/fprintf.
• Second, we can use a special set of string-only functions, get string (gets/fgets) and put string (
puts/fputs )

gets() Function:
The gets function is used to read a line of text from the standard input (usually the keyboard)
and stores it as a string.
It reads characters from the standard input until a newline character ('\n') is encountered or the
end-of-file is reached.
char str[50];
printf("Enter a string: ");
gets(str); // Unsafe! Don't use gets.
printf("You entered: %s\n", str);

puts() Function:
The puts function is used to write a string to the standard output (usually the console).
It appends a newline character ('\n') after the string, automatically moving the cursor to the
next line.
char str[] = "Hello, World!";
puts(str);
Sample Program
#include <stdio.h>
int main() {
char str[50];
// Reading a string using gets (unsafe, avoid using gets)
printf("Enter a string: ");
gets(str);
printf("You entered: %s\n", str);
// Writing a string using puts
puts("Hello, World!");
return 0;
}

ARITHEMETIC OPERATIONS ON CHARACTERS:


 Character arithmetic is used to implement arithmetic operations like addition and subtraction
on characters in C language.
 character range is between -128 to 127 or 0 to 255
 It is used to manipulate the strings.
 When the characters are used with the arithmetic operations, it converts them into integer
value automatically i.e. ASCII value of characters.
include <stdio.h>
int main(){
char s = 'm';
char t = 'z' - 'y';

printf("%d\n", s);
printf("%c\n", s);
printf("%d\n", (s+1));
printf("%c\n", (s+1));
printf("%d\n", (s-1));
printf("%c\n", (s-1));
printf("%d\n", t);
// printf("%c", t);

return 0;
}

Output

109
m
110
n
108
l
1
// C program to demonstrate character arithmetic.
#include <stdio.h>
int main()
{
char ch1 = 125, ch2 = 10;
ch1 = ch1 + ch2;
printf("%d\n", ch1);
printf("%c\n", ch1 - ch2 - 4);
return 0;
}
Output
-121
y
STRING HANDLING FUNCTIONS
The C string functions are built-in functions that can be used for various operations and
manipulations on strings.
These string functions can be used to perform tasks such as string copy, concatenation,
comparison, length, etc.
The <string.h> header file contains these string functions.

String Functions in C
Some of the commonly used string functions in C are as follows:

1. strcat() Function

The strcat() function in C is used for string concatenation. It will append a copy of the source
string to the end of the destination string.

// C Program to illustrate the strcat function


#include <stdio.h>
int main()
{
char dest[50] = "This is an";
char src[50] = " example";
printf("dest Before: %s\n", dest);
strcat(dest, src);
printf("dest After: %s", dest);
return 0;
}
strncat()
This function is used for string handling. This function appends not more than n characters from
the string pointed to by src to the end of the string pointed to by dest plus a terminating Null-
character.

strlen() Function

The strlen() function calculates the length of a given string. It doesn’t count the null character
‘\0’.
// C program to demonstrate the strlen() function
#include <stdio.h>
#include <string.h>

int main()
{
char str[] = "GeeksforGeeks";
int length = strlen(str);
// Print the length of the string
printf("String: %s\n", str);
printf("Length: %d\n", length);
return 0;
}
OUTPUT:
String: GeeksforGeeks
Length: 13

3. strcmp() Function

The strcmp() is a built-in library function in C. This function takes two strings as arguments and
compares these two strings lexicographically.
Return Value
 If str1 is less than str2, the return value is less than 0.
 If str1 is greater than str2, the return value is greater than 0.
 If str1 is equal to str2, the return value is 0.
strncmp()
This function lexicographically compares the first n characters from the two null-terminated
strings and returns an integer based on the outcome.

4. strcpy

The strcpy() is a standard library function in C and is used to copy one string to another. In C, it
is present in <string.h> header file.
// C program to illustrate the use of strcpy()
#include <stdio.h>
#include <string.h>
int main()
{
// defining strings
char source[] = "GeeksforGeeks";
char dest[20];
// Copying the source string to dest
strcpy(dest, source);
// printing result
printf("Source: %s\n", source);
printf("Destination: %s\n", dest);
return 0;
}
Output
Source: GeeksforGeeks
Destination: GeeksforGeeks

6. strstr()

The strstr() function in C is used to search the first occurrence of a substring in another string.

Return Value
 If the s2 is found in s1, this function returns a pointer to the first character of the s2 in s1,
otherwise, it returns a null pointer.
 It returns s1 if s2 points to an empty string.
// C program to demonstrate the strstr() function
#include <stdio.h>
#include <string.h>
int main()
{
// Define a string 's1' and initialize it with
// "GeeksforGeeks"
char s1[] = "GeeksforGeeks";
// Define a string 's2' and initialize it with "for"
char s2[] = "for";
// Declare a pointer 'result' to store the result of
// strstr()
char* result;
// Find the first occurrence of 's2' within 's1' using
// strstr() function and assign the result to 'result'
result = strstr(s1, s2);
if (result != NULL) {
// If 'result' is not NULL, it means the substring
// was found, so print it
printf("Substring found: %s\n", result);
}
else {
// If 'result' is NULL, it means the substring was not found, so print message
printf("Substring not found.\n");
}
return 0;
}
OUTPUT:
Substring found: forGeeks

CHARACTER HANDLING FUNCTIONS:


In C, character handling functions are part of the standard library ctype.h and string.h. These
functions are used for performing operations on individual characters or strings. Here are some
commonly used character handling functions in C:

1.isalpha:Checks if a character is an alphabet (A-Z or a-z).


2.isdigit:Checks if a character is a digit (0-9).
3.isalnum:Checks if a character is an alphanumeric character (alphabet or digit).
4.tolower:Converts an uppercase alphabet to a lowercase alphabet.
5.toupper:Converts a lowercase alphabet to an uppercase alphabet.
In C programming, mathematical functions are part of the standard library math.h. These
functions allow you to perform various mathematical operations. Here are some commonly
used mathematical functions in C:

Mathematical Functions:
In C programming, mathematical functions are part of the standard library math.h. These
functions allow you to perform various mathematical operations. Here are some commonly
used mathematical functions in C:
1.Basic Arithmetic Functions:
+, -, *, /: Basic arithmetic operators for addition, subtraction, multiplication, and division.
2.Power and Exponential Functions:
 pow(x, y): Raises x to the power of y.
 sqrt(x): Calculates the square root of x.
 exp(x): Calculates the exponential (e^x) of x.
 log(x): Calculates the natural logarithm of x (base e).
3.Trigonometric Functions:
 sin(x), cos(x), tan(x): Sine, cosine, and tangent of x (in radians).
4.Rounding Functions:

 ceil(x): Rounds x up to the nearest integer.


 floor(x): Rounds x down to the nearest integer.
 round(x): Rounds x to the nearest integer.

C Pointers

 Pointers are one of the core components of the C programming language. A


pointer can be used to store the memory address of other variables, functions, or
even other pointers.
 A pointer is defined as a derived data type that can store the address of other C
variables or a memory location. We can access and manipulate the data stored in
that memory location using pointers.

Syntax of pointers

The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.
datatype * ptr;
 ptr is the name of the pointer.
 datatype is the type of data it is pointing to.

Pointer Declaration

In pointer declaration, we only declare the pointer but do not initialize it. To declare a
pointer, we use the ( * ) dereference operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is not
initialized. Such pointers are called wild pointers.
Pointer Initialization

Pointer initialization is the process where we assign some initial value to the pointer
variable. We generally use the ( & ) address of operator to get the memory address of a
variable and then store it in the pointer variable.

Example

int var = 10;


int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is called
pointer definition as the pointer is declared and initialized at the same time.

Pointer Expressions in C

1. Declaration and Initialization:


int *ptr;: Declares a pointer variable ptr that can point to an integer.
int x = 10; int *ptr = &x;: Initializes ptr with the address of the integer variable x.
2. Dereferencing:
int value = *ptr;: Retrieves the value stored at the memory address pointed to by ptr.
3. Assignment:
*ptr = 20;: Assigns a new value (20 in this case) to the memory location pointed to by ptr.
4. Pointer Arithmetic:
ptr++; or ptr--;: Increments or decrements the pointer to the next or previous memory
location.
ptr = ptr + 2; or ptr = ptr - 1;: Moves the pointer by a specified number of elements.
Useful for navigating arrays.
5. Array Access:
int arr[5]; int *ptr = &arr[0];: Pointers can be used to iterate through array elements.
6. Scale Factor:
The compiler automatically accounts for the size of the data type when you perform
pointer arithmetic.

C Pointers and Arrays

In C programming language, pointers and arrays are closely related. An array name acts
like a pointer constant. The value of this pointer constant is the address of the first
element. For example, if we have an array named val then val and &val[0] can be used
interchangeably.
If we assign this value to a non-constant pointer of the same type, then we can access the
elements of the array using this pointer.
Accessing Array Elements using Pointer with Array

Table list the differences between an array and a pointer:

Pointer Array

A pointer is a derived data type that can An array is a homogeneous collection of


store the address of other variables. items of any type such as int, char, etc.

Pointers are allocated at run time. Arrays are allocated at runtime.

An array is a collection of variables of the


The pointer is a single variable.
same type.

Dynamic in Nature Static in Nature.

Uses of Pointers in C
The C pointer is a very powerful tool that is widely used in C programming to perform
various useful operations. It is used to achieve the following functionalities in C:
 Pass Arguments by Reference
 Accessing Array Elements
 Return Multiple Values from Function
 Dynamic Memory AllocatioN
 Implementing Data Structures
 In System-Level Programming where memory addresses are useful.
 In locating the exact value at some memory location.
 To avoid compiler confusion for the same variable name.

Advantages of Pointers
Following are the major advantages of pointers in C:
 Pointers are used for dynamic memory allocation and deallocation.
 An Array or a structure can be accessed efficiently with pointers
 Pointers are useful for accessing memory locations.
 Pointers are used to form complex data structures such as linked lists, graphs,
trees, etc.
 Pointers reduce the length of the program and its execution time as well.

Disadvantages of Pointers
Pointers are vulnerable to errors and have following disadvantages:
 Memory corruption can occur if an incorrect value is provided to pointers.
 Pointers are a little bit complex to understand.
 Pointers are majorly responsible for memory leaks in C.
 Pointers are comparatively slower than variables in C.

You might also like