0% found this document useful (0 votes)
7 views

Module 4 & 5

The document provides a comprehensive overview of arrays in C, including their declaration, initialization, types (one-dimensional and multidimensional), and properties. It also discusses the advantages and disadvantages of using arrays, along with a brief introduction to strings and pointers in C programming. Additionally, it covers key concepts such as memory management, pointer operations, and the differences between character arrays and string literals.
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)
7 views

Module 4 & 5

The document provides a comprehensive overview of arrays in C, including their declaration, initialization, types (one-dimensional and multidimensional), and properties. It also discusses the advantages and disadvantages of using arrays, along with a brief introduction to strings and pointers in C programming. Additionally, it covers key concepts such as memory management, pointer operations, and the differences between character arrays and string literals.
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/ 40

Arrays

1
Array in C
Array in C 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.

Dept. of Mechanical Engineering 2


Array in C
Syntax of Array Declaration

data_type array_name [size];


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

Dept. of Mechanical Engineering 3


Array in C

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

Dept. of Mechanical Engineering 4


Array Initialization

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

Example:

Int arr[] = {1,2,3,4,5};

Dept. of Mechanical Engineering 5


Array Initialization
// C Program to demonstrate array initialization
#include <stdio.h>

int main()
{

// array initialization using initialier 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;
}
Dept. of Mechanical Engineering 6
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.

Example:
array_name [index];

Dept. of Mechanical Engineering 7


Types of Array in C
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 in C


The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.

Syntax of 1D Array in C
array_name [size];

Dept. of Mechanical Engineering 8


Array of Characters (Strings)

In C, we store the words, i.e., a sequence of characters in the form of an array of characters terminated by a
NULL character. These are called strings in C language.

// C Program to illustrate strings


#include <stdio.h>
int main()
{
// creating array of character
char arr[6] = { 'G', 'e', 'e', 'k', 's', '\0' };

// printing string
int i = 0;
while (arr[i]) {
printf("%c", arr[i++]);
}
return 0;
}
Dept. of Mechanical Engineering 9
2. Multidimensional Array in C

Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of the
popular multidimensional arrays are 2D arrays and 3D arrays.

Dept. of Mechanical Engineering 10


Two Dimensional Array in C
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be
represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database
lookalike data structure. It provides ease of holding the bulk of data at once which can be passed to any number of
functions wherever required

Dept. of Mechanical Engineering 11


Declaration of two dimensional Array in C

Syntax:
data_type array_name[rows][columns];

Example
int twodimen[4][3];

Initialization of an array:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Dept. of Mechanical Engineering 12


Two Dimensional Array Example

Example

1.#include<stdio.h>
2.int main(){
3.int i=0,j=0;
4.int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5.//traversing 2D array
6.for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10.}//end of i
11.return 0;
12.}

Dept. of Mechanical Engineering 13


2D array example: Storing elements in a matrix and printing it.
1.#include <stdio.h>
2.void main ()
3.{
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. } Dept. of Mechanical Engineering 14
22.}
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];

Dept. of Mechanical Engineering 15


Properties of Arrays in C
It is very important to understand the properties of the C array so that we can avoid bugs while using it.
1. Fixed Size
The array in C 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 in C language. It means that the index of the first element of the array
will be 0 and the last element will be N – 1.

Dept. of Mechanical Engineering 16


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 in C which is also the reason why random access is possible in the array.
6. Random Access
The array in C provides random access to its element i.e we can get to a random element at any index of the
array in constant time complexity just by using its index number.
7. No Index Out of Bounds Checking
There is no index out-of-bounds checking in C/C++, for example, the following program compiles fine but
may produce unexpected output when run.

Dept. of Mechanical Engineering 17


Advantages of Array in C
The following are the main advantages of an array:
1.Random and fast access of elements using the array index.
2.Use of fewer lines of code as it creates a single array of multiple elements.
3.Traversal through the array becomes easy using a single loop.
4.Sorting becomes easy as it can be accomplished by writing fewer lines of code.

Disadvantages of Array in C
1.Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked
list, an array in C is not dynamic.
2.Insertion and deletion of elements can be costly since the elements are needed to be rearranged after insertion
and deletion.
Dept. of Mechanical Engineering 18
Strings in C
A String in C programming 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 in C is terminated with a unique character ‘\0’.

Dept. of Mechanical Engineering 19


C String Declaration Syntax

char string_name[size];

C String Initialization

1. Assigning a String Literal without Size

char str[] = "GeeksforGeeks";

2. Assigning a String Literal with a Predefined Size

char str[50] = "GeeksforGeeks";

Dept. of Mechanical Engineering 20


3. Assigning Character by Character with Size

We can also assign a string character by character. But we should remember to set the end character as ‘\0’ which is a
null character.

char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

4. Assigning Character by Character without Size

char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

Dept. of Mechanical Engineering 21


C String Example
// C program to illustrate strings

#include <stdio.h>
#include <string.h>

