R22 PPS Unit - 2 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Programming for Problem Solving Notes

UNIT-2
Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of arrays
Strings: Introduction to strings, handling strings as array of characters, basic string functions available in C (strlen, strcat,
strcpy, strstr etc.), arrays of strings
Structures: Defining structures, initializing structures, unions, Array of structures
Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and Structures, Use of Pointers in self referential
structures, usage of self referential structures in linked list (no implementation) Enumeration data type

Arrays
An array in C is a collection of data items of similar data type. One or more values same data type, which may be
primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array. In C,
the type of elements in the array should match with the data type of the array itself.

The size of the array, also called the length of the array, must be specified in the declaration itself. Once declared,
the size of a C array cannot be changed. When an array is declared, the compiler allocates a continuous block of
memory required to store the declared number of elements. Arrays are used to store and manipulate the similar
type of data.

Types of Arrays

There are majorly 3 types of arrays

1. One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array

One-Dimensional Array
Suppose we want to store the marks of 10 students and find the average. We declare 10 different variables to store
10 different values as follows:

int a = 50, b = 55, c = 67, . . . ;


float avg = (float)(a + b + c +. . . ) / 10;

These variables will be scattered in the memory with no relation between them. Importantly, if we want to extend
the problem of finding the average of 100 (or more) students, then it becomes impractical to declare so many
individual variables. To go back to the problem of storing the marks of 10 students and find the average, the
solution with the use of array would be:
#include <stdio.h>
void main(){
int marks[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51};
int i, sum = 0;
float avg;
for (i = 0; i <= 9; i++){
sum += marks[i];

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 1
}
avg = (float)sum / 10;
printf("Average: %f", avg);
}
Output
Average: 52.000000

Array elements are stored in contiguous memory locations. Each element is identified by an index starting with "0".
The lowest address corresponds to the first element and the highest address to the last element.

Declaration of an Array

To declare an array in C, you need to specify the type of the elements and the number of elements to be stored in
it.

Syntax to Declare an Array


type arrayName[size];

The "size" must be an integer constant greater than zero and its "type" can be any valid C data type. There are
different ways in which an array is declared in C.

Example: Declaring an Array in C

In the following example, we are declaring an array of 5 integers and printing the indexes and values of all array
elements:

#include <stdio.h>
void main(){
int arr[5];
int i;
for (i = 0; i <= 4; i++){
printf("a[%d]: %d\n", i, arr[i]);
}
}
Output
a[0]: -133071639
a[1]: 32767
a[2]: 100
a[3]: 0
a[4]: 4096

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 2
Initialization of an Array:

At the time of declaring an array, you can initialize it by providing the set of comma-separated values enclosed
within the curly braces {}.

Syntax to Initialize an Array


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

The following example demonstrates the initialization of an integer array:

// Initialization of an integer array


#include <stdio.h>
void main()
{
int numbers[5] = {10, 20, 30, 40, 50};
int i; // loop counter
printf("The array elements are : ");
for (i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
}
Output
The array elements are : 10 20 30 40 50

Example of Initializing all Array Elements to 0


#include <stdio.h>
void main(){
int arr[5] = {0};
int i;
for(i = 0; i <= 4; i++){
printf("a[%d]: %d\n", i, arr[i]);
}
}
Output
a[0]: 0
a[1]: 0
a[2]: 0
a[3]: 0
a[4]: 0

Getting Size of an Array in C

The compiler allocates a continuous block of memory. The size of the allocated memory depends on the data type
of the array.

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 3
Example: Size of Integer Array

If an integer array of 5 elements is declared, the array size in number of bytes would be "sizeof(int) x 5"

#include <stdio.h>
int main(){
int arr[5] = {1, 2, 3, 4, 5};
printf("Size of array: %ld", sizeof(arr));
return 0;
}
Output
Size of array: 20

The sizeof operator returns the number of bytes occupied by the variable.

Example : Adjacent Address of Array Elements

The size of each int is 4 bytes. The compiler allocates adjacent locations to each element.

#include <stdio.h>
int main(){
int a[] = {1, 2, 3, 4, 5};
int i;

for(i = 0; i < 4; i++){


printf("a[%d]: %d \t Address: %d\n", i, a[i], &a[i]);
}
return 0;
}
Output
a[0]: 1 Address: 2102703872
a[1]: 2 Address: 2102703876
a[2]: 3 Address: 2102703880
a[3]: 4 Address: 2102703884
In this array, each element is of int type. Hence, the 0th element occupies the first 4 bytes 642016 to 19. The
element at the next subscript occupies the next 4 bytes and so on.
Example : Size of Character Array
The length of a "char" variable is 1 byte. Hence, a char array length will be equal to the array size.
#include <stdio.h>
int main(){
char a[] = "Hello";
int i;

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 4
for (i=0; i<5; i++){
printf("a[%d]: %c address: %ld\n", i, a[i], &a[i]);
}
return 0;
}
Output
a[0]: H address: 6422038
a[1]: e address: 6422039
a[2]: l address: 6422040
a[3]: l address: 6422041
a[4]: o address: 6422042
Accessing Array Elements
Each element in an array is identified by a unique incrementing index, stating with "0". To access the element by its
index, this is done by placing the index of the element within square brackets after the name of the array.
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to the "salary".
Example to Access Array Elements in C
The following example shows how to use all the three above-mentioned concepts viz. declaration, assignment, and
accessing arrays.

#include <stdio.h>
int main(){
int n[5]; /* n is an array of 5 integers */
int i, j;
/* initialize elements of array n to 0 */
for(i = 0; i < 5; i++){
n[i] = i + 100;
}
/* output each array element's value */
for(j = 0; j < 5; j++){
printf("n[%d] = %d\n", j, n[j]);
}
return 0;
}
Output
n[0] = 100
n[1] = 101
n[2] = 102
n[3] = 103
n[4] = 104

The index gives random access to the array elements. An array may consist of struct variables, pointers and even
other arrays as its elements.

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 5
Two-Dimensional Array

Multidimensional arrays can be considered as an array of arrays or as a matrix consisting of rows and columns.
Syntax for Declaration of Two-Dimensional Array
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension];

where,
data_type: is a type of data of each array block.
array_name: is the name of the array using which we can refer to it.
sizeof_dimension: is the number of blocks of memory array going to have in the corresponding dimension.

For Example
int nums[5][10];

Initialization of Two-Dimensional Array


A two-dimensional array can be initialized by providing a list of the single-dimensional arrays in proper syntax,

int numbers[5][2] = {
{0, 2, 4, 6, 8},
{1, 3, 5, 7, 9}
};

Arrangement

Accessing Individual Elements of Two-Dimensional Array


The individual element can be accessed by providing both row and column index of the array,
arrayName[rowIndex][columnIndex];

Two-dimensional array example in C


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

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 6
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

Three-dimensional array:
A 3-D Multidimensional array contains three dimensions, so it can be considered an array of two-dimensional
arrays.

Syntax for Declaration of Three-Dimensional Array

data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension][sizeof_3rd_dimension];

where,
data_type: is a type of data of each array block.
array_name: is the name of the array using which we can refer to it.
sizeof_dimension: is the number of blocks of memory array going to have in the corresponding dimension.

For Example
int nums[5][10][2];

Three-dimensional arrays are also a specialized form of a multidimensional array, generally, they are used to
represent three-dimensional coordinates in programming. We could also say that three-dimensional arrays
are an array of two-dimensional arrays.

//Example
int array[5][10][15];

C program to show the concept of a three-dimensional array.

#include <stdio.h>
int main() {
int array[2][2][2];
int i, j, k;
printf("Enter Elements(8) of 3 Dimensional Array: \n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
scanf("%d", & array[i][j][k]);

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 7
}
}
}
printf("Print the Array\n");

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


for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++)
printf("%d ", array[i][j][k]);
printf("\n");
}
}
return 0;
}

Input:

Enter Elements(8) of 3 Dimensional Array:


12345678

Output:
12
34
56
78

