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

UNIT-III

The document provides a comprehensive overview of arrays and strings in C programming, including definitions, declarations, initializations, and memory layouts. It explains how to access array elements, different types of arrays, and includes several example programs for reading, printing, and manipulating arrays. Additionally, it outlines the memory layout of C programs, detailing segments such as text, data, stack, and heap.

Uploaded by

loknath4007
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)
4 views

UNIT-III

The document provides a comprehensive overview of arrays and strings in C programming, including definitions, declarations, initializations, and memory layouts. It explains how to access array elements, different types of arrays, and includes several example programs for reading, printing, and manipulating arrays. Additionally, it outlines the memory layout of C programs, detailing segments such as text, data, stack, and heap.

Uploaded by

loknath4007
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/ 17

35

Unit III
Arrays and Strings

Q.1. Define an Array. Explain how to declare and initialize an array.


➔ An array is a variable which can store more than one value of same datatype.
➔ The elements of array stored in continues memory locations.
Declaration of Array:
➔ when we want to create an array, we must know the datatype of values to be stored in that array
and also the number of values to be stored in that array.
➔ We use the following general syntax to create an array...
Syntax: datatype arrayName[ size ] ;
In the above syntax, the datatype specifies the type of values we store in that array and size
specifies the maximum number of values that can be stored in that array.
Example
int a [3] ;
Here, the compiler allocates 6 bytes of memory locations with a single name 'a' and tells the
compiler to store three different integer values (each in 2 bytes of memory).
For the above declaration, the memory is organized as follows...

Initialization of Array:
Syntax for creating an array with size and initial values.
datatype arrayName [ size ] = {value1, value2, ...} ;
Example
int a[5] = {1, 2, 3, 4, 5};
Here, an array ‘a’ stores 5 values.

Syntax for creating an array without size and with initial values
datatype arrayName [ ] = {value1, value2, ...} ;
Example
int a[ ] = {1, 2, 3, 4, 5};
Here, an array ‘a’ stores 5 values.
36

Q.2. Explain how to access elements of an array?


An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array.
Syntax:
arrayName [ indexValue ] ;
Example:
int a[5] = {1, 2, 3}
For the above example the individual elements can be denoted as follows

➔ We can access the elements as follows:


printf(“%d”, a[2]);
Output of the above statement is: 3
➔ We can change the individual elements of array as follows:
a[1] = 100;
➔ Then array elements are:

Q.3. Explain Memory Layout of C Programs?


A typical memory representation of a C program consists of the following sections.
1. Text segment (i.e. instructions)
2. Initialized data segment
3. Uninitialized data segment (bss)
4. Heap
5. Stack
37

A typical memory layout of a running process

1. Text Segment:

➔ A text segment, also known as a code segment or simply as text, is one of the sections of a program
in an object file or in memory, which contains executable instructions.
➔ As a memory region, a text segment may be placed below the heap or stack in order to prevent
heaps and stack overflows from overwriting it.
➔ Usually, the text segment is sharable so that only a single copy needs to be in memory for frequently
executed programs, such as text editors, the C compiler, the shells, and so on. Also, the text segment
is often read-only, to prevent a program from accidentally modifying its instructions.

2. Initialized Data Segment:

➔ Initialized data segment, usually called simply the Data Segment.


➔ A data segment is a portion of the virtual address space of a program, which contains the global
variables and static variables that are initialized by the programmer.
➔ The data segment is not read-only, since the values of the variables can be altered at run time.
➔ This segment can be further classified into the initialized read-only area and the initialized read-
write area.
➔ For instance, the global string defined by char s[] = “hello world” in C and a C statement like int
debug=1 outside the main (i.e. global) would be stored in the initialized read-write area. And a
global C statement like const char* string = “hello world” makes the string literal “hello world” to be
stored in the initialized read-only area and the character pointer variable string in the initialized
read-write area.
➔ Ex: static int i = 10 will be stored in the data segment and global int i = 10 will also be stored in data
segment

3. Uninitialized Data Segment:

➔ Uninitialized data segment often called the “bss” segment, named after an ancient assembler
operator that stood for “block started by symbol.”
➔ Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executing
uninitialized data starts at the end of the data segment and contains all global variables and static
variables that are initialized to zero or do not have explicit initialization in source code.
➔ For instance, a variable declared static int i; would be contained in the BSS segment.
➔ For instance, a global variable declared int j; would be contained in the BSS segment.
38

4. Stack:

➔ The stack area traditionally adjoined the heap area and grew in the opposite direction; when the
stack pointer met the heap pointer, free memory was exhausted. (With modern large address
spaces and virtual memory techniques they may be placed almost anywhere, but they still typically
grow in opposite directions.)
➔ The stack area contains the program stack, a LIFO structure, typically located in the higher parts of
memory. On the standard PC x86 computer architecture, it grows toward address zero; on some
other architectures, it grows in the opposite direction.
➔ A “stack pointer” register tracks the top of the stack; it is adjusted each time a value is “pushed”
onto the stack.
➔ The set of values pushed for one function call is termed a “stack frame”;
➔ A stack frame consists at minimum of a return address.
Stack, where automatic variables are stored, along with information that is saved each time a
function is called.
➔ Each time a function is called, the address of where to return to and certain information about the
caller’s environment, such as some of the machine registers, are saved on the stack.
➔ The newly called function then allocates room on the stack for its automatic variables.
➔ This is how recursive functions in C can work.
➔ Each time a recursive function calls itself, a new stack frame is used, so one set of variables doesn’t
interfere with the variables from another instance of the function.