int main()
{
// declare and initialize string
char str[] = "Geeks";

// print string
printf("%s\n", str);

int length = 0;
length = strlen(str);

// displaying the length of string


printf("Length of string str is %d", length);

return 0;
}
Dept. of Mechanical Engineering 22
C String Length
The length of the string is the number of characters present in the string except for the NULL character. We can
easily find the length of the string using the loop to count the characters from the start till the NULL character is
found.

Dept. of Mechanical Engineering 23


Passing Strings to Function
As strings are character arrays, we can pass strings to functions in the same way we pass an array to a
function. Below is a sample program to do this:

// C program to illustrate how to


// pass string to functions
#include <stdio.h>

void printStr(char str[]) { printf("String is : %s", str); }

int main()
{
// declare and initialize string
char str[] = "GeeksforGeeks";

// print string by passing string


// to a different function
printStr(str);

return 0;
} Dept. of Mechanical Engineering 24
Difference between char array and string literal

There are two main differences between char array and literal.

•We need to add the null character '\0' at the end of the array by ourself whereas, it is appended internally
by the compiler in the case of the character array.

•The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.

Dept. of Mechanical Engineering 25


Scansets in C
scanf family functions support scanset specifiers which are represented by %[]. Inside scanset, we can
specify single character or range of characters. While processing scanset, scanf will process only those
characters which are part of scanset. We can define scanset by putting characters inside square brackets.

scansets are case-sensitive.


We can also use scanset by providing comma in between the character you want to add.
example: scanf(%s[A-Z,_,a,b,c]s,str);
This will scan all the specified character in the scanset.

Dept. of Mechanical Engineering 26


/* A simple scanset example */
#include <stdio.h>

int main(void)
{
char str[128];

printf("Enter a string: ");


scanf("%[A-Z]s", str);

printf("You entered: %s\n", str);

return 0;
}

Dept. of Mechanical Engineering 27


Pointers

Dept. of Mechanical Engineering 28


C Pointers
A pointer is a variable that stores the memory address of another variable. Instead of holding a direct
value, it holds the address where the value is stored in memory. There are 2 important operators that
we will use in pointers concepts i.e.
•Dereferencing operator(*) used to declare pointer variable and access the value stored in the address.
•Address operator(&) used to returns the address of a variable or to access the address of a variable to
a pointer.

Dept. of Mechanical Engineering 29


#include <stdio.h>
int main()
{
The Value of Variable m is: 100
The Memory Address of Variable m is: 0x7ffee1eea79c
// taking an integer variable The Memory Address of Variable m is using ptr: 0x7ffee1eea79c
int m = 100;

// pointer variable ptr that stores


// the address of variable m
int *ptr = &m;
// printing the value of variable m
printf("The Value of Variable m is: %d\n", m);

// printing the memory address of variable m


// in hexadecimal format
printf("The Memory Address of Variable m is: %p\n", &m);
// printing the value of ptr i.e.
// printing the memory address of variable m
// in hexadecimal format using pointer variable
printf("The Memory Address of Variable m is using ptr: %p\n", ptr);

return 0;
} Dept. of Mechanical Engineering 30
A. Pointer Declaration
To declare a pointer, we use the (*) dereference operator before its name. In pointer declaration, we only declare the
pointer but do not initialize it.

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

Note: We can also declare and initialize the pointer in a single step. This is called pointer definition.

C. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We
use the same (*) dereferencing operator that we used in the pointer declaration.

Dept. of Mechanical Engineering 31


Important Points:

•%p format specifier is used to print the address stored in pointer variables.

•Printing a pointer with %d format specifier may result in a warning or undefined behaviour because the size of a
pointer (usually 4 or 8 bytes) may not match that of an integer.

•The memory address format will always be in hexadecimal format(starting with 0x).

•C does not use the term “reference” explicitly (unlike C++), “referencing” in C usually refers to obtaining the address
of a variable using the address operator (&).
•Pointers are essential for dynamic memory allocation, providing control over memory usage with functions
like malloc, calloc, and free.

Dept. of Mechanical Engineering 32


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.

Dept. of Mechanical Engineering 33


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.
•Uninitialized pointers might cause a segmentation fault.

Dept. of Mechanical Engineering 34


Structures

Dept. of Mechanical Engineering 35


The structure in C is a user-defined data type that can be used to group items of
possibly different types into a single type.

The struct keyword is used to define the structure in the C programming language.

The items in the structure are called its member and they can be of any valid data
type. Additionally, the values of a structure are stored in contiguous memory
locations

Dept. of Mechanical Engineering 36


Create a Structure

You can create a structure by using the struct keyword and declare each of its members
inside curly braces:

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon

Dept. of Mechanical Engineering 37


To access the structure, you must create a variable of it.
Use the struct keyword inside the main() method, followed by the name of the structure
and then the name of the structure variable:

struct myStructure {
int myNum;
char myLetter;
};

int main() {
struct myStructure s1;
return 0;
}

Dept. of Mechanical Engineering 38


Access Structure Members
To access members of a structure, use the dot syntax (.):

// Create a structure called myStructure


struct myStructure {
int myNum;
char myLetter;
};

int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


s1.myNum = 13;
s1.myLetter = 'B';

// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);

return 0;
} Dept. of Mechanical Engineering 39
Dept. of Mechanical Engineering 40

You might also like