Unit 2 PPT-1
Unit 2 PPT-1
Arrays
Introduction
• We have used fundamental data types namely char, int, float which
are very useful.
• But the variable of these types stores only one value at a given
time.
• In various applications, we need to handle large amount of data in
terms of reading, processing and printing.
• To process such data we require a data type that would facilitate
efficient storing, accessing and manipulation of data items.
• C supports a derived data type known as array.
• An array is a fixed-size sequenced collection of elements of the
same data type.
• An array can also be defined as follows...
• An array is a collection of similar data items stored in continuous
memory locations with single name.
• Examples:
– List of numbers: Test scores of a class of students.
– List of names: list of employees in a company.
• Array provides a convenient structure for representing data, so it is
classified as data structures in C.
• For example, we can use array name salary to represent a set of salaries of
a group of employees in an organization.
• To refer to the individual salaries by writing a number called index or
subscript in brackets after the array name.
elements salary
0 1 2 3 ... ...
number[0] = 15;
number[0]
number[1] = 8;
number[1]
number[2] number[2] = 84;
number[3] number[3] =14;
number[4] number[4] =29;
Declaration of 1-D array
• Array declaration
type variable_name[ size ];
Type of elements
that will be in array Maximum number of elements
stored inside the array
float height[50];
int group[4*5];
int marks[2];
scanf(“%d %d %d”, &marks[0], &marks[1]);
• It initializes the array elements with values entered through the
keyboard.
Read and display array elements
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5], i;
printf(“enter array elements:”);
for(i = 0; i < 5; i++)
{
scanf("%d", &arr[i]);
}
printf("\nPrinting elements of the array: \n\n");
for(i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
getch();
}
Program to find average marks obtained by 10 students in a test
#include<stdio.h>
void main()
{
int sum=0, avg, i, marks[10];
for(i=0;i<10;i++)
{
printf("Enter marks:");
scanf("%d",&marks[i]); or scanf("%d",(marks+i));
}
for(i=0;i<10;i++)
{
sum=sum+ marks[i]); or sum=sum+ *(marks+i);
}
avg=sum/10;
printf("\nAverage marks= %d\n", avg); or printf("\nAverage marks= %d\n", sum/10);
}
Notations for retrieving array elements
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={25,23,21,42};
int i;
clrscr();
for(i=0;i<4;i++)
{
printf("address=%u, ",&a[i]);
printf("a[%d]=%d %d %d %d \n",i,a[i], *(a+i), *(i+a), i[a]);
}
getch();
}
2-Dimensional array
• Two dimensional array is called a matrix.
• Declaration: columns
rows
Row 0 101 56
Row 1 102 80
Row 2 103 33
Row 3 104 78
H E L L O \0
65520 65521 65522 65523 65524 65525
Memory allocation of character array
#include<conio.h>
void main()
{
char name[]= { 'H', 'E', 'L', 'L', 'O', '\0'};
int i=0;
clrscr();
while(i<5)
{
printf("'%c' = %u\n", name[i], &name[i]);
i++;
}
getch();
}
• while loop condition i<5 can be replaced by name[i]!=‘\0’ as each
character array always ends with a ‘\0’.
• C provides a shortcut to declare a string
• Ex: char name[] = “HELLO”;
• ‘\0’ is not required, C inserts the null character automatically.
• The %s used in printf() is a format specification for printing out a
string.
• The same specification can be used to receive a string from
keyboard using scanf().
String accessing
#include<conio.h>
void main()
{
char name[]= "HELLO", name2[10]; \\ sets aside 10 bytes under the array name2
int i=0;
clrscr();
printf("\n");
while(name[i]!='\0')
{
printf("%c", name[i]);
i++;
}
printf("\nEnter your name: ");
scanf("%s", name2); \\ fills in the characters until enter key is hit then places ‘\0’ in the array
printf("Your name is %s.\n",name2);
getch();
}
• While entering the string using scanf()
– Length of the string should not exceed the dimension of he
character array. Since compiler doesn’t perform bound checking.
– scanf() is not capable of receiving multi-word strings. Therefore,
names such as ‘Michel Jackson’ would be unacceptable.
• String I/O functions in C
– gets() is used to receive multi-word strings from keyboard.
– puts() is used to print multi-word strings.
A program to show how gets() and puts() functions are used
#include<conio.h>
void main()
{
char name[20];
clrscr();
printf("Enter your name: ");
gets(name);
puts("Hello!");
puts(name);
getch();
}
String Functions
• C provides a wide range of string functions for
performing different string tasks
• Examples
strlen(str) - calculate string length
strcpy(dst,src) - copy string at src to dst
strcmp(str1,str2) - compare str1 to str2
• Functions come from the utility library string.h
– #include <string.h> to use
String Length
Syntax: int strlen(char *str)
returns the length (integer) of the string argument
counts the number of characters until an \0 encountered
does not count \0 char
Example:
char str1 = “hello”;
X=strlen(str1) //x is 5
Copying a String
Syntax:
char *strcpy(char *dst, char *src)
copies the characters (including the \0) from the source string (src)
to the destination string (dst)
dst should have enough space to receive entire string (if not, other
data may get written over)
if the two strings overlap (e.g., copying a string onto itself) the
results are unpredictable
return value is the destination string (dst)
char *strncpy(char *dst, char *src, int n)
similar to strcpy, but the copy stops after n characters
if n non-null (not \0) characters are copied, then no \0 is copied
String Comparison
Syntax:
int strcmp(char *str1, char *str2)
compares str1 to str2, returns a value based on the first character
they differ at:
less than 0
if ASCII value of the character they differ at is smaller for str1
or if str1 starts the same as str2 (and str2 is longer)
greater than 0
if ASCII value of the character they differ at is larger for str1
or if str2 starts the same as str1 (and str1 is longer)
0 if the two strings do not differ
String Comparison (cont)
strcmp examples:
strcmp(“hello”,”hello”) -- returns 0
strcmp(“yello”,”hello”) -- returns value > 0
strcmp(“Hello”,”hello”) -- returns value < 0
strcmp(“hello”,”hello there”) -- returns value < 0
strcmp(“some diff”,”some dift”) -- returns value < 0
expression for determining if two strings s1,s2 hold the
same string value:
!strcmp(s1,s2)
String Comparison (cont)
Sometimes we only want to compare first n chars:
int strncmp(char *s1, char *s2, int n)
Works the same as strcmp except that it stops at the
nth character
looks at less than n characters if either string is shorter than
n
strcmp(“some diff”,”some DIFF”) -- returns value > 0
strncmp(“some diff”,”some DIFF”,4) -- returns 0
String Comparison (ignoring case)
Syntax:
int strcasecmp(char *str1, char *str2)
similar to strcmp except that upper and lower case characters (e.g.,
‘a’ and ‘A’) are considered to be equal
int strncasecmp(char *str1, char *str2, int n)
version of strncmp that ignores case
String Concatenation
Syntax:
char *strcat(char *dstS, char *addS)
appends the string at addS to the string dstS (after dstS’s delimiter)
returns the string dstS
can cause problems if the resulting string is too long to fit in dstS
char *strncat(char *dstS, char *addS, int n)
appends the first n characters of addS to dstS
if less than n characters in addS only the characters in addS
appended
always appends a \0 character
Searching for a Character/String
Syntax:
char *strchr(char *str, int ch)
returns a pointer (a char *) to the first occurrence of ch in str
returns NULL if ch does not occur in str
can subtract original pointer from result pointer to determine which
character in array
char *strstr(char *str, char *searchstr)
similar to strchr, but looks for the first occurrence of the string
searchstr in str
char *strrchr(char *str, int ch)
similar to strchr except that the search starts from the end of string
str and works backward
String Spans (Searching)
• Syntax: int strspn(char *str, char *cset)
– specify a set of characters as a string cset
– strspn searches for the first character in str that is not part of
cset
– returns the number of characters in set found before first non-
set character found
• Syntax: int strcspn(char *str, char *cset)
– similar to strspn except that it stops when a character that is
part of the set is found
• Examples:
– strspn(“a vowel”,”bvcwl”) returns 2
– strcspn(“a vowel”,”@,*e”) returns 5
String functions
• strlen()
– Counts the number of characters in the string.
– Ex:
char array[] = “Dhoni”;
int len1, len2;
len1 = strlen(array);
len2 = strlen(“Pawan Kalyan”);
• strcpy()
– Copies the contents of one string into another.
– The base addresses of the source and target strings should be supplied
to this function.
– Ex:
char source[]= “Monalisa”;
char target[20];
strcpy (target , source);
A program to illustrate strlen() and strcpy()
#include<conio.h>
#include<string.h>
void main()
{
char arr1[] = "Hello";
char source[] = "Monalisa", target[20];
int l1, l2;
clrscr();
l1=strlen(arr1);
l2=strlen("Pawan Kalyan");
printf("\nLength of '%s' = %d", arr1, l1);
printf("\nLength of 'Pawan kalyan' = %d", l2);
strcpy(target, source);
printf("\nSource =");
puts(source);
printf("\nTarget = ");
puts(target);
getch();
}
• strcat()
– Concatenates the source string at the end of the target string.
– Ex: “Gabbar” and “Singh” on concatenation becomes
“GabbarSingh”.
• strcmp()
– This function compares 2 strings to find out whether they are
same or different.
– 2 strings are compared char by char until there is a mismatch or
end of the one the strings is reached (whichever occurs first).
– If 2 strings are identical then this function returns zero.
– Else it returns the numeric difference between the ASCII values
of he first non-matching pair of char.
A program to illustrate strcat() and strcmp()
#include<stdio.h>
#include<string.h>
void main()
{
char source[] = "Hello";
char target[] = "Monalisa";
char str1[]="Jerry";
char str2[]="Ferry";
int i, j ,k;
printf("Source = %s \n", source);
strcat(target, source);
printf("Target = %s \n", target);
i=strcmp(str1, "Jerry");
j=strcmp(str1,str2);
k=strcmp(str1,"Jerry boy");
printf("\n %d %d %d\n", i, j, k);
}
String/Data Conversion
#include<stdio.h>
void main()
{
//atoi: alphabet to integer
char str[]="2019";
Output:
//str=str+3;
Year: 2022
int yr = atoi(str); 101000001
yr = yr+3; 1
printf("Year: %d\n",yr);
//itoa: integer to alphabet
int num = 321;
char snum[20];
itoa(num, snum, 2);
printf("%s\n", snum);
printf("%c ",snum[2]);
}
C - scanf() and sprintf() function
#include <stdio.h>
const int SIZE = 3;
void main()
{
// creating an array
int arr[] = { 1, 2, 3 };
// we can make an integer pointer array to store the address of array elements
int i, *ptr[SIZE];
for (i = 0; i < SIZE; i++) {
// assigning the address of integer.
ptr[i] = &arr[i];
}
// printing values using pointer Output:
for (i = 0; i < SIZE; i++) { Value of arr[0] = 1
Value of arr[1] = 2
printf("Value of arr[%d] = %d\n", i, *ptr[i]); Value of arr[2] = 3
}
}
void pointer
• Pointer to void is the concept of defining a pointer variable
that is independent of datatype.
• void pointer is a pointer variable used to store the address of
variable of any datatype.
• "void“ keyword is used to create void pointer.
• Declaration:
void *pointer_name ;
Program to illustrate void pointer
#include<conio.h>
int main()
{
int a=10 ;
float b ;
char c ;
void *ptr ;
clrscr() ;
ptr = &a ;
printf("Address of integer variable a = %u\n", ptr) ;
ptr = &b ;
printf("Address of float variable b = %u\n", ptr) ;
ptr = &c ;
printf("Address of character variable c = %u\n", ptr) ;
getch();
return 0;
}
Pointers to arrays
#include<conio.h>
void main()
{
int arr[]={5,10,15,20,25,30};
int i, *ptr;
clrscr();
ptr = &arr[0];
for(i=0;i<6;i++)
{
printf("arr[%d] = %d ",i,*ptr);
printf("address = %u\n",ptr);
ptr++;
}
getch();
}
Program to illustrate accessing 1D array elements using
value at address operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
int i;
clrscr();
printf("Enter 5 integer elements\n");
for(i=0;i<5;i++)
{
scanf("%d", a+i);
}
for(i=0;i<5;i++)
{
printf("address=%u, ",&a[i]);
printf("a[%d]=%d %d %d %d \n", i, a[i], *(a+i), *(i+a), i[a]);
}
getch();
}
Accessing 2-Dimensional arrays using pointers