UNIT-III
UNIT-III
Unit III
Arrays and Strings
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
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.
➔ 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
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:
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:
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:
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:
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:
We use the following general syntax for declaring a single dimensional array
Example
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.
We use the following general syntax for declaring and initializing a single dimensional array with size and
initial values.
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.
➔ 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:
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.
➔ We use the following general syntax for declaring a two dimensional array.
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.
➔ We use the following general syntax for declaring and initializing a two dimensional array with
specific number of rows and coloumns with initial values.
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
Example
{1, 2, 3},
{4, 5, 6}
};
➢ 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...
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.
String:
Creating a String:
2. char str2[20];
➢ 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:
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:
#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:
Output: