Unit 3
Unit 3
Unit III
Arrays and Strings
Q.1. Define an Array. Explain how to declare and ini alize an array.
An array is a variable which can store more than one value of same datatype.
The elements of array stored in con nues memory loca ons.
Declara on 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 loca ons with a single name 'a' and tells the
compiler to store three different integer values (each in 2 bytes of memory).
For the above declara on, the memory is organized as follows...
Syntax for crea ng an array without size and with ini al values
datatype arrayName [ ] = {value1, value2, ...} ;
Example
int a[ ] = {1, 2, 3, 4, 5};
Here, an array ‘a’ stores 5 values.
35
1. Text Segment:
A text segment, also known as a code segment or simply as text, is one of the sec ons of a program
in an object file or in memory, which contains executable instruc ons.
As a memory region, a text segment may be placed below the heap or stack in order to prevent
heaps and stack overflows from overwri ng 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 o en read-only, to prevent a program from accidentally modifying its instruc ons.
Ini alized data segment, usually called simply the Data Segment.
A data segment is a por on of the virtual address space of a program, which contains the global
variables and sta c variables that are ini alized by the programmer.
The data segment is not read-only, since the values of the variables can be altered at run me.
This segment can be further classified into the ini alized read-only area and the ini alized 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 ini alized 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 ini alized read-only area and the character pointer variable string in the ini alized
read-write area.
Ex: sta c int i = 10 will be stored in the data segment and global int i = 10 will also be stored in 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.
37
4. Stack:
The stack area tradi onally adjoined the heap area and grew in the opposite direc on; 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 s ll typically
grow in opposite direc ons.)
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 direc on.
A “stack pointer” register tracks the top of the stack; it is adjusted each me a value is “pushed”
onto the stack.
The set of values pushed for one func on call is termed a “stack frame”;
A stack frame consists at minimum of a return address.
Stack, where automa c variables are stored, along with informa on that is saved each me a
func on is called.
Each me a func on is called, the address of where to return to and certain informa on about the
caller’s environment, such as some of the machine registers, are saved on the stack.
The newly called func on then allocates room on the stack for its automa c variables.
This is how recursive func ons in C can work.
Each me a recursive func on calls itself, a new stack frame is used, so one set of variables doesn’t
interfere with the variables from another instance of the func on.
5. Heap:
Heap is the segment where dynamic memory alloca on 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 poten ally
non-con guous 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.
38
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]);
}
}
42
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 declara on of single dimensional array reserves 60 con nuous memory loca ons of 2 bytes each
with the name rollNumbers and tells the compiler to allow only integer values into those memory loca ons.
We use the following general syntax for declaring and ini alizing a single dimensional array with size and
ini al values.
The above declara on of single dimensional array reserves 6 con guous memory loca ons of 2 bytes each
with the name marks and ini alizes with value 89 in first memory loca on, 90 in second memory loca on,
76 in third memory loca on, 78 in fourth memory loca on, 98 in fi h memory loca on and 86 in sixth
memory loca on.
We can also use the following general syntax to in alize a single dimensional array without
specifying size and with ini al values.
The array must be ini alized if it is created without specifying any size. In this case, the size of the
array is decided based on the number of values ini alized.
Example:
In the above example declara on, 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
We use the following general syntax for declaring a two dimensional array.
Example
int matrix_A [2][3] ;
The above declara on of two dimensional array reserves 6 con nuous memory loca ons of 2 bytes each in
the form of 2 rows and 3 columns.
We use the following general syntax for declaring and ini alizing a two dimensional array with
specific number of rows and coloumns with ini al values.
Example
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declara on of two-dimensional array reserves 6 con guous memory loca ons of 2 bytes each in
the form of 2 rows and 3 columns. And the first row is ini alized with values 1, 2 & 3 and second row is
ini alized with values 4, 5 & 6.
45
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.
Q 11. Define a string. Explain how to create and ini alize strings in C.
String:
Crea ng a String:
2. char str2[20];
gets() func on 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() func ons 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 func ons
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:
15. Write a C Program to Reverse a string without built-in string func ons
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:
16. Write a C Program to Reverse a string using built-in string func ons
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: