Array & String

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Chapter 4

Array & String


Array

• An array is a collection of similar data type value in a single


variable. It is a derived data type in C, which is constructed from
fundamental data type of C language.

Array of 10 elements
Array
• Advantage of array
• Code Optimization: Less code is required, one variable can store
numbers of value.
• Easy to traverse data: By using array easily retrieve the data of array.
• Easy to sort data: Easily short the data using swapping technique
• Random Access: With the help of array index you can randomly access
any elements from array.
• Dis-Advantage of array
• Fixed Size: Whatever size, we define at the time of declaration of array,
we can not change their size, if you need more memory in that time you
can not increase memory size, and if you need less memory in that case
also wastage of memory.
Declaring Array
• To declare an array in C you need to declare datatype and size of
an array.
• Syntax
• datatype arrayname[SIZE];
• Example
• int rollno[10];
Initializing Array
• Initializing is a process to initialize the value in array variable. This is happen
in two ways, initialize array one by one or all elements are initializing once.
1) Initialization of array one by one
int arr[5];
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;
2) Initialization of array at once
int arr[]={10,20,30,40,50};
Accessing Array Elements

• We can access array elements with the help of index value of


element.
• Example
int arr[]={10,20,30,40,50};
arr[3]; // here 3 is index value and it return 40
#include<stdio.h>
Example of array
#include<conio.h>
void main()
{
int i, marks[]={80, 62, 70, 90, 98}; //declaration and initialization of array
clrscr();
//traversal of array
for(i=0;i<5;i++)
{
printf("\n %d",marks[i]);
}
getch();
}
2-dimentional array
• In 2-dimentional elements are arranged in row and column
format.
• When we are working with 2-dimentional array we require to
refer 2-subscript operator which indicates row and column sizes.
• Themain memory of 2-dimentional array is rows and sub-
memory is columns.
• On 2-dimentional array when we are referring one-subscript
operator then if gives row address, 2-subscript operator will gives
element.
• On 2-dimentional array arrayName always gives main memory
that is 1st row base address, arrayName will gives next row base
address.
2-dimentional array
• Syntax
• datatype arrayname[rowsize][columnsize];
• Initialization of 2D Array
• There are two ways to initialize a two Dimensional arrays during
declaration.
1) int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
2) int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
#include<stdio.h> Example 2D Array
#include<conio.h>
void main(){
int abc[5][4];
int i, j;
for(i=0; i<5; i++)
{
for(j=0;j<4;j++)
{
scanf("%d", &abc[i][j]);
}
}
getch();}
Simple Two dimensional(2D) Array Example
#include<stdio.h>
#include<conio.h>
void main(){
int disp[2][3];
int i, j;
for(i=0; i<2; i++)
{ Output:
for(j=0;j<3;j++) Enter value for disp[0][0]:1
{ Enter value for disp[0][1]:2
scanf("%d", &disp[i][j]); Enter value for disp[0][2]:3
} Enter value for disp[1][0]:4
} Enter value for disp[1][1]:5
printf("Two Dimensional array elements:\n"); Enter value for disp[1][2]:6
for(i=0; i<2; i++) Two Dimensional array elements:
{ 123
for(j=0;j<3;j++) 456
{
printf("%d ", disp[i][j]);
if(j==2)
{
printf("\n");
}
}
} getch(); }
Important points related to array
• Always size of the array must be an unsigned integer value which is greater
than ‘0' only. In declaration of the array size must be required to mention, if
size is not mention then compiler will give an error.
Example
int arr[]; //error
• In declaration of the array, size must be assigned type which value is greater
than 0. In initialization of the array if specific number of values are not
initialized it then rest of all elements will be initialized with it '0'.
Example
int arr[5]={10,20}; // yes valid
arr[0]=10;
arr[1]=20;
arr[2], arr[3], arr[4]; // initialized with zero
Important points for Array

• In implementation when we required 'n' number of variables of


same data type then go for an array.
• When we are working with arrays always memory will created in
continues memory location, so randomly we can access the data.
• In arrays all elements will share same name with unique
identification value called index.
• Always array index will start with '0' and end with 'size-1'.
• When we are working with array compile time memory
management will occur that is static memory allocation.
String
• String is a collection of character or group of character.
• It is achieve in C language by using array character. The
string in C language is one-dimensional array of character
which is terminated by a null character ‘ \0 '. In other
words string is a collection of character which is enclose
between double cotes ( " " ).
• Note: Strings are always enclosed within double quotes” ”.
Whereas, character is enclosed within single quotes ‘ ‘ in C.
Declaration of string

• Stringsare declared in C in similar manner as arrays. Only


difference is that, strings are of char type.
• Syntax
• char stringname[size];
• Example
• char s[5];

1000 1001 1002 1003 1004


Memory address
Initializing string

• String are initialize into various way in c language;


• Example
1) char str[]="abcd";
OR
2) char str[5]="abcd";
OR
3) char str[5]={'a','b','c','d','\0'}; String Initialization
OR
4) char str[]={'a','b','c','d','\0'};
Reading(input)String from user

