Introduction to C language, Study notes of Introduction to Computing

An introduction to arrays and strings in C programming language. It covers topics such as array declaration, initialization, and processing, as well as multi-dimensional arrays and character arrays. how arrays simplify the task of data management and provide a mechanism for declaring and accessing several data items with only one identifier. It also includes examples of array initialization and character array initialization.

Typology: Study notes

2021/2022

Available from 01/22/2023

mani002
mani002 🇮🇳

13 documents

1 / 110

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
84
An Introduction to C UNIT 4 ARRAYS AND STRINGS
Structure
4.0 Introduction
4.1 Objectives
4.2 Array Declaration
4.2.1 Syntax of Array Declaration
4.2.2 Size Specification
4.3 Array Initialization
4.3.1 Initialization of Array Elements in the Declaration
4.3.2 Character Array Initialization
4.4 Subscript
4.5 Processing the Arrays
4.6 Multi-Dimensional Arrays
4.6.1 Multi-Dimensional Array Declaration
4.6.2 Initialization of Two-Dimensional Arrays
4.7 Introduction to Strings
4.8 Declaration and Initialization of Strings
4.9 Display of Strings Using Different Formatting Techniques
4.10 Array of Strings
4.11 String Functions and Applications
4.12 Summary
4.13 Solutions / Answers
4.14 Further Readings
4.0 INTRODUCTION
C language provides four basic data types - int, char, float and double. We
have learnt about them in Unit 2. These basic data types are very useful; but
they can handle only a limited amount of data. As programs become larger and
more complicated, it becomes increasingly difficult to manage the data.
Variable names typically become longer to ensure their uniqueness. And, the
number of variable names makes it difficult for the programmer to concentrate
on the more important task of correct coding. Arrays provide a mechanism for
declaring and accessing several data items with only one identifier, thereby
simplifying the task of data management.
Many programs require the processing of multiple, related data items that have
common characteristics like list of numbers, marks in a course, or enrolment
numbers. This could be done by creating several individual variables. But this
is a hard and tedious process. For example, suppose you want to read in five
numbers and print them out in reverse order. You could do it the hard way as:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Introduction to C language and more Study notes Introduction to Computing in PDF only on Docsity!

An Introduction to C

UNIT 4 ARRAYS AND STRINGS

Structure

4.0 Introduction 4.1 Objectives 4.2 Array Declaration 4.2.1 Syntax of Array Declaration 4.2.2 Size Specification 4.3 Array Initialization 4.3.1 Initialization of Array Elements in the Declaration 4.3.2 Character Array Initialization 4.4 Subscript 4.5 Processing the Arrays 4.6 Multi-Dimensional Arrays 4.6.1 Multi-Dimensional Array Declaration 4.6.2 Initialization of Two-Dimensional Arrays 4.7 Introduction to Strings 4.8 Declaration and Initialization of Strings 4.9 Display of Strings Using Different Formatting Techniques 4.10 Array of Strings 4.11 String Functions and Applications 4.12 Summary 4.13 Solutions / Answers 4.14 Further Readings

4.0 INTRODUCTION

C language provides four basic data types - int, char, float and double. We have learnt about them in Unit 2. These basic data types are very useful; but they can handle only a limited amount of data. As programs become larger and more complicated, it becomes increasingly difficult to manage the data. Variable names typically become longer to ensure their uniqueness. And, the number of variable names makes it difficult for the programmer to concentrate on the more important task of correct coding. Arrays provide a mechanism for declaring and accessing several data items with only one identifier, thereby simplifying the task of data management.

Many programs require the processing of multiple, related data items that have common characteristics like list of numbers, marks in a course, or enrolment numbers. This could be done by creating several individual variables. But this is a hard and tedious process. For example, suppose you want to read in five numbers and print them out in reverse order. You could do it the hard way as:

main { int a scan print }

Does and p varia perfo disad such in ad case Decl each to st follo

int a

Now find An a defin

int a

wher Each calle array

In th alloc

This initia focu

Afte

n()

