0% found this document useful (0 votes)
4 views17 pages

Unit 3

The document provides an overview of arrays and strings in C programming, detailing how to define, declare, and initialize arrays. It explains how to access array elements, the memory layout of C programs, and includes several C program examples for reading, printing, and manipulating arrays. Additionally, it classifies arrays into single-dimensional and multi-dimensional types, with syntax and examples for both.

Uploaded by

abrarhabib75
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 views17 pages

Unit 3

The document provides an overview of arrays and strings in C programming, detailing how to define, declare, and initialize arrays. It explains how to access array elements, the memory layout of C programs, and includes several C program examples for reading, printing, and manipulating arrays. Additionally, it classifies arrays into single-dimensional and multi-dimensional types, with syntax and examples for both.

Uploaded by

abrarhabib75
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

34

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...

Ini aliza on of Array:


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

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

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 a er 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:


prin (“%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 representa on of a C program consists of the following sec ons.
1. Text segment (i.e. instruc ons)
2. Ini alized data segment
3. Unini alized data segment (bss)
4. Heap
5. Stack
36

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 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.

2. Ini alized Data Segment:

 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

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.
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

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,
39

Q . 5 . Write a C program to print all nega ve 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


40

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
41

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]);
}
}
42

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
43

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. Mul -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.

Declara on 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 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.

Ini aliza on of Single Dimensional Array:

We use the following general syntax for declaring and ini alizing a single dimensional array with size and
ini al values.

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


Example

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

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.

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


44

 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:

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

char studentName [ ] = "GATESIT" ;

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

2. Mul -Dimensional Array:


 If an array contains more than one subscript is known as mul -dimensional array.
 Mul -dimensional array can be of two dimensional array or three dimensional array or four
dimensional array or more.
 Most popular and commonly used mul -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 mathema cal matrices.

Declara on 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 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.

Ini aliza on of Two Dimensional Array:

 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.

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

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

 We can also ini alize 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 applica ons of array?

1. Arrays are used to Store List of values

2. Arrays are used to Perform Matrix Opera ons

3. Arrays are used to implement Search Algorithms

4. Arrays are used to implement Sor ng 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 ini alize strings in C.

String:

String is a set of characters enclosed in double quota on marks.


46

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

Crea ng a String:

Syntax: char string_name[size];

Example: char str1[30];


Ini aliza on:

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 func ons.

 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:

Enter a String: hello


Your String is: hello
47

Q.13. Explain about string handling func ons.


 C programming language provides a set of pre-defined func ons called string handling func ons to
work with string values.
 The string handling func ons are defined in a header file called string.h.
 Whenever we want to use any string handling func on we must include the header file called
string.h.
 The following table provides most commonly used string handling func on and their use
48

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:

Enter First String: Computer Science


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

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:

Enter the string: COMPUTER


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

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:

Enter a string to be reversed: SUPREME

After the reverse of a string: EMERPUS

You might also like