• Example
char str[5];
scanf(“ %s",str); //no & in string
Example

#include<stdio.h>
#include<conio.h>
Note: String variable can only take
void main() only one word. It is because when
{ white space is encountered, the
scanf() function terminates. to over
char name[10];
come this problem you can use gets()
printf("Enter name: "); function.
scanf("%s",name);
printf("Your name is: %s.",name);
getch();
}
gets() & puts()
• gets()
• gets() are used to get input as a string from keyword, using gets() we can
input more than one word at a time.
• Syntax
char str[5];
gets(str);
• puts()
• puts() are used to print output on screen, generally puts() function are
used with gets() function.
• Syntax
puts(str);
Example of String program
gets() & puts()
#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
printf("Enter any string: ");
gets(str);
printf("String are: ");
puts(str);
getch();
}
C Library String functions
(Built in String Functions)
• All the library function of String is available in string.h header file.
No Function Purpose

1 strcpy(s1, s2); Copies string s2 into string s1.


2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0
4 strcmp(s1, s2);
if s1>s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
7 Strrev(s1); Reverse the string
8 strlwr(s1); Converts string in lowercase
9 Strupr(s1); Converts string in uppercase
strcpy(s1,s2);
It copies the string str2 into string str1, including the end character (terminator char ‘ \0 ’).

#include <stdio.h>
#include<conio.h>
#include <string.h>
Void main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
Output:
printf("String s1 is: %s", s1); String s1 is: string 2: I’m gonna copied into s1
getch();
strcat(s1,s2);
It concatenates two strings and returns the concatenated string.
#include <stdio.h>
#include<conio.h>
#include <string.h>
void main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
getch(); Output:
Output string after concatenation: HelloWorld
}
strncat(s1,s2,n);
It concatenates n characters of str2 to string str1. A terminator char (‘.\ 0 .’) will always be appended
at the end of the concatenated string.\
#include <stdio.h>
#include<conio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
getch(); Output:
Concatenation using strncat: HelloWor
}
strlen(s1);
It returns the length of the string without including end character (terminating char ‘\0’).

#include <stdio.h>
#include<conio.h>
#include <string.h>
void main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1)); Output:
Length of string str1: 13
getch();
} strlen vs sizeof
strlen(str1) returned value 13.
sizeof(str1) would return value 20 as the array size is 20 (see the first statement in main function).
strnlen(s1,n);
It returns length of the string if it is less than the value specified for maxlen (maximum
length) otherwise it returns maxlen value.
#include <stdio.h>
#include<conio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
getch(); Output:
Length of string str1 when maxlen is 30: 13
} Length of string str1 when maxlen is 10: 10
strcmp(s1,s2);
It compares the two strings and returns an integer value. If both the strings are same (equal) then this
function would return 0 otherwise it may return a negative or positive value based on the comparison.
If string1 < string2 -result in a negative value.
If string1 > string2 -return positive value.
If string1 == string2 -result is 0(zero)
#include <stdio.h>
#include <string.h>
void main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
Output:
{ string 1 and 2 are different
printf("string 1 and 2 are different");
}getch();}
strncmp(s1,s2,n);
It compares both the string till n characters or in other words it compares first n characters
#include <stdio.h> of both the strings.
#include<conio.h>
#include <string.h>
void main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different"); Output:
} string1 and string 2 are equal
getch();
}
strchr(s1,ch);
It searches string str for character ch.
#include <stdio.h>
#include<conio.h>
#include <string.h>
void main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
getch(); Output:
f function strchr
}
strstr(s1,s2);
It is similar to strchr, except that it searches for string srch_term instead of
a single char.
#include <stdio.h>
#include<conio.h>
#include <string.h>
void main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, “Begi”));
getch();
}
Output:
Output string is: BeginnersBook.COM
Program to check palindrome string
#include <stdio.h>
#include<conio.h>
#include <string.h>
void main()
{
char a[100], b[100];
printf("Enter a string to check if it is a palindrome\n");
gets(a);
strcpy(b, a); // Copying input string
strrev(b); // Reversing the string
if (strcmp(a, b) == 0) // Comparing input string with the reverse string
printf("The string is a palindrome.\n");
else
printf("The string isn't a palindrome.\n");
getch();
}
Important points for Declaration of string
• In declaration of string size must be required to mention otherwise it gives
an error.
• char str[]; // Invalid
• char str[10]; // Valid
• In declaration of the string size must be unsigned integer value (not -ve or
zero value) which is greater than zero only.
• char str[]; // Invalid
• char str[0]; // Invalid
• char str[-1]; // Invalid
• char str[10]; // Valid
Important points for Initialization of the string
• In Initialization of the string if the specific number of character are not initialized it then rest
of all character will be initialized with NULL.
char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
str[3]; ---> NULL
str[4]; ---> NULL
• In initialization of the string we can not initialized more than size of string elements.
• char str[2]={'5','+','A','B'}; // Invalid
• In initialization of the string the size is optional in this case how many variable elements are
initialized it, that array element will created.
• char str[]={'5','+','A','B'}; // Valid
• sizeof(str) --> 4byte
• Thank you

You might also like