Ip U-Iii
Ip U-Iii
MODULE – III
Arrays
Definition:
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc.
Properties of Array:
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int = 2
bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.
Advantage of Array:
1. Code Optimization: Less code to the access the data.
2. Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.
3. Easy to sort data: To sort the elements of array, we need a few lines of code only.
4. Random Access: We can access any element randomly using the array.
Disadvantage of Array:
Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList.
Array Types:
Single-Dimensional Arrays (One-Dimensional Arrays)
Multi-Dimensional Arrays (Two-Dimensional Arrays)
One-Dimensional Arrays
Declaration of an Array:
We can declare an array in the c language in the following way.
data_type array_name[array_size];
For example:
int arr[10];
Here int is the data type, arr is the name of the array and 10 is the size of array. It
means array arr can only contain 10 elements of int type. Index of an array starts from 0 to
size-1 i.e first element of arr array will be stored at arr[0] address and last element will occupy
arr[9].
1
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
Initialization of Array:
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
In such case, there is no requirement to define the size. So it may also be written as
the following code.
int marks[]={20,30,40,50,60};
2
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
int marks[5] = {20, 30, 40, 50, 60}; // declaration and initialization
of array traversal of array
for (i = 0; i < 5; i++)
{
printf("%d \n", marks[i]);
}
return 0;
}
Output:
20
30
40
50
60
int i;
int arr[5];
for(i=0; i<5; i++)
{
printf("Index -> %d : ",i);
scanf("%d", &arr[i]);
}
printf("\nElements in array are: ");
for(i=0; i<5; i++)
{
printf("%d \t", arr[i]);
}
}
Output:
Index -> 0 : 20
Index -> 1 : 30
Index -> 2 : 40
Index -> 3 : 50
Index -> 4 : 60
3
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
int i, j, temp;
int a[10] = {12, 9, 6, 104, 32, 44, 14, 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]);
}
}
Output:
Printing Sorted Element List ...
6
9
12
14
23
32
34
44
78
104
4
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
if (flag == 0) {
printf("Element not found in the array.\n");
}
}
Output:
Enter the element to search: 54
Element found at position: 1
Two-Dimensional Arrays
The two dimensional array in C language is represented in the form of rows and
columns, also known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.
Declaration of two dimensional Array:
The syntax to declare the 2D array is given below.
Syntax:
data_type array_name[rows][columns];
or
data_type array_name[size1][size2];
Example 1:
int twodimen[4][3];
Example 2:
int a[3][4];
Initialization of 2D Array:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
{
for (j = 0; j < 3; j++)
{
printf("arr[%d] [%d] = %d \n", i, j, arr[i][j]);
} // end of j
} // end of i
return 0;
}
Output:
arr[0] [0] = 1
arr[0] [1] = 2
arr[0] [2] = 3
arr[1] [0] = 2
arr[1] [1] = 3
arr[1] [2] = 4
arr[2] [0] = 3
arr[2] [1] = 4
arr[2] [2] = 5
arr[3] [0] = 4
arr[3] [1] = 5
arr[3] [2] = 6
6
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
void main()
{
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
int c[3][3];
int i, j, k, m = 3, n = 3;
printf("\nThe multiplication of two matrics");
for (i = 0; i < m; i++)
{
printf("\n");
for (j = 0; j < n; j++)
{
c[i][j] = 0;
for (k = 0; k < n; k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
printf("\t%d", c[i][j]);
}
}
}
Output:
The multiplication of two matrics
1 2 3
4 5 6
7 8 9
STRINGS
In „C‟ language the group of characters, digits, and symbols enclosed within double
quotation (" ") marks are called as string otherwise a string is an array of characters and
terminated by NULL character which is denoted by the escape sequence „\0‟.
Declaration of String:
C does not support string as a data type. However, it allows us to represent strings as
character arrays. In C, a string variable is any valid C variable name and it is always declared
as an array of characters.
The general form of declaration of a string variable is,
Syntax:
char string_name[size];
The size determines the number of characters in the string name.
Note: In declaration of string size must be required to mention otherwise it gives an error.
Ex:
char str[]; // Invalid
char str[0]; // Invalid
7
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
Here, the string variable a can hold maximum of 9 characters including NULL(\0)
character.
Initializing Array String:
Syntax:
char string_name[size]={“string” };
Note: In Initialization of the string if the specific number of character is not initialized it then
rest of all character will be initialized with NULL.
char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
str[3]; ---> NULL
str[4]; ---> NULL
Note: In initialization of the string we cannot initialized more than size of string elements.
Ex: char str[2]={'5','+','A','B'}; // Invalid
Different ways of initialization can be done in various ways:
1. Initializing locations character by character.
2. Partial array initialization.
3. Initialization without size.
4. Array initialization with a string.
Initializing locations character by character
Consider the following declaration with initialization,
char b[9]={„C‟,„O‟,„M‟,„P‟,„U‟,„T‟,„E‟,„R‟};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations
are initialized with the characters in the order specified. The remaining locations are
automatically initialized to null characters.
8
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
The compiler allocates 10 bytes for the variable a ranging from 0 to 9 and initializes
first four locations with the ASCII characters of „R‟, „A‟, „M‟, „A‟. The remaining locations
are automatically filled with NULL characters (i.e.,\0).
9
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
Input Functions:
1. scanf(): Reads input from the standard input (usually the keyboard) and stores it in
variables.
Syntax: int scanf(const char *format, ...);
Example: scanf("%d %f %s", &age, &height, name);
2. getchar(): Reads a single character from the standard input.
Syntax: int getchar(void);
Example: char c = getchar();
10
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
3. getch(): Reads a single character from the standard input without echoing it to the
console.
Syntax: int getch(void); (Note: getch() is not part of the C standard library, but is
available in some implementations like conio.h)
Example: char c = getch();
4. getche(): Reads a single character from the standard input and echoes it to the console.
Syntax: int getche(void); (Note: getche() is not part of the C standard library, but is
available in some implementations like conio.h)
Example: char c = getche();
5. gets(): Reads a string from the standard input until a newline character is encountered.
Syntax: char *gets(char *str);
Example: gets(name); (Note: gets() is deprecated due to security concerns)
Output Functions:
1. printf(): Prints output to the standard output (usually the console).
Syntax: int printf(const char *format, ...);
Example: printf("Hello, %s!", name);
// Using scanf()
printf("Enter your age, height, and name: ");
scanf("%d %f %s", &age, &height, name);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Name: %s\n", name);
// Using getchar()
11
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
// Using getch()
printf("Enter a character (without echo): ");
ch = getch();
printf("You entered: %c\n", ch);
// Using getche()
printf("Enter a character (with echo): ");
ch = getche();
printf("\nYou entered: %c\n", ch);
// Using gets()
printf("Enter your full name: ");
gets(name);
printf("Your full name is: %s\n", name);
// Using putchar()
putchar('\n');
putchar('A');
printf("\n");
// Using putch()
putch('\n');
putch('B');
printf("\n");
// Using puts()
puts("Hello, World!");
return 0;
}
Output:
Enter your age, height, and name: 31 5.6 Srihari
Age: 31
Height: 5.60
Name: Srihari
Enter a character: X
You entered: X
Enter a character (without echo): Y
You entered: Y
Enter a character (with echo): Z
You entered: Z
12
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
B
Hello, World!
int main() {
char ch = 'A';
// Character functions
printf("Is 'A' an alphabet? %d\n", isalpha(ch));
printf("Is 'A' a digit? %d\n", isdigit(ch));
printf("Is 'A' an alphabet or digit? %d\n", isalnum(ch));
printf("Is 'A' in lowercase? %d\n", islower(ch));
printf("Is 'A' in uppercase? %d\n", isupper(ch));
printf("Convert 'A' to lowercase: %c\n", tolower(ch));
printf("Convert 'A' to uppercase: %c\n", toupper(ch));
return 0;
}
Output:
Is 'A' an alphabet? 1
Is 'A' a digit? 0
Is 'A' an alphabet or digit? 1
Is 'A' in lowercase? 0
Is 'A' in uppercase? 1
Convert 'A' to lowercase: a
Convert 'A' to uppercase: A
13
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
Example Program:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char str3[20];
// strlen()
printf("Length of str1: %d\n", strlen(str1));
// strcpy()
strcpy(str3, str1);
printf("Copied string: %s\n", str3);
// strcat()
strcat(str3, str2);
printf("Concatenated string: %s\n", str3);
// strcmp()
if (strcmp(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
// strrev()
strrev(str1);
printf("Reversed str1: %s\n", str1);
// strlwr()
strlwr(str2);
printf("Lowercase str2: %s\n", str2);
// strupr()
strupr(str3);
printf("Uppercase str3: %s\n", str3);
14
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)
return 0;
}
Output:
Length of str1: 5
Copied string: Hello
Concatenated string: HelloWorld
Strings are not equal
Reversed str1: olleH
Lowercase str2: world
Uppercase str3: HELLOWORLD
Arrays of Strings
An array of strings in C is a two-dimensional array of character types. Each String is
terminated with a null character (\0). It is an application of a 2d array.
Using Two-dimensional Arrays:
Creating a String Array is one of the applications of two-dimensional Arrays. To get a
picture of the arrangement, observe the below representation:
For suppose we want to create an Array of 3 Strings of size 5:
Every String in a String Array must terminate with a null Character. It is the property of a
String in C.
Syntax to create a String Array:
char Array[rows][columns] = {"String1", "String2"...};
Example String Array:
Observe that when we assign the number of rows and columns, we need to consider
the Null Character to the length.
#include <stdio.h>
void main()
{
int i;
char Array[3][6] = {"Black", "Blame", "Block"};
printf("String Array: \n");
for (i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}
}
Output:
String Array:
Black
Blame
Block
~ ~ END OF THE UNIT ~ ~
15
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur