0% found this document useful (0 votes)
36 views11 pages

C Programming: Arrays and Strings Guide

Module 3 of the C Programming course covers arrays and strings, detailing derived, fundamental, and user-defined data types. It explains one-dimensional, two-dimensional, and multi-dimensional arrays, including their declaration, initialization, and memory layout. Additionally, it introduces string handling in C, including string manipulation functions and searching algorithms like linear and binary search.

Uploaded by

gauravis147
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)
36 views11 pages

C Programming: Arrays and Strings Guide

Module 3 of the C Programming course covers arrays and strings, detailing derived, fundamental, and user-defined data types. It explains one-dimensional, two-dimensional, and multi-dimensional arrays, including their declaration, initialization, and memory layout. Additionally, it introduces string handling in C, including string manipulation functions and searching algorithms like linear and binary search.

Uploaded by

gauravis147
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

INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

MODULE-3: ARRAYS & STRINGS


C supports a rich set of derived and user defined data types in addition to a variety of
fundamental types as given below;

Data types

Derived Fundamental User – defined


Types types types

✓ Derived types Ex: Arrays, Function, pointers.


✓ Fundamental types: Ex: - Integer type, float type, character type.
✓ User Defined Types : Structures, Unions, Enumerations.

Array and Structures are referred to as structured data types because they can be used to
represent data values that have a structure of some sort.

Array: An array is a sequenced collection of related data items that share a common name.

Types of arrays: based on the number of subscripts in an array, the arrays are classified in the
following types
✓ One dimensional array
✓ Two dimensional array AJIET

✓ Multi dimensional array

One – Dimensional Arrays


A list of items can be given one variable name using only one subscript and such a variable is
called a single subscripted variable or a one- dimensional array.
In C the single subscripted variable xi can be expressed as x[0], x[1],x[2],x[3]………….x[n]

Declaration of One – Dimensional Array


Arrays must be declared before they are used so that the compiler can allocate space for them
in memory
The general form of array declaration is
Type variable –name[size];
Where the type specifies the type of element that will be contained in the array such as int,
char, float and the size indicates the maximum number of elements that can be stored inside
the array.
Ex: int height[10];

Department of CSE, AJIET, Mangaluru Page 1


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

Char name[10], declares the name as a character array (string) variable, when the complier
sees a character string, it terminates with a additional null character.

Initialization of One- Dimensional Array


After an array is declared its elements must be initialized, otherwise they will contain garbage
values. Array can be initialized at either of the following stages:
• At compile time
• At run time

Compile time initialization

We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared. The general form of initialization of arrays is

Type array-name[size] = {list of values};

Ex: int num[3] = {1,2,3};


Int count[ ] ={1,2,3,4};
Char name [ ]={‘c’,’s’,’e’}
Char name [ ]= “CSE”;
Int num [5] = {1,2};

Run time Initialization


An array can be explicitly initialized at run time. This approach is usually used for initializing
AJIET

large arrays. For example consider the sequence of c program


------------
------------
For( i =0; i<100; i++)
{
If ( i < 50)
Sum[i] = 0. 0;
Else
Sum[i] = 1.0;
}

// Program to find the average of n (n < 10) numbers using


arrays
#include<stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)

Department of CSE, AJIET, Mangaluru Page 2


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return0;
}

Two Dimensional Array

In mathematics we represent a particular value in a matrix by using two subscripts such as v ij.
Where v denotes the entire matrix and vij refers to value ith row and jth column.
Two dimensional array can be declared in C as

type array_name[row_size][column_size];

AJIET

Initializing two dimensional arrays

Two dimensional arrays can be initialized by following their declaration with a list of initial
values enclosed in braces.
int table[2][3]= {0,0,0,1,1,1};
Initializes the elements of the first row to zero and second row to one. The above declaration
can be also written as
Int table[2][3] ={{0,0,0}{1,1,1}}; by surrounding the elements of each row by
braces.
When the array is completely initialized with all the values , explicitly, we need not specify
the size of the first dimension i.e
Int table [ ][3]= { {0,0,0},{1,1,1}};
If the values are missing in an initializer they are automatically set to zero.
Int table[2][3] = { {1,1},{2}};
When all the elements are to be initialized to zero the following short cut method may be
used int m[3][5] = { {0},{0},{0}};

