Upload
uma-parameswari
View
53
Download
0
Embed Size (px)
Citation preview
ARRAYSDefinition
An array is a fixed-size sequenced collection of elements of the same data type.
Advantages of arrays
Huge amount of data can be stored under single variable name.
Searching of data item is faster.
2 dimension arrays are used to represent the matrices.
It is helpful in implementing other data structure like linked list, queue,stack.
Types of arrays
One dimensional array. Two dimensional array. Multi dimensional array.
One dimensional array
A list of items can be given one variable name using only one subscript is called single subscripted variable or a one dimensional array.
Declaration of one dimensional array
Syntax :
<data_type> <array_name> [size]
Data_type :It represents the type of array (i.e)float,int,char,string.
Array_name:The name of array.
Size: Size of array represent the total number of element of array, data stored in array with index, we can retrieve data by there index.
Example: int x[7];
1
Initialization of one dimensional arrays
Array can initialized at either of the following :
At run time . At compile time.
Run time initialization
An array can be explicitly initialized at run time.
Syntax:
<data_type> <array_name> [size];
Example: int x[10];
Compile time initialization
The elements of the array can be initialized as the ordinary variables.
Example: int a[5]={1,2,3,4,5};
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[50],i=0,b,c[5]={1,2,3,4,5};
2
clrscr();
printf("How many element you want to enter \n");
scanf("%d", &b);
printf("Enter %d No for array \n", b);
for(i=0 ;i<b ; i++)
{
scanf(" %d ", &arr[i]);
}
//output
printf("\n Element of the array are :- \n");
for(i=0; i<b ; i++)
{
printf("Element of %d position is %d \n", i, arr[i]);
printf(“Elements of %d position is %d\n”,I,c[i]);
}
getch();
}
Output:
How many element you want to enter 2
Enter 2 No for array
6
5
Element of the array are :-
Element of 0 position is
6
3
Element of 0 position is
1
Element of 1 position is
5
Elements of 1 position is
2
Two dimensional array
A list of items can be given one variable name using two subscript is called two dimensional array. One subscript for row and another for column.
SYNTAX:
data-type array_name[row-size][column-size];
EXAMPLE:
int a[3][4];
Initialization of two dimensional arrays
Array can initialized at either of the following :
At run time . At compile time.
4
Run time initialization
An array can be explicitly initialized at run time.
Syntax:
data-type array_name[row-size][column-size];
example: int a[2][2];
Compile time initialization
The elements of the array can be initialized as the ordinary variables.
Example:
int odd[3][2]={1,3,5,7,9,11};
Individual element can also be assigned as:
Odd[0][0]=1;
Odd[0][1]=3;
Odd[1][0]=5;
Odd[1][1]=7;
Odd[2][0]=9;
Odd[2][1]=11;
Reading data from the user:
Nested for loop is used.
Example:
#include<stdio.h>#include<conio.h> void main(){ int m, n, p, q, c, d, k, sum = 0;
5
int first[10][10], second[10][10], multiply[10][10]; printf("Enter the number of rows and columns of first matrix\n"); scanf("%d%d", &m, &n); printf("Enter the number of rows and columns of second matrix\n"); scanf("%d%d", &p, &q); if (n != p) printf("Matrices with entered orders can't be multiplied with each other.\n"); else { printf("Enter the elements of first matrix\n"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) scanf("%d", &first[c][d]); }
printf("Enter the elements of second matrix\n"); for (c = 0; c < p; c++) { for (d = 0; d < q; d++) scanf("%d", &second[c][d]); } for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { for (k = 0; k < p; k++) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } } printf("Product of entered matrices:-\n"); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { printf("%d\t", multiply[c][d]); printf("\n"); } } getch();}
6
Multidimensional array
A list of items can be given one variable name using more than two subscript is called multi dimensional array. The exact limit is determined by the compiler.
SYNTAX:
data-type array_name[s1][s2][s3][s4][s5]……….[sm];
EXAMPLE:
int a[3][4][5];
Dynamic arrays
STATIC 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.
Dynamic arrays:
The process of allocating memory to arrays at run time is known as dynamic memory allocation and the arrays created at run time are called dynamic arrays.
Dynamic arrays are created using pointer variables and memory management functions malloc,calloc and realloc.These functions are included in the header file<stdlib.h>.The dynamic arrays is used to create and manipulate data structures such as linked list,stack and queues.
Character Arrays & Strings
Introduction
A string is a sequence of characters. Any sequence or set of characters defined within double quotation symbols is a constant string. In c it is required to do some meaningful operations on strings they are:
Reading string displaying strings Combining or concatenating strings Copying one string to another. Comparing string & checking whether they are equal Extraction of a portion of a string
7
Declaring & Initializing String Variables
char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};
Then the string month is initializing to January. This is perfectly valid but C offers a special way to initialize strings.
The above string can be initialized as
char month1[]=”January”;
The characters of the string are enclosed within a part of double quotes. The compiler takes care of string enclosed within a pair of double quotes. The compiler takes care of storing the ASCII codes of characters of the string in the memory and also stores the null terminator in the end.
/*String.c string variable*/
#include < stdio.h >
#include<conio.h>void main() { char month[15]; printf (“Enter the string”); gets (month); printf (“The string entered is %s”, month); }
\0 specifies a single character whose ASCII value is zero.
J A N U A R Y \0 ? ? ? ? ? ? ?
Character string terminated by a null character ‘\0’.
A string variable is any valid C variable name & is always declared as an array.
syntax
char string_name[size];
8
The size determines the number of characters in the string name.
Example:
char address[100];
The size of the array should be one byte more than the actual space occupied by the string since the complier appends a null character at the end of the string.
Reading Strings from the terminal:
The function scanf with %s format specification is needed to read the character string from the terminal.
Example:
char address[20]; scanf(“%s”,address);
->Scanf statement has a draw back it just terminates the statement as soon as it finds a blank space, suppose if we type the string new york then only the string new will be read and since there is a blank space after word “new” it will terminate the string.
->The function getchar can be used repeatedly to read a sequence of successive single characters and store it in the array.
We cannot manipulate strings since C does not provide any operators for string. For instance we cannot assign one string to another directly.
For example:
String=”xyz”; String1=string;
are not valid. To copy the chars in one string to another string we may do so on a character to character basis.
9
Reading a Line of Text
To read a line of text with white spaces, we have a special format specifier %[..] called “Edit set conversion code” that can be used to read a line containing a variety of characters.
Example: To terminate a string only when a ‘\n’ (New Line) character is inserted, we need to give the following statement:
scanf(“%[^\n]”,str);
Here, str – string variable
^\n – Describes terminate the reading when ‘\n’ character is encountered
Using getchar and gets Function
getchar() function is used to read a single character from the terminal. By providing a loop to read characters until we provide a newline character, we are facilitating the reading of a line of text.
Example:
int c;
char character;
….
c = 0;
do
{
character = getchar();
line[c++] = character;
}while(character != ‘\n’);
10
We may also use the gets() function present in <stdio.h> header file to read a line of text. It is in the form:
gets(str);
Example:
char line[80];
gets(line);
Writing Strings to Screen
Using printf() function
The format specifier %s can be used to display an array of characters that is terminated by null (\0) character.
Example:printf(“%s”, name);
We can also specify the precision. Example:
%10.4s
Indicates that first four characters are to be printed in a field width of 10 columns. Including a – (minus) sign immediately after the % symbol will print the content left-justified.
For variable specification of width and precision, we use the * symbol. Example:
printf(“%*.*s”,w,s,str);
Using putchar() and puts()
We can use the putchar() function repeatedly to print a string to the screen.
Example:
Void main()
{
char name[6] = “paris”;
for(i=0;i<5;i++)
11
putchar(name[i]);
putchar(‘\n’);
getch();
}
Another convenient way of printing a string to screen is using puts() function present in <stdio.h>. Example:
puts(line);
Arithmetic operations on characters:
We can also manipulate the characters as we manipulate numbers in c language. When ever the system encounters the character data it is automatically converted into a integer value by the system. We can represent a character as a interface by using the following method.
x=’a’; Printf(“%d\n”,x);
Will display 97 on the screen. Arithmetic operations can also be performed on characters for example x=’z’-1; is a valid statement. The ASCII value of ‘z’ is 122 the statement the therefore will assign 121 to variable x.
It is also possible to use character constants in relational expressions for example ch>’a’ && ch < = ’z’ will check whether the character stored in variable ch is a lower case letter.
A character digit can also be converted into its equivalent integer value suppose un the expression
Void main()
{
char character=’8’;
int a;
a=character-‘1’;
12
printf(“%d”,a);
getch();
}
where a is defined as an integer variable & character contains value 8 then a= ASCII value of 8 ASCII value ‘1’=56-49=7.
We can also get the support of the c library function to converts a string of digits into their equivalent integer values the general format of the function in
x=atoi(string);
here x is an integer variable & string is a character array containing string of digits. For example
string=“101”; it will be stored as numeral 101 to x.
Putting Strings Together
We cannot apply the arithmetic addition for joining of two or more strings in the manner
string1 = string2 + string3; or
string1 = string2 + "SACY";
For carrying out the above we need to write a program to copy the contents of the string2 & string3 into string1 one after the other. This process is called concatenation of strings.
strcat() Function
strcat() joins two or more strings together. It takes the following form
strcat(string1, string2);
string1 and string2 are character arrays. When the above function is executed, string2 is appended to string1. It does so by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains unchanged.
strcat function may also append a string constant to a string variable. The following is valid
13
strcat(part1,"SACY");
C also permits nesting of strcat functions. For example
strcat(strcat((string1,string2),string3);
is allowed and concatenates all the three strings together. The resultant string is stored in string1.
String Handling Functions
C language recognizes that string is a different class of array by letting us input and output the array as a unit and are terminated by null character. C library supports a large number of string handling functions that can be used to array out many o f the string manipulations such as:
Length (number of characters in the string). Concatentation (adding two are more strings) Comparing two strings. Substring (Extract substring from a given string) Copy(copies one string over another)
To do all the operations described here it is essential to include<string.h> library header file in the program.
strlen() function:
This function counts and returns the number of characters in a string. The length does not include a null character.
Syntax: n=strlen(string);
Where n is integer variable. Which receives the value of length of the string.
14
Example
length=strlen(“Hollywood”);
The function will assign number of characters 9 in the string to a integer variable length.Result is length=9.
strcat() function:
when you combine two strings, you add the characters of one string to the end of other string. This process is called concatenation. The strcat() function joins 2 strings together. It takes the following form
strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1. the string at string2 remains unchanged.
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcpy(string1,”sri”); strcpy(string2,”Bhagavan”); Printf(“%s”,strcat(string1,string2);
getch();
}
15
From the above program segment the value of string1 becomes sribhagavan. The string at str2 remains unchanged as bhagawan. Result string1= sribhagavan
strcmp function:
In c you cannot directly compare the value of 2 strings in a condition like:
if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given below:
strcmp(string1,string2)
String1 & string2 may be string variables or string constants. String1, & string2 may be string variables or string constants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcmp(“Newyork”,”Newyork”);//will return zero because 2 strings are equal.
strcmp(“their”,”therr”);//will return a 9 which is the numeric difference between ASCII ‘i’ and ASCII ’r’. strcmp(“The”, “the”)// will return 32 which is the numeric difference between ASCII “T” & ASCII “t”.
getch();
}
strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.
16
Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcmpi(“THE”,”the”);// will return 0.
getch();
}
strcpy() function:
C does not allow you to assign the characters to a string directly as in the statement name=”Robert”; Instead use the strcpy(0 function found in most compilers the syntax of the function is illustrated below.
strcpy(string1,string2);
Strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcpy(Name,”Robert”);
getch();
}
In the above example Robert is assigned to the string called name. Result:Name=Robert.
17
Other string functions
strncpy//string copy strncmp//string compare strncat//string concatenation strstr//finding sub string
strncpy//string copy
This is three parameter function and is invoked as follows.
Syntax:strncpy(s1,s2,n);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
char s2=”ammukutti”;
strncpy(s1,s2,5);
s1[6]=’\0’;
printf(“%s”,s1);
getch();
}
Result:ammuk
strncmp//string compare
syntax:strncmp(s1,s2,n);
this compares left most n characters of s1 and s2 and returns.
(a) 0 if they are equal.(b) Negative number,if s1 sub-string is less than s2.(c) Positive number otherwise negative number.
18
strncat//string concatenation
syntax:strncat(s1,s2,n);
Concatenate the left most n characters of s2 to the end of s1.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char s1=”Bala”, s2=”ammukutti”;
strncat(s1,s2,5);
printf(“%s”,s1);
getch();
}
Result:Balaammuk.
strstr//finding sub string
It is a two parameter function that can be used to locate a sub-string in a string.
Syntax:strstr(s1,s2);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
19
Char s1=”Abacus”, s2=”cus”;
if(strstr(s1,s2)==NULL)
printf(“sub string is not found”);
else
printf(“s2 is a substring of s1);
getch();
}
Strchr//determine the existence of a first occurrence of character in a string
Example:
s1=”Mohamed”;
strchr(s1,”M”);
strrchr//last occurrence of character in a string
Example:
s1=”Mohamed”;
strrchr(s1,”d”);
20