al,a2,a3,a4,a nf(“%d %d % tf(“%d %d %

s it look goo print them in able names a orm the oper dvantageous h situations. A djacent mem of C, you h laration and h element, an ore marks of ows:

ar1, ar2, ar3,

w, if we want it difficult to array declara ne an array a ar[100];

re ar is defin h element of ed the subscr y is the colle

2001

he above figu cated in the m

s unit explain alization wit uses on string

OBJE

er going thro

declare and initialize arr

; %d %d %d”,& %d %d %d”',a

od if the prob n reverse ord a 1 , a2 and so rations on th s too. One co An array is mory location ave to declar definition te nd the size or f five studen

ar4, ar5;

t to do the sa o handle 100 ation uses its as:

ned as an arr f this collecti ript is used t ection of 200

2003

Figur

ure, as each memory.

ns the use of th the help o g handling in

CTIVES

ugh this unit

use arrays o rays;

a1,&a2,&a3,& 5,a4,a3,a2,a

blem is to re der? Of cour o on. But to he variables i ommon orga a collection ns and are re re and defin ell the compi r number of nts. They can

ame thing fo 0 variables. T s size in [] br

ray of size 10 ion is called to denote ind 0 consecutiv

re 4.1: Repre

integer valu

f arrays, type f examples i n C program

S

t you will be

of one dimen

&a4,&a5); );

ad in 100 or rse, the solut remember e is not only te anizing techn n of similar k ferred to by e array befo iler the name f elements. T n be stored u

or 100 studen This can be rackets. For

00 to store m an array-ele dividual elem e memory lo

esentation of

e occupies 2

es of arrays, in the first fe mming langua

e able to:

nsion;

r more relate tion is the us each and eve edious a job nique is to us kind of data e a single arra ore it can be e of the arra To explain it, using five va

nts in a class obtained by above exam

marks of inte ement and an ments of the ocations refe

220

an Array

2 bytes, 200 b

declaration ew sections a age.

ed data items se of the regu ry variable a and se arrays in elements sto ay-name. In used. y, the type o let us consi ariables as

s then one wi using an arr mple, we can

eger data-typ n integer val array. An ar erred as belo

00

bytes were

and and later on

s ular and

ored the

of ider

ill ray.

pe. lue r w:

Arrays and S trings

 The data type of an array applies uniformly to all the elements; for this^ Arrays and Strings reason, an array is called a homogeneous data structure.

4.2.2 Size Specification

The size of an array should be declared using symbolic constant rather a fixed integer quantity(The subscript used for the individual element is of are integer quantity). The use of a symbolic constant makes it easier to modify a program that uses an array. All reference to maximize the array size can be altered simply by changing the value of the symbolic constant.(Please refer to Unit – 2 for details regarding symbolic constants).

To declare size as 50 use the following symbolic constant, SIZE, defined:

#define SIZE 50

The following example shows how to declare and read values in an array to store marks of the students of a class.

Example 4.

Write a program to declare and read values in an array and display them.

/* Program to read values in an array*/

include

define SIZE 5 /* SIZE is a symbolic constant */

main() { int i=0; /* Loop variable / int stud_marks[SIZE]; / array declaration */

/* enter the values of the elements */ for(i=0;i An Introduction to C (^) Value stored in a[0] is 11 Value stored in a[1] is 12 Value stored in a[2] is 13 Value stored in a[3] is 14 Value stored in a[4] is 15

4.3 ARRAY INITIALIZATION

Arrays can be initialized at the time of declaration. The initial values must appear in the order in which they will be assigned to the individual array elements,enclosed within the braces and separated by commas. In the following section,we see how this can be done.

4.3.1 Initialization of Array Elements in the Declaration

The values are assigned to individual array elements enclosed within the braces and separated by comma. Syntax of array initialization is as follows: data type array-name [size] = {val 1,val 2,.......val n};

val 1 is the value for the first array element, val 2 is the value for the second element,and val n is the value for the n array element. Note that when you are initializing the values at the time of declaration, then there is no need to specify the size. Let us see some of the examples given below: int digits [10]={1,2,3,4,5,6,7,8,9,10};

int digits[]={1,2,3,4,5,6,7,8,9,10};

int vector[5]={12,-2,33,21,13};

float temperature[10]={31.2,22.3,41.4,33.2,23.3,32.3,41.1,10.8,11.3,42.3};

double width[]={17.33333456,-1.212121213,222.191345 };

int height[10]={60,70,68,72,68 };

4.3.2 Character Array Initialisation

The array of characters is implemented as strings in C. Strings are handled differently as far as initialization is concerned. A special character called null character ‘ \0 ’,implicitly suffixes every string. When the external or static string character array is assigned a string constant, the size specification is usually omitted and is automatically assigned; it will include the ‘\0’character, added at end. For example, consider the following two assignment statements: char thing[3]= “TIN”; char thing[]= “TIN”;

In the above two statements the assignments are done differently. The first statement is not a string but simply an array storing three characters ‘T’,‘I’ and ‘N’ and is same as writing: char thing[3]={‘T’,‘I’,‘N’};

An Introduction to C

4.4 SUBSCRIPT

To refer to the individual element in an array,a subscript is used. Refer to the statement we used in the Example 4.1, scanf(“ %d”,&stud_marks[i]);

Subscript is an integer type constant or variable name whose value ranges from 0 to SIZE - 1 where SIZE is the total number of elements in the array. Let us now see how we can refer to individual elements of an array of size 5: Consider the following declarations:

char country[] =“India”; int stud[]={1,2,3,4,5};

Here both arrays are of size 5. This is because the country is a char array and initialized by a string constant “India” and every string constant is terminated by a null character ‘\0’. And stud is an integer array. country array occupies 5 bytes of memory space whereas stud occupies size of 10 bytes of memory space. The following table: 4.1 shows how individual array elements of country and stud arrays can be referred: Table 4.1: Reference of individual elements Element no.

Subscript country array

Reference Value

stud array

Reference Value 1 0 country [0] ‘I’ stud [0] 1 2 1 country [1] ‘n’ stud [1] 2 3 2 country [2] ‘d’ stud [2] 3 4 3 country [3] ‘i’ stud [3] 4 5 4 country [4] ‘a’ stud [4] 5

Example 4.

Write a program to illustrate how the marks of 10 students are read in an array and then used to find the maximum marks obtained by a student in the class.

/* Program to find the maximum marks among the marks of 10 students*/

#include< stdio.h> #define SIZE 10 /* SIZE is a symbolic constant */

main() {

int i=0; int max=0; int stud_marks[SIZE]; /* array declaration */

/* enter the values of the elements */ for(i=0;i scanf(“%d”,&stud_marks[i]);^ Arrays and Strings }

/* find maximum */ for(i=0;imax) max= stud_marks[i]; } printf(“\n\nThe maximum of the marks obtained among all the 10 students is: %d ”,max); }

OUTPUT

Student no. = 1 Enter the marks out of 50: 10 Student no. = 2 Enter the marks out of 50: 17 Student no. = 3 Enter the marks out of 50: 23 Student no. = 4 Enter the marks out of 50: 40 Student no. = 5 Enter the marks out of 50: 49 Student no. = 6 Enter the marks out of 50: 34 Student no. = 7 Enter the marks out of 50: 37 Student no. = 8 Enter the marks out of 50: 16 Student no. = 9 Enter the marks out of 50: 08 Student no. = 10 Enter the marks out of 50: 37

The maximum of the marks obtained among all the 10 students is: 49

4.5 PROCESSING THE ARRAYS

For certain applications the assignment of initial values to elements of an array is required. This means that the array be defined globally(extern) or locally as a static array.

Let us now see in the following example how the marks in two subjects, stored in two different arrays, can be added to give another array and display the average marks in the below example.

Example 4.

Write a program to display the average marks of each student, given the marks in 2 subjects for 3 students.

/* Program to display the average marks of 3 students */

include < stdio.h >

define SIZE 3

main() { int i =0; float stud_marks1[SIZE]; /* subject 1array declaration / float stud_marks2[SIZE]; /subject 2 array declaration */ float total_marks[SIZE]; float avg[SIZE];

printf(“\n Enter the marks in subject-1 out of 50 marks: \n”);

{^ Arrays and Strings printf(“Element no.=%d Value of the element=”,i+1); scanf(“%d”,&num_list[i]); } printf(“Enter the element to be searched:”); scanf(“%d”,&j);

/* search using linear search */ for(i=0;i #define SIZE 5

main() {

int j,min_pos,tmp; int i; /* Loop variable / int a[SIZE]; / array declaration */

/* enter the elements */

for(i=0;i An Introduction to C (^) min_pos=i; for(j=i+1;j An Introduction to C (^) the indices on each side of the chessboard array run 0 through 7, rather than 1

through 8. The effect is the same: a two-dimensional array of 64 elements.

int chessboard [8][8];

To pinpoint an element in this grid, simply supply the indices in both dimensions.

4.6.2 Initialisation of Two - Dimensional Arrays

If you have an m x n array, it will have m * n elements and will require mnelement-size bytes of storage. To allocate storage for an array you must reserve this amount of memory. The elements of a two-dimensional array are stored row wise. If table is declared as: int table [2] [3]={1,2,3,4,5,6 };

It means that element table [0][0]=1; table [0][1]=2; table [0][2]=3; table [1][0]=4; table [1][1]=5; table [1][2]=6;

The neutral order in which the initial values are assigned can be altered by including the groups in {} inside main enclosing brackets, like the following initialization as above: int table [2][3]={{1,2,3},{4,5,6} };

The value within innermost braces will be assigned to those array elements whose last subscript changes most rapidly. If there are few remaining values in the row, they will be assigned zeros. The number of values cannot exceed the defined row size. int table [2] [3]={{1, 2, 3},{4}};

It assigns values as:

table[0][0]=1; table[0][1]=2; table[0][2]=3; table[1][0]=4; table[1][1]=0; table[1][2]=0;

Remember that, C language performs no error checking on array bounds. If you define an array with 50 elements and you attempt to access element 50(the 51st element), or any out of bounds index, the compiler issues no warnings. It is the programmer’s task to check that all attempts to access or write to arrays are done only at valid array indexes. Writing or reading past the end of arrays is a common programming bug and is hard to isolate.

Check Your Progress 3^ Arrays and Strings

  1. Declare a multi-dimensioned array of floats called balances having three rows and five columns. ……………………………………………………………………………… ……………………………………………………………………………… ……………………………………………………………………………… ……………………………………………………………………………… ………………………………………………………………………………
  2. Write a for loop to total the contents of the multi-dimensioned float array balances. ……………………………………………………………………………… ……………………………………………………………………………… ……………………………………………………………………………… ……………………………………………………………………………… ………………………………………………………………………………
  3. Write a for loop which will read five characters(use scanf) and deposit them into the character based array words, beginning at element 0. ……………………………………………………………………………… ……………………………………………………………………………… ……………………………………………………………………………… ……………………………………………………………………………… ………………………………………………………………………………

4.7 INTRODUCTION TO STRINGS

In the previous unit, we have discussed numeric arrays, a powerful data storage method that lets you group a number of same-type data items under the same group name. Individual items, or elements, in an array are identified using a subscript after the array name. Computer programming tasks that involve repetitive data processing lend themselves to array storage. Like non-array variables, arrays must be declared before they can be used. Optionally, array elements can be initialized when the array is declared. In the earlier unit, we had just known the concept of character arrays which are also called strings.

String can be represented as a single-dimensional character type array. C language does not provide the intrinsic string types. Some problems require that the characters within a string be processed individually. However, there are many problems which require that strings be processed as complete entities. Such problems can be manipulated considerably through the use of special string oriented library functions. Most of the C compilers include string library functions that allow string comparison, string copy, concatenation of strings etc. The string functions operate on null-terminated arrays of characters

char str[4]={‘u’, ‘n’, ‘i’, ‘x’};^ Arrays and Strings char str[5]={‘u’, ‘n’, ‘i’, ‘x’, ‘\0’}; char str[3]; char str[]=“UNIX”; char str[4]=“unix”; char str[9]=“unix”;

All of the above declarations are legal. But which ones don’t work? The first one is a valid declaration, but will cause major problems because it is not null- terminated. The second example shows a correct null-terminated string. The special escape character \0 denotes string termination. The fifth example suffers the size problem, the character array ‘ str’ is of size 4 bytes, but it requires an additional space to store \0’. The fourth example however does not. This is because the compiler will determine the length of the string and automatically initialize the last character to a null-terminator. The strings not terminated by a ‘\0’ are merely a collection of characters and are called as character arrays.

String Constants

String constants have double quote marks around them, and can be assigned to char pointers. Alternatively, you can assign a string constant to a char array - either with no size specified, or you can specify a size, but don’t forget to leave a space for the null character! Suppose you create the following two code fragments and run them:

/* Fragment 1 */ { char *s; s=hello”; printf(“%s\n”,s); }

/* Fragment 2 */ { char s[100]; strcpy(s,“ hello”); printf(“%s\n”,s); }

These two fragments produce the same output, but their internal behaviour is quite different. In fragment 2, you cannot say s="hello";. To understand the differences, you have to understand how the string constant table works in C. When your program is compiled, the compiler forms the object code file, which contains your machine code and a table of all the string constants declared in the program. In fragment 1, the statement s="hello"; causes s to point to the address of the string hello in the string constant table. Since this string is in the string constant table, and therefore technically a part of the executable code, you cannot modify it. You can only point to it and use it in a read-only manner. In fragment 2, the string hello also exists in the constant table, so you can copy it into the array of characters named s. Since s is not an address, the statement s="hello"; will not work in fragment 2. It will not even compile.

An Introduction to C (^) Example 4.

Write a program to read a name from the keyboard and display message Hello onto the monitor”. /Program that reads the name and display the hello along with your name/ #include main() { char name[10]; printf(“\nEnter Your Name :); scanf(“%s”, name); printf(“Hello %s\n”,name); }

OUTPUT

Enter Your Name: Alex Hello Alex

In the above example declaration char name [10] allocates 10 bytes of memory space(on 16 bit computing) to array name []. We are passing the base address to scanf function and scanf() function fills the characters typed at the keyboard into array until enter is pressed. The scanf() places ‘\0’ into array at the end of the input. The printf() function prints the characters from the array on to monitor, leaving the end of the string ‘\0’. The %s used in the scanf() and printf() functions is a format specification for strings.

4.9 DISPLAY OF STRINGS USING DIFFERENT

FORMATTING TECHNIQUES

The printf function with %s format is used to display the strings on the screen. For example, the below statement displays entire string: printf(“%s”, name);

We can also specify the accuracy with which character array (string) is displayed. For example, if you want to display first 5 characters from a field width of 15 characters, you have to write as: printf(“%15.5s”, name); If you include minus sign in the format (e.g. % –10.5s), the string will be printed left justified. printf(“% -10.5s”, name); Example 4. Write a program to display the string “UNIX” in the following format. U UN UNI UNIX UNIX UNI

An Introduction to C

It can be represented by a two-dimensional array of size[3][10] as shown below:

0 1 2 3 4 5 6 7 8 9 m a r t i n p h i l c o l l i n s \

Example 4.

Write a program to initializes 3 names in an array of strings and display them on to monitor

/* Program that initializes 3 names in an array of strings and display them on to monitor.*/

#include main() { int n; char names[3][10]={“Alex”, “Phillip”, “Collins” }; for(n=0; n<3; n++) printf(“%s \n”,names[n] ); }

OUTPUT

Alex Phillip Collins Check Your Progress 4

  1. Which of the following is a static string? A. Static String; B. “Static String”; C. ‘Static String’; D. char string[100]; ……………………………………………………………………………… ……………………………………………………………………………… ………………………………………………………………………………
  2. Which character ends all strings? A. ‘.’ B. ‘ ‘ C. ‘0’ D. ‘n’ ……………………………………………………………………………… ……………………………………………………………………………… ………………………………………………………………………………
  1. What is the Output of the following programs?^ Arrays and Strings

(a) main() { char name[10]=“IGNOU”; printf(“\n %c”, name[0]); printf(“\n %s”, name); }

(b) main() { char s[]=“hello”; int j=0; while( s[j] !=‘\0’ ) printf(“ %c”,s[j++]); }

(c) main() { char str[]=“hello”; printf(“%10.2s”, str); printf(“%-10.2s”, str); } ……………………………………………………………………………… ……………………………………………………………………………… ………………………………………………………………………………

4 Write a program to read 'n' number of lines from the keyboard using a two-dimensional character array (ie., strings). ……………………………………………………………………………… ……………………………………………………………………………… ………………………………………………………………………………

4.11 BUILT IN STRING FUNCTIONS AND

APPLICATIONS

The header file contains some string manipulation functions. The following is a list of the common string managing functions in C.

4.11.1 Strlen Function

The strlen function returns the length of a string. It takes the string name as argument. The syntax is as follows:

n=strlen(str);

where str is name of the string and n is the length of the string, returned by strlen function.

Example 4.

Write a program to read a string from the keyboard and to display the length of the string on to the monitor by using strlen( ) function.