Department of CSE, AJIET, Mangaluru Page 3


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

Memory layout

The elements of all arrays are stored contiguously in increasing memory locations, essentially
in a single list. A two dimensional array is stored row wise starting from the first row and
ending with last row treating each row like a simple array.

Multi dimensional arrays

C allows arrays of three or more dimensions. The exact limit is determined by the
compiler. The general form of a multi – dimensional array is
type array_name [s1][s2][s3]………[sm];

Ex: int survey [3][5][12];


Anci C does not specify any limit for array dimension. However, most compliers permit
AJIET

seven to ten dimensions.

Dynamic Arrays

The process of allocating memory at compile time is known as static memory


allocation and the arrays that receive static memory allocation are called static arrays. This
approach works fine as long as we know exactly what our data requirements are.
In C it is possible to allocate memory to arrays at run time, this feature is called dynamic
memory allocation and the arrays created at run time are called dynamic arrays.
Dynamic arrays are created using memory management functions malloc, calloc, and
realloc. These functions are included in <stdlib.h>.

Introduction to strings

A string constant or literal can be defined as a sequence of characters enclosed in double


quotes that will be treated as single data element.

In C strings are arrays of characters


✓ Every string in a C program ends with \0 character
✓ Strings are always enclosed within double quotes
✓ If the program uses the string function it must define the header file string.h

Department of CSE, AJIET, Mangaluru Page 4


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

The common operations performed on character strings include the following:


• Reading and writing strings
• Combining strings together
• Copying one string to another
• Comparing strings for equality
• Extracting a portion of a string

Declaration and initialization of string variables

C does not support strings as a data type, however it allows us to represent strings as
character arrays. In C therefore a string variable is any valid C variable name and is always
declared as an array of characters. The string variables must be defined and initialized in
same way of array declaration and initialization.

The general form of declaring of a string variable is :

Syntax : char string_variable[size];

Ex: char name[20];

Like numeric arrays, character arrays may be initialized when they are declared. C permits a
character array to be initialized in either of the following two forms:
char city[9] =”NEW YORK”;
char city[9]={‘N’, ‘E’, ‘W’, ‘ ‘, ‘Y’, ‘O’,’R’,’K’,’\0’};
AJIET

Terminating null Character:


A string is not a data type in C, but it is considered a data structure stored in an array. The
string is a variable – length structure and is stored in a fixed length array. We need someway
to determine the end of the string data and the null character serves as the “end of string”
marker.

Reading Strings from terminal

1) Using scanf Function:

The familiar input function scanf() can be used with a %s format specification to read in a
string of charcters. The scanf reads a string until white space is found from a keyboard. A
whitespace includes blans, tabs, carriage returns, form feed, newline etc.

#include <stdio.h>
#include <conio.h>

Int main(){
char inputString1[100], inputString2[100];
printf("Enter a string1\n");
scanf("%s", inputString1);
printf("Enter a string2\n");
scanf("%s", inputString2);

printf("%s\n%s", inputString1,inputString2);

Department of CSE, AJIET, Mangaluru Page 5


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

getch();
return0;
}

2) Using getchar() and gets() function

We can use the getchar() function to repeatedly read successive single character from the
input and place them into a character array. getchar() function has no parameters.
getchar() takes the form
char ch;
ch=getchar();
Another more convenient way of reading a string of text containing whitespaces is to use the
library function gets available in the <stdio.h> header file. This is a simple function with one
string parameter and called as
gets(str);
It reads characters into str from the keyboard until a newline character is encountered and
then appends a null character to the string. Unlike scanf it does not skip whitespaces.
Ex: char line [80];
gets(line);
printf(“%s”,line);

Writing Strings to terminal

1) Using printf() function


We can use the printf() function with the %s format specifier, the %s can be used to display
an array of characters that is terminated by a null character.
AJIET