5. Heap:

➔ Heap is the segment where dynamic memory allocation usually takes place.
➔ The heap area begins at the end of the BSS segment and grows to larger addresses from there.
➔ The Heap area is managed by malloc, realloc, and free, which may use the brk and sbrk system calls
to adjust its size (note that the use of brk/sbrk and a single “heap area” is not required to fulfill the
contract of malloc/realloc/free; they may also be implemented using mmap to reserve potentially
non-contiguous regions of virtual memory into the process’ virtual address space).
➔ The Heap area is shared by all shared libraries and dynamically loaded modules in a process.
39

Q. 4. Write a C program to read and print elements of array.

Program:
#include <stdio.h>
int main()
{
int arr[N];
int i, N;
printf("Enter size of array: ");
scanf("%d", &N);
printf("Enter %d elements in the array : ", N);
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
printf("\nElements in array are: ");
for(i=0; i<N; i++)
{
printf("%d, ", arr[i]);
}
return 0;
}

Output:

Enter size of array: 10


Enter 10 elements in the array : 10
20
30
40
50
60
70
80
90
100
Elements in array are : 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
40

Q . 5 . Write a C program to print all negative elements in an array.

Program:
#include <stdio.h>
int main()
{
int arr[N];
int i, N;
printf("Enter size of the array : ");
scanf("%d", &N);
printf("Enter elements in array : ");
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
printf("\nAll negative elements in array are : ");
for(i=0; i<N; i++)
{
if(arr[i] < 0)
{
printf("%d\t", arr[i]);
}
}
return 0;
}

Output:

Enter size of the array : 10

Enter elements in array : -1 -10 100 5 61 -2 -23 8 -90 51

All negative elements in array are : -1 -10 -2 -23 -90


41

Q. 6 . Write a C program to find second largest element in an array

Program:
#include <stdio.h>
# define SIZE 20
int main()
{
int size, i;
int arr[SIZE],max1, max2;
printf("Enter size of the array (1-1000): ");
scanf("%d", &size);
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max1 = max2 = arr[0];
for(i=0; i<size; i++)
{
if(arr[i] > max1)
{
max2 = max1;
max1 = arr[i];
}
else if(arr[i] > max2 && arr[i] < max1)
{
max2 = arr[i];
}
}
printf("First largest = %d\n", max1);
printf("Second largest = %d", max2);
return 0;
}
Output:

Enter size of the array (1-1000): 10


Enter elements in the array: -7 2 3 8 6 6 75 38 3 2
First largest = 75
Second largest = 38
42

Q. 7 . Write a C program to print all unique elements in the array

Program:

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE], freq[MAX_SIZE];
int size, i, j, count;
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
freq[i] = -1;
}
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
if(arr[i] == arr[j])
{
count++;
freq[j] = 0;
}
}
if(freq[i] != 0)
{
freq[i] = count;
}
}
printf("\nUnique elements in the array are: ");
for(i=0; i<size; i++)
{
if(freq[i] == 1)
{
printf("%d ", arr[i]);
}
}
43

return 0;
}

Output:

Enter size of array: 8

Enter elements in array: 1 2 5 1 2 4 9 6

Unique elements in the array are: 5 4 9 6

Q. 8. Write a C program to input elements in array and find reverse of array

Program:

#include <stdio.h>
#define MAX_SIZE 100 // Defines maximum size of array
int main()
{
int arr[MAX_SIZE];
int size, i;
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf("\nArray in reverse order: ");
for(i = size-1; i>=0; i--)
{
printf("%d\t", arr[i]);
}
return 0;
}
Output:

Enter size of the array: 5


Enter elements in array: 1 5 9 7 3
Array in reverse order: 3 7 9 5 1
44

Q 9. Explain the different types of arrays.

Arrays are classified into two types. They are as follows...

1. Single Dimensional Array / One Dimensional Array


2. Multi-Dimensional Array

1. Single Dimensional Array (One Dimensional Array):

✓ An array contains one subscript is known as One or Single Dimensional Array.


✓ Single dimensional arrays are used to store list of values of same datatype.
✓ Single dimensional arrays are also called as one-dimensional arrays, Linear Arrays or simply 1-D
Arrays.

Declaration of Single Dimensional Array:

We use the following general syntax for declaring a single dimensional array

Syntax: datatype arrayName [ size ] ;

Example

int rollNumbers [60];

The above declaration of single dimensional array reserves 60 continuous memory locations of 2 bytes each
with the name rollNumbers and tells the compiler to allow only integer values into those memory locations.

Initialization of Single Dimensional Array:

We use the following general syntax for declaring and initializing a single dimensional array with size and
initial values.

datatype arrayName [ size ] = {value1, value2, ...} ;


Example

int marks [6] = { 89, 90, 76, 78, 98, 86 } ;

The above declaration of single dimensional array reserves 6 contiguous memory locations of 2 bytes each
with the name marks and initializes with value 89 in first memory location, 90 in second memory location,
76 in third memory location, 78 in fourth memory location, 98 in fifth memory location and 86 in sixth
memory location.

➔ We can also use the following general syntax to intialize a single dimensional array without
specifying size and with initial values.

datatype arrayName [ ] = {value1, value2, ...} ;


45

➔ The array must be initialized if it is created without specifying any size. In this case, the size of the
array is decided based on the number of values initialized.

Example:

int marks [ ] = { 89, 90, 76, 78, 98, 86 } ;

char studentName [ ] = "GATESIT" ;

In the above example declaration, size of the array 'marks' is 6 and the size of the array 'studentName' is 16.
This is because in case of character array, compiler stores one extra character called \0 (NULL) at the end

2. Multi-Dimensional Array:
➢ If an array contains more than one subscript is known as multi-dimensional array.
➢ Multi-dimensional array can be of two dimensional array or three dimensional array or four
dimensional array or more.
➢ Most popular and commonly used multi-dimensional array is two dimensional array.
➢ The 2-D arrays are used to store data in the form of table.
➢ We also use 2-D arrays to create mathematical matrices.

Declaration of Two Dimensional Array:

➔ We use the following general syntax for declaring a two dimensional array.

Datatype arrayName [ rowSize ] [ columnSize ] ;

Example
int matrix_A [2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes each in
the form of 2 rows and 3 columns.

Initialization of Two Dimensional Array:

➔ We use the following general syntax for declaring and initializing a two dimensional array with
specific number of rows and coloumns with initial values.

datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;

Example
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each in
the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and second row is
initialized with values 4, 5 & 6.
46

➔ We can also initialize as follows.

Example

int matrix_A [2][3] = {

{1, 2, 3},

{4, 5, 6}

};

Accessing Individual Elements of Two Dimensional Array:

➢ To access elements of a two-dimensional array we use array name followed by row index value and
column index value of the element that to be accessed.
➢ Here the row and column index values must be enclosed in separate square braces.

➔ We use the following general syntax to access the individual elements of a two-dimensional array...

arrayName [ rowIndex ] [ columnIndex ]

Example

matrix_A [0][1] = 10 ;

In the above statement, the element with row index 0 and column index 1 of matrix_A array is assinged
with value 10.

Q 10. What are the applications of array?

1. Arrays are used to Store List of values

2. Arrays are used to Perform Matrix Operations

3. Arrays are used to implement Search Algorithms

4. Arrays are used to implement Sorting Algorithms

5. Arrays are used to implement Data structures.

6. Arrays are also used to implement CPU Scheduling Algorithms

Q 11. Define a string. Explain how to create and initialize strings in C.

String:

String is a set of characters enclosed in double quotation marks.


47

In C programming, the string is a character array of single dimension.

Creating a String:

Syntax: char string_name[size];

Example: char str1[30];


Initialization:

Syntax: string_name[size] = String

Example: 1. char str1[30] = “Hello”

2. char str2[20];

str = “Hello Hai”


Note: ‘\0’ represents end of the string.

Q 12. Explain about gets and puts functions.

➢ gets() function is used to read a string from standard input device and puts is used to display a string on
standard output device.
➢ gets() and puts() functions are defined in stdio.h header file

Example:

#include<stdio.h>
int main()
{
char s[20];
printf("Enter a String: ");
gets(s);
printf("Your String is: ");
puts(s);
return 0;
}

Output:

Enter a String: hello


Your String is: hello
48

Q.13. Explain about 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
49

Example Programs :
14. Write a C Program to Concatenate two strings without built-in functions
Source Code:
#include<stdio.h
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}

Output:

Enter First String: Computer Science


Enter Second String:& Engineering
Concatenated String is Computer Science & Engineering
50

15. Write a C Program to Reverse a string without built-in string functions


Source Code:

#include <stdio.h>
#include <string.h>
int main()
{
char str[50]; // size of char string
int i, len, temp;
printf (" Enter the string: ");
gets(str); // use gets() function to take string
printf(" \n Before reversing the string: %s \n", str);
len = strlen(str); // use strlen() to get the length of str string
for (i = 0; i < len/2; i++)
{
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf (" After reversing the string: %s", str);
}

Output:

Enter the string: COMPUTER


Before reversing the string: COMPUTER
After reversing the string: RETUPMOC
51

16. Write a C Program to Reverse a string using built-in string functions


Source Code:
#include <stdio.h>
#include <string.h>
int main()
{
char str[40]; // declare the size of character string
printf (" \n Enter a string to be reversed: ");
scanf ("%s", str);
printf (" \n After the reverse of a string: %s ", strrev(str));
return 0;
}

Output:

Enter a string to be reversed: SUPREME

After the reverse of a string: EMERPUS

You might also like