Arrays Strings-Program-Notes
Arrays Strings-Program-Notes
UNIT IV
ARRAYS
An array is a collection of similar data items that are stored under a common name.
The above ststement declares the name as an array of character initialisez with the string
‘LAK’
Examples
int a[3] = {2, 3, 5};
char ch[20] = "TechnoExam" ;
float stax[3] = {5003.23, 1940.32, 123.20} ;
An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array.
For example:
int salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable.
Following is an example which will use all the above mentioned three concepts viz.
declaration, assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
Output:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Processing an Array
Single operations which involve entire arrays are not permitted in C. Thus, if a and b
are similar arrays (i.e., same data type, same dimensionality and same size), assignment
operations, comparison operations, etc. must be carried out on an element-by-element
basis.
getch();
}
Output :
Enter three numbers: 9 4 6
Numbers are: 9 4 6
OUTPUT
Enter the elements
1 2 3
2 2 3
3 3 3
sum=6
Limitations of two dimensional array:
We cannot delete any element in 2D array.
If we don’t know that how many elements have to be stored in a memory in
advance, then there will be memory wastage if large array size is specified.
In some cases there is a need for arrays with a third or even a fourth dimension.
These arrays are called multidimensional arrays.
These multidimensional arrays relatively infrequently.
They can facilitate an understanding of the data, improve the readability of
algorithms, and facilitate processing since the data can be processed through the use
of three or more nested loops.
For example, with input data on temperatures referenced by day, city, county, and
state, day would be the first dimension, city would be the second dimension, county
would be the third dimension, and state would be the fourth dimension of the array.
In any case, any temperature could be found as long as the day, the city, the county,
and the state are known.
A multidimensional array allows the programmer to use one array for all the data.
Fig.4.4 shows a block of memory locations and their reference names for a three-
dimensional array. The recommended variable names for the indexes of a three
dimensional array are Row for row, Column for column, and Depth for depth.
For a fourth dimension, Volume for volume is used. These arrays are processed
much like two-dimensional arrays.
4 .9 | Arrays, Strings and Pointers
4.6 STRINGS
Definition
A string is an array of characters terminated by a special symbol named as null
character (represented as ‘\0’). Hence null character is also named as string-
termination character. It is used to identify the length of the string and expresses the
end of string.
4.6.1Defining a string
A string definition expressed as
char string-name [size];.
Size is a positive-valued integer expression which indicates the number of elements in
the string including null character.
Ex:
char name [50];
/* name is a string that can consist of maximum 50 characters */
The length of actual string is 7. In the case 8th element of the array i.e. name [7] location
will be used to store null character, as shown in Fig 4.5 & 4.6.
W E L C O M E ‘\0’
[0] [1] [2] [3] [4] [5] [6] [7] [49]
Fig 4.5: String storage
Null character is used to identify the string termination and no processing is done after
the identification of null character.
Thus reading, writing, copying a string will be processed up to the null character’s
position i.e. up to subscript number 7 in above example.
The null character is not counted towards the length of the string, but takes memory of
one element. Null character cannot be read or written, but is used internally only.
The strings can be initialized at the time of definition. It can also be initialized using
double quotes.
EX:
char str[30] = ”Hello World”;
char str[[30] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’};
H E l l o W o r l D \0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [29]
In both cases, the null character will get appended at the last automatically. Both of
these initializations will result into storage as shown in figure.
4.6.4 Reading and Writing a String
A string can be read and written by using a single scanf and printf function using %s (s
stands for string) and no loop is needed, which was compulsory for reading & writing
arrays of other data types.
Example :
/** Read a string from keyboard and display the same on screen **/
#include<stdio.h>
#define MAX_SIZE 50
main()
{
char str [Max_SIZE];
4 .11 | Arrays, Strings and Pointers
This scanf function reads a string from keyboard till a whitespace character (blank, tab,
newline) is encountered.
After the reading is complete, the null character is appended automatically at the next
position inside the array.
In first case, the input word programming gets stored at str[0] to str[10] and null
character is appended at str[11].
The scanf function with %s can be used to read strings not consisting of spaces. So if we
gave C Program as input, only c gets read. So the null character is appended at str[1] in
case the input was “c program”.
If we are interested to read a string consisting of blank characters as well e.g. we want
to read a line of text, gets function is the easiest way to do it.
But the string.h header file must be included to use gets function.
Th e gets function keeps on reading the characters till the newline character (Enter key)
is not pressed.
Similarly for printing a string puts function can be used. The gets and puts functions can
be used as follows:
gets (string-name);
puts (string);
where the string-name refers to the variable name of string. The puts function can
be used to print a constant string written within double quotes as well as string
variable.
The gets function also appends null character at the end of the string automatically, as
done in case of scanf with %s.
Example:
#include<stdio.h>
#include<string.h>
#define MAX_SIZE 50
main()
4 .12 | Arrays, Strings and Pointers
{
char str [MAX_Size];
printf(“Enter a line of text of maximum %d characters:”, MAX_SIZE);
gets(str);
puts(“ The entered line is :”);
puts(str);
}
Output:
Enter a line of text of maximum 49 characters: Hello World
The entered line is:
Hello world
4.7 POINTERS
A Pointer is a variable. It can contain the memory address of the variable.
A pointer is a variable that represents the location (rather than the value) of a data
item, such as a variable, an array element, structure.
Examples
char *c;
int i, *ptri;
float f,*ptrf;
int i;
int *ptr=&i;
The first line declares i to be integer type variable and the second line declares ptri to
be a pointer variable whose object is an integer point quantity. In addition, the
address of i is initially assigned to ptr as shown in Fig.4.7 below
ptr
1200
Pv represents v’s address, not its value. Thus pv is referred to as a pointer variable
shown in Fig 4.8.
#include<stdio.h>
main()
{
int a=22;
printf(“\n Value of a=%d”,*a);
printf(“\n Address of a=%u”,&a);
printf(“\n Value at address %u=%d”,&a,*(&a));
}
OUTPUT
Value of a=22
Address of a=4000
Value at address 4000=22
4 .17 | Arrays, Strings and Pointers
ADDITIONAL PROGRAMS
5
Enter Array elements
20
21
19
18
20
Average=19.600
33
44
55
#include<stdio.h>
#include<conio.h>
void main()
{
4 .21 | Arrays, Strings and Pointers
int num[50],i,size,sum=0;
printf("Enter size of an array\n");
scanf("%d", &size);
printf("Enter Array elements\n");
for(i=0;i<size;i++)
scanf("%d",&num[i]);
for(i=0;i<size;i=i+2)
sum=sum + num[i];
printf("sum=%d",sum);
getch();
}
OUTPUT:
Enter size of an array
5
Enter Array elements
1
2
3
4
5
Sum of even position=9
{ if(mark[i]>=50)
{
count++;
}
}
printf("No.of pass mark:%d",count);
getch();
}
OUTPUT:
Enter size of an array
5
Enter marks
50
55
23
45
78
No. of pass marks:3
}
if(flag==0)
printf("Value not found\n");
getch();
}
OUTPUT:
Enter the size of array
5
Enter Array elements
44
55
66
77
88
88
First array
44
55
66
77
88
Second array
44
55
66
77
88
88
Reverse array
88
77
66
55
44
2
2
2
2
2
2
Enter Second Matrix:3
3
3
3
3
3
3
3
3
The First Matrix is:
2 2 2
2 2 2
2 2 2
The Second Matrix is :
3 3 3
3 3 3
3 3 3
Addition Of Two Matrices :
5 5 5
5 5 5
5 5 5
//Multiplication Logic
for (i = 0; i < r1; i++) {
for (j = 0; j <c2; j++) {
c[i][j]=0;
for (k = 0; k < c1; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
3
Enter elements of Matrix :
2
2
3
4
5
6
The Matrix is:
2 2 3
4 5 6
The Transpose Matrix is :
2 4
2 5
3 6
#include<stdio.h>
int main()
{
int a[5][5], r1,c1,i, j,sum=0;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter elements of Matrix : \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", &a[i][j]);
}
}
printf("The Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
printf(" %d ", a[i][j]);
}
printf("\n");
}
for (i = 0; i <c1; i++) {
4 .33 | Arrays, Strings and Pointers
#include<stdio.h>
int main( )
{
int a[5][5], r1,c1,i, j;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter elements of Matrix : \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", &a[i][j]);
}
}
printf("The Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
4 .34 | Arrays, Strings and Pointers
OUTPUT:
Enter size of First Matrix :
3
3
Enter elements of Matrix :
2
3
4
1
2
6
7
4
5
The Matrix is:
2 3 4
1 2 6
7 4 5
Upper matrix:
2 3 4
0 2 6
0 0 5
#include<stdio.h>
int main( )
{
int a[5][5], r1,c1,i, j;
printf("\nEnter size of First Matrix : \n");
scanf("%d%d",&r1,&c1);
printf("\nEnter elements of Matrix : \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", &a[i][j]);
}
}
printf("The Matrix is: \n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
printf(" %d ", a[i][j]);
}
printf("\n");
}
printf(“Diagonal elements :\n”);
for (i = 0; i <c1; i++) {
for (j = 0; j < r1; j++) {
if(i==j)
printf("%d\t",a[i][j]);
else
printf(“\t”);
}
printf("\n");
}
return (0);
}
OUTPUT:
Enter size of Matrix :
3 3
Enter Element of Matrix :
5
6
4
4 .38 | Arrays, Strings and Pointers
3
2
5
7
6
5
Matrix is:
564
325
765
The Diagonal Element of Matrix is:
5
2
5
20. Program to find the length of string without string functions
#include<stdio.h>
#include<conio.h>
void main( )
{
char s[20];
int i;
printf("Enter the string\n");
scanf("%s",s);
i=0;
while(s[i]!='\0')
i++;
printf(" No. of characters:%d", i);
getch();
}
OUTPUT:
Enter the string
Apple
No. of characters:5
21. Program to find the length of string using string functions
#include<stdio.h>
#include<conio.h>
4 .39 | Arrays, Strings and Pointers
void main( )
{
char s[20]; int i;
printf("Enter the string\n");
scanf("%s",s);
i=strlen(s);
printf(" No. of characters:%d", i);
getch();
}
OUTPUT:
Enter the string
Apple
No. of characters:5
22. Program to copy a string
#include<stdio.h>
#include<conio.h>
void main( )
{
char s1[20],s2[20];
printf("Enter the string\n");
scanf("%s",s1);
strcpy(s2,s1);
printf("Copied string: %s", s2);
getch();
}
OUTPUT:
Enter the string
Lord
Copied string :Lord
#include<stdio.h>
#include<conio.h>
void main( )
{
char s1[20],s2[20];
printf("Enter the string \n");
4 .40 | Arrays, Strings and Pointers
scanf("%s",s1);
for(int i=0;s1[i]!='\0';i++)
s2[i]= s1[i];
printf("Copied string: %s", s2);
getch();
}
OUTPUT:
Enter the string
Lord
Copied string :Lord
pink
red
white
OUTPUT:
Enter the first point
8 10
Enter the second point
5 6
Distance= 5
break;
case 6: exit(0);
break;
}
printf("Result=%d",result);
}while(opt<=5);
getch();
}
OUTPUT:
Enter two numbers
67
Choose the option(1-5) from the following menu
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.Exit
3
Result=42
Choose the option(1-5) from the following menu
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.Exit
6
4 .46 | Arrays, Strings and Pointers