Ex: printf(“%s”, name);

2) Using putchar() and puts function


C supports another character handling function putchar() to output the values of character
variables. It takes the following form
char ch = ‘A’;
putchar(ch);

Another more convienient way of printing string values is to use the function puts declared in
the header file <stdio.h>. This is a one parameter function and is invoked as
puts(str);
where str is a string variable containing a string value. This prints the value of the string
variable str and then moves the cursor to the beginning of the next line on the screen.

Arithmetic operations on characters

C allows us to manipulate characters the same way we do with number, whenever a character
constant or character variable is used in an expression, it is automatically converted into an
integer value by the system. The integer value depends on the local character set of the
system (ASCII code).
To write a character in its integer representation we may write it as an integer. For example if
machine uses the ASCII representation then,
X=’a’;
Printf(“%d”, x);

Department of CSE, AJIET, Mangaluru Page 6


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

This will display the number 97 on the screen.


The C library supports a function that converts a string of digits into their integer values. The
function takes the form
X=atoi(string);

String Manipulation/Handling functions

C supports a large number of string handling functions in the standard library "string.h"

Strlen() function:
To find the total number of characters in a string we use the strlen() function which is from
the string.h header file.
Syntax of finding the length of a string is given below.
AJIET

int len = strlen(str);


Where, str is the name of the variable holding the string.
Example :

#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char str[] = "Hello";

printf("%ld", strlen(str)); //this will give us 5


return 0;
}

Strcmp() function
To compare two strings in C we use the strcmp() method from the string.h header file.
The strcmp() function compares two strings lexicographically and will return an integer
value.
• If returned value is negative then string1 < string2 i.e., string1 is lexically above
string2.
• If returned value is 0 then string1 and string2 are identical.

Department of CSE, AJIET, Mangaluru Page 7


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

•If returned value is positive then string1 > string2 i.e., string1 is lexically below
string2.
Syntax: strcmp(string1,string2);

Strcpy() function
The strcpy function works almost like a string assignment operator. It takes the following
form
Strcpy(string1, string2);
And assigns the content of string2 to string1.

Strcat() function:
We use the strcat() function from the string.h header file to concatenate two strings.
In the following example we will concatenate "Hello" and "World".

#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char
str1[] = "Hello",
str2[] = "World",
str3[100] = "";

//concat
strcat(str3, str1); //concat "Hello" to str3 so, str3 = "Hello"
AJIET

strcat(str3, " "); //concat " " to str3 so, str3 = "Hello "
strcat(str3, str2); //concat "World" to str3 so, str3 = "Hello World"

printf("Concatenated string: %s\n", str3);

printf("End of code\n");
return 0;
}

Searching algorithms

Binary Search and Linear Search are the commonly used searching algorithms. Linear Search
Algorithm is used to find an item in the list. It starts searching for the item from the
beginning of the list and continues till the end of the list until the item is found. The Binary
Search Algorithm follows the Divide and Conquer strategy where in it finds the item from the
sorted list of items.

Department of CSE, AJIET, Mangaluru Page 8


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

Linear search

#include <stdio.h>

void main()
{
int array[10];
int i, num, keynum, found = 0;

printf("Enter the value of num \n");


scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%dn", array[i]);
}
printf("Enter the element to be searched \n");
scanf("%d", &keynum);
/* Linear search begins */
for (i = 0; i < num ; i++)
AJIET

{
if (keynum == array[i] )
{
found = 1;
break;
}
}
if (found == 1)
printf("Element is present in the array\n");
else
printf("Element is not present in the array\n");
}

Binary Search

This C Program accepts the sorted array and does search using Binary search. Binary search
is an algorithm for locating the position of an item in a sorted array. A search of sorted data,
in which the middle position is examined first. Search continues with either the left or the
right portion of the data, thus eliminating half of the remaining search space. In other words,
a search which can be applied to an ordered linear list to progressively divide the possible
scope of a search in half until the search object is found.
#include <stdio.h>

void main()

Department of CSE, AJIET, Mangaluru Page 9


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