Strings
String is a set of characters that are enclosed in double quotes. In the C programming language, strings are
created using one dimension array of character datatype. Every string in C programming language is enclosed
within double quotes and it is terminated with NULL (\0) character. Whenever c compiler encounters a string
value it automatically appends a NULL character (\0) at the end. The formal definition of string is as follows...
In C programming language, there are two methods to create strings and they are as follows...
1. Using one dimensional array of character datatype ( static memory allocation )
2. Using a pointer array of character datatype ( dynamic memory allocation )
Creating String
In C, strings are created as a one-dimensional array of character datatype. We can use both static and dynamic
memory allocation. When we create a string, the size of the array must be one more than the actual number
of characters to be stored. That extra memory block is used to store string termination character NULL (\0).
The following declaration stores a string of size 5 characters.
char str[6] ;
The following declaration creates a string variable of a specific size at the time of program execution.
char *str = (char *) malloc(15) ;
Assigning string value
String value is assigned using the following two methods...
1. At the time of declaration (initialization)
2. After declaraation

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 8
Examples of assigning string value
void main()
{
char str1[6] = "Hello";
char str2[] = "Hello!";
char name1[] = {'j','n','t','u','h'};
char name2[6] = {'j','n','t','u','h'};

char title[20];
*title = "JNTUH HYD CAMPUS";
}

Reading string value from user in C programming language


We can read a string value from the user during the program execution. We use the following two methods...
1. Using scanf() method - reads single word
2. Using gets() method - reads a line of text
Using scanf() method we can read only one word of string. We use %s to represent string in scanf() and printf()
methods.
Examples of reading string value using scanf() method
#include<stdio.h>
#include<conio.h>

void main(){

char name[50];
printf("Please enter your name : ");

scanf("%s", name);

printf("Hello! %s , welcome to btech smart class !!", name);

When we want to read multiple words or a line of text, we use a pre-defined method gets().
The gets() method terminates the reading of text with Enter character.
Examples of reading string value using gets() method
#include<stdio.h>
#include<conio.h>
void main(){
char name[50];
printf("Please enter your name : ");
gets(name);
printf("Hello! %s , welcome to btech smart class !!", name);
}

C Programming language provides a set of pre-definied functions called String Handling Functions to work
with string values. All the string handling functions are defined in a header file called string.h.

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 9
String Handling Functions
C programming language provides a set of pre-defined functions called string handling functions to work with
string values. The string handling functions are defined in a header file called string.h. Whenever we want to
use any string handling function we must include the header file called string.h.
The following table provides most commonly used string handling function and their use...
Function Syntax (or) Example Description

strcpy() strcpy(string1, string2) Copies string2 value into string1

strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string1

strlen() strlen(string1) returns total number of characters in string1

strcat() strcat(string1,string2) Appends string2 to string1

strncat() strncpy(string1, string2, 4) Appends first 4 characters of string2 to string1

strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2; greater than 0 if string1>string2

strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1 and string2

stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignoring case (similar
to strcmpi())

strlwr() strlwr(string1) Converts all the characters of string1 to lower case.

strupr() strupr(string1) Converts all the characters of string1 to upper case.

strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of character 'b' in string1

strstr() strstr(string1, string2) Returns a pointer to the first occurrence of string2 in string1

strrev() strrev(string1) It reverses the value of string1

Example:
#include <stdio.h>
#include <string.h>
void main() {
// Declaration and Initialization
char str1[] = "SCITSKNR cse";
char str2[20];
char search = 'o';

// strlen - String Length


printf("Length of str1: %lu\n", strlen(str1));

// strcpy - String Copy


strcpy(str2, str1);

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 10
printf("After copying, str2: %s\n", str2);

// strcat - String Concatenation


strcat(str2, " welcomes");
printf("After concatenation, str2: %s\n", str2);

// strcmp - String Comparison


int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 is equal to str2\n");
} else if (result < 0) {
printf("str1 is less than str2\n");
} else {
printf("str1 is greater than str2\n");
}

// strchr
char *found = strchr(str1, search);
// Check if the character is found
if (found != NULL) {
printf("'%c' found at position: %ld\n", search, found - str1 + 1);
} else {
printf("'%c' not found in the string.\n", search);
}
}

Output:
Length of str1: 12
After copying, str2: SCITSKNR cse
After concatenation, str2: SCITSKNR cse welcomes
str1 is less than str2
'o' not found in the string.

PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 11

You might also like