Module03 DerivedDataTypes
Module03 DerivedDataTypes
Module03 DerivedDataTypes
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
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.
The size of the above arrays is 5 which is automatically deduced by the compiler.
int main()
{
#include <stdio.h>
int main() {
int values[5];
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
Output
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}};
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
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
OUTPUT:
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.
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.
return 0;
}
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.
1. By char array
2. By string literal
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.
Output
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.
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;
}
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.
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
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:
C 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
Pointer Expressions in C
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
Pointer Array
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.