{
int array[10];
int i, j, num, temp, keynum;
int low, mid, high;

printf("Enter the value of num \n");


scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array elements \n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
AJIET

array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
printf("Enter the element to be searched \n");
scanf("%d", &keynum);
/* Binary searching begins */
low = 1;
high = num;
do
{
mid = (low + high) / 2;
if (keynum < array[mid])
high = mid - 1;
else if (keynum > array[mid])
low = mid + 1;
} while (keynum != array[mid] && low <= high);
if (keynum == array[mid])
{

Department of CSE, AJIET, Mangaluru Page 10


INTRODUCTION TO C PROGRAMMING [1BPLC205E/105E] | Module 3

printf("SEARCH SUCCESSFUL \n");


}
else
{
printf("SEARCH FAILED \n");
}
}

*****

AJIET

Department of CSE, AJIET, Mangaluru Page 11

Common questions

Powered by AI

String literals and character arrays, being arrays, provide efficient access to elements, but manual handling of their memory and bounds is critical to avoid overflows and undefined behavior. String literals are stored in read-only memory, making them safer from overwrites, but using them as mutable character arrays leads to segmentation faults. Careful boundary and null-termination management is vital to ensure safety in operations .

String handling functions in C, such as strlen, strcat, and strcpy, facilitate operations on character arrays by performing tasks like finding lengths, concatenating, and copying strings. They manage special cases like null-terminated strings by using the null character \'0\' to determine the end of strings, preventing buffer overflows and handling string manipulations efficiently. These functions are critical for ensuring the consistency and correctness of operations on strings .

The use of scanf for string inputs can lead to buffer overflow if inputs exceed the allocated space, as it does not check bounds, leading to potential security vulnerabilities such as stack smashing. getc mitigates some issues of scanf with single-character inputs, but handling strings should use safer functions like fgets or validating input lengths before processing to prevent common security exploits .

'Divide and conquer' in binary search splits the dataset into two halves at each step and recurses into the half likely containing the searched item. This drastically reduces the number of comparisons needed, leading to O(log n) time complexity. Practical limitations include the necessity of a sorted array and the increased complexity of implementing sorting as a preprocessing step, impacting overall performance for non-static datasets .

Challenges in C's character manipulation include managing different character encodings and handling edge cases like integer conversion leading to unexpected results due to overflow or different interpretations of characters. These are mitigated by understanding the ASCII values characters map to and cautiously manipulating characters in expressions, ensuring explicit casts where necessary .

In C, two-dimensional arrays are stored in a row-major order, meaning the complete rows are stored contiguously in memory. This layout can be highly efficient for accessing elements row-wise but less so for column-wise access due to cache performance, as accessing contiguous memory locations is faster due to caching effects. This impacts algorithms that involve intensive column operations, where cache misses can significantly degrade performance .

Dynamic arrays offer flexibility as they allow memory allocation at runtime and can resize as needed using functions like malloc, calloc, and realloc. This can lead to more efficient memory usage when the program's data needs are not known at compile time. However, managing dynamic arrays is more complex and prone to errors such as memory leaks if memory is not properly freed, adding to the complexity compared to statically allocated arrays, which have a fixed size determined at compile time .

Multi-dimensional arrays can represent complex data structures like matrices, tables, and grids, which are common in mathematical computations and simulations. They allow for more structured data organization compared to single-dimensional arrays, enabling more intuitive handling of data that naturally forms a multi-axis representation, such as 2D images or board games .

Initializing an array is crucial because it ensures that the array elements are set to known values rather than random data (garbage values). Uninitialized arrays can lead to unpredictable behavior because they may contain junk memory data, leading to incorrect program outputs and potential crashes .

Linear search scans through each element sequentially from start to end and is simple but inefficient for large datasets, with O(n) time complexity. Binary search, however, divides the data set in half and eliminates half the search space at each step, assuming a sorted array, which results in O(log n) time complexity. Thus, binary search is significantly more efficient for large datasets but requires pre-sorting, unlike linear search .

You might also like