0% found this document useful (0 votes)
4 views

arraypdf

The document discusses the concept of arrays in programming, highlighting their efficiency in storing multiple values compared to individual variables. It explains the declaration, initialization, and accessing of array elements, as well as the differences between control statements like break, continue, return, and exit. Additionally, it covers multidimensional arrays, their syntax, and provides sample code for various array operations.

Uploaded by

rimipo8410
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

arraypdf

The document discusses the concept of arrays in programming, highlighting their efficiency in storing multiple values compared to individual variables. It explains the declaration, initialization, and accessing of array elements, as well as the differences between control statements like break, continue, return, and exit. Additionally, it covers multidimensional arrays, their syntax, and provides sample code for various array operations.

Uploaded by

rimipo8410
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Prepared by:

Sushant Paudel
PROBLEM
If we need to sort 30 integer type data and
display them, we have to define 30
variables of integer data type as follows:
int a, b, c,…, z, a1, a2, a3, a4;
This is possible but inefficient.
Further as the number of integers required
increases, more and more variables need to
be defined.
Solution: ARRAY
ARRAY: Array is the collection of similar data types
or collection of similar entity stored in contiguous
memory location. Array of character is a string. Each
data item of an array is called an element. And each
element is unique and located in separated memory
location. Each of elements of an array share a variable
but each element having different index no. known as
subscript. An array can be a single dimensional or
multi-dimensional and number of subscripts
determines its dimension. And number of subscript is
always starts with zero. One dimensional array is
known as vector and two dimensional arrays are
known as matrix.
ADVANTAGES:
array variable can store more than one value
at a time where other variable can store one
value at a time.
Example:
int arr[100];
int mark[100];
The most important property of an array is that its
elements are stored in contiguous memory
locations
E.g. int num[5];

num[0] num[1] num[2] num[3] num[4]

2 4 6 8 10
2000 2002 2004 2006 2008
DECLARATION OF AN ARRAY :
Its syntax is :
Data type array name [size];
int arr[100];
int mark[100];
int ar[5]={10,20,30,100,5}

The declaration of an array tells the compiler that, the data type, name
of the array, size of the array and for each element it occupies memory
space. Like for int datatype, it occupies 2 bytes for each element and
for float it occupies 4 byte for each element etc.

We can represent individual array (elements) as :


int ar[5];
ar[0], ar[1], ar[2], ar[3], ar[4];
INITIALIZATION OF AN ARRAY:
In an uninitialized array (declared only), the
individual array elements contain garbage values.
Assigning specific values to the individual array
elements, at the time of array declaration, is
known as array initialization.
Since an array has multiple elements, braces are
used to denote the entire array and commas are
used to separate the individual values assigned to
the individual elements in the array.
INITIALIZATION OF AN ARRAY:
Data type array_name [size] = {value1, value2, value3…}
Example:
int ar[5]={20,60,90,100,120}
Array subscript always start from zero which is known as lower
bound and upper
value is known as upper bound and the last subscript value is
one less than the size of array.

Total size in byte for 1D array is:


Total bytes=size of (data type) * size of array.
Example : if an array declared is:
int [20];
Total byte= 2 * 20 =40 byte
ACCESSING OF ARRAY ELEMENT:
/*Write a program to input values into an array and display them*/
#include<stdio.h>
int main()
{
int arr[5],i;
for(i=0;i<5;i++)
{
printf("\nenter the element for arr[%d]",i);
scanf("%d",&arr[i]);
}
printf("the array elements are\n");
for (i=0;i<5;i++)
{
printf("arr[%d]=%d\n",i,arr[i]);
}
return 0;
}
C program to find sum of elements of the array
• What are the differences between Break,
Continue, Return and Exit?
• break - The break statement is used to jump out
of loop. After the break statement control
passes to the immediate statement after the
loop.
• continue - Using continue we can go to the
next iteration in loop.
• return - Exits the function.
• exit - It is used to exit the execution of
program. note: break and continue are
statements, exit is function.
#include<stdio.h> //C program to find sum of elements of the array
int main()
{
int array[10],i,sum=0;
printf("enter the elements of aarya\n");
for(i=0;i<10;i++)
scanf("%d",&array[i]);
printf("\n elements of array are\n");
for(i=0;i<10;i++)
printf("%d\n",array[i]);
for(i=0;i<10;i++)
sum=sum+array[i];
printf("\nsum of array is %d",sum);
}
Write a program to accept your name from
keyboardand display as: Hello! your name.
void main()
{
char name[20];
printf(“Enter your name”);
scanf(“%s”, &name);
printf(“Hello ! %s”, name);
getch();
}
Program to count the no of positive and negative numbers
#include< stdio.h >
void main( )
{
int a[50],n,count_neg=0,count_pos=0,i;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
printf(“Enter the elements of the array\n”);
for(i=0;i < n;i++)
scanf(“%d”,&a[i]);
for(i=0;i < n;i++)
{
if(a[i] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the
array\n”,count_neg);
printf(“There are %d positive numbers in the
array\n”,count_pos);
}
Write a program to find the sum of n numbers using array.
#include<stdio.h>
#include<conio.h>
main ()
{
clrscr();
int a[100],i,n;
printf("How many number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the numbers:\n");
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("The sum=%d",sum);
getch();
}
Write a program to read age of n students and count the number of students of the
age between 15 and 22
main()
{
clrscr();
int a[100],i,n,c=0;
printf("How many number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the age:\n");
scanf("%d",&age[i]);
if(age[i]>15 && age[i]<22)
{
c=c+1;
}
}
printf("The number of students =%d",c);
getch();
}
#include<stdio.h>
main()
{
int i=0;
float avg=0,sum=0;
int arry[10]={1,2,3,4,5,6,7,8,9,10};// 1 2 3 4 5 6 7 8 9 10

while(i<10)
{
sum=sum+arry[i];
i++;
}
avg=sum/10;
printf("\nthe sum of elements of array is %f",sum);
printf("\n the average of the sum of elements of the array is %f:",avg);
}
main () // C program to find sum and average of n elements of the array
{
int a[100],i,n,sum=0;
float ave;
printf("How many number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the numbers:\n");
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
printf("The sum=%d",sum);
ave=sum/n;
printf("The average=%f",ave);
getch();
}
Void main() //Write a program to input n numbers and find the smallest number
{
int a[100],i,n,smallest;
printf("How many number:");
scanf("%d",&n);
printf("Enter the number:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
smallest=a[0];
for(i=0;i<n;i++)
{
if(smallest>a[i])
{
smallest=a[i];
}
}
printf("Smallest number=%d",smallest);
getch();}
SORTING
Sorting is the process of arranging items in
some sequence (ascending or descending) by
value or by alphabet or by any other weight.
Various sorting techniques exist but they are
beyond the scope of this course (Included in
Data Structures and Algorithms).
We will be using a simple sorting technique in
the coming slide to sort numbers in ascending
order.
void main()
{
int num[100], i, j, n, temp;
printf("\nHow many numbers you want to sort?:\t");
scanf("%d", &n);
for(i=0;i<n;i++)
scanf("%d", &num[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
printf("\nThe numbers in ascending order are:\n");
for(i=0;i<n;i++)
printf("\t%d", nums[i]);
getch();
}
Assignment:
• Write a program to input n numbers and find the greatest number
• Write a program to read salary of n employees and count the
number of employees whose salary is in between 10000 and 15000
• Write a program to read marks obtained by n students in a subject
and count the number of students whose mark is in between 60 and
80

Points to Remember
• An array is a collection of similar elements.
• The first element in the array is numbered 0, so the last element is 1
less than the size of the array.
• An array is also known as subscripted variable.
• Before using an array its type and dimension must be declared.
• Stored in contiguous memory.
MULTIDIMENSIONAL ARRAYS
Multidimensional arrays are those having
more than one dimension.
Multidimensional arrays are defined in the
same way as one dimensional arrays, except
that a separate pair of square brackets is
required for each subscript or dimension or
index.
Thus a 2-D (two dimensional) array requires
two pairs of square brackets, a 3-D array
requires three pairs of square brackets and
so on.
• Syntax for defining multidimensional array is:
data_type array_name[dim1][dim2]…[dimN];
• Here, dim1, dim2,…,dimN are positive valued
integer expressions that indicate the number of
array elements associated with each subscript.
Thus, total no. of elements=dim1*dim2*…*dimN
E.g.
• int survey[3][5][12];
• Here, survey is a 3-D array that can contain
3*5*12=180 integer type data. This array survey
may represent a survey data of rainfall during last
three years (2009,2010,2011) from months Jan. to
Dec. in five cities. Its individual elements are from
survey[0][0][0] to survey[2][4][11].
• MULTIDIMENSIONAL ARRAYS…
• E.g.
• int matrix[2][3];
• Here, matrix is a 2-D array that can contain
2*3=6 elements. This array matrix can
represent a table having 2 rows and 3
columns from matrix[0][0] to matrix[1][2].
Column1 Column2 Column3

Row1 matrix[0][0] matrix[0][1] matrix[0][2]

Row2 matrix[1][0] matrix[1][1] matrix[1][2]


2-D ARRAYS
• The two dimensional array is also called
matrix.
• An m*n two dimensional array can be
thought as tables of values having m rows
and n columns.
• Like 1-D arrays, 2-D arrays must also be
declared before using it. The syntax is:
• data_type array_name[row_size][col_size];
• E.g.
float matrix[3][4]; //contains 12 elements
char students[10][15];
• The array having two dimensions is called two
dimensional arrays. Such array contains element in row
– column wise. Two dimensional arrays are also called a
matrix.
• Example
int num[4][2] refers to the array in tabular form with 4
rows and two columns

Row number 0 num[0][0] → first num[0][1] → first


row first column row second column
Row number 1 num[1][0] num[1][1]
Row number 2 num[2][0] num[2][1]
Row number 3 num[3][0] num[3][1]
Row number 0 num[0][0] → first row num[0][1] → first row
first column second column
Row number 1 num[1][0] num[1][1]
Row number 2 num[2][0] num[2][1]
Row number 3 num[3][0] num[3][1]

This tabular form of a 2 –D array is just a conceptual


design. But in memory, it doesn’t store as tabular form,
but in contiguous format.
num[0][0] num[0][1] num[1][0] num[1][1] num[2][0] num[2][1] num[3][0] Num[3][1]

12 13 144 36 33 536 36 56
65508 65510 65512 65514 65516 65518 65520 65522
Sample code
void main()
{
int num[4][2];
int i. j;
//use nested loop
for(i=0; i<4; i++) // first outer loop refers to the row
{
for(j=0; j<2; j++) // second inner loop refers to the column
{
printf(“\nEnter a number:”);
scanf(“%d”,&num[i][j]); //similarly we can print
the element also
}
}
}
Initializing a Two Dimensional Array
int num[4][2] ={
{1,2},
{3,4},
{5,6},
{7,8}
};
OR
int num[4][2] = {1,2,3,4,5,6,7,8};
Arr[4][4]

arr[0][0] arr[0][1] arr[0][2] arr[0][3]

arr[1][0] arr[1][1] arr[1][2] arr[1][3]

arr[2][0] arr[2][1] arr[2][2] arr[2][3]

arr[3][0] arr[3][1] arr[3][2] arr[3][3]


2D array Matrix representation

Row/column

0 1 2 3
2 4 6 8
0
10 20 30 40
1
5 10 15 20
2
3 6 9 12
3
#include<stdio.h> //program to Initialize a Two Dimensional Array
int main()
{
int arr[4][4]={
{2,4,6,8},
{10,20,30,40},
{5,10,15,20},
{3,6,9,12}
};
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("arr[%d][%d]:%d\n",i,j,arr[i][j]);
}
}
}
#include<stdio.h> //program to Initialize a Two Dimensional Array
int main()
{
int arr[4][4]={
{2,4,6,8},
{10,20,30,40},
{5,10,15,20},
{3,6,9,12}
};
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("\t%d",arr[i][j]);
}
printf("\n");
}
}
int main() /*a program to input values into a 2D array and display them*/
{
int array[2][3],i,j;
printf("enter the elements of 2d array\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&array[i][j]);
}
}
printf("the elements of 2d array are:\n") ;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\t%d",array[i][j]);
}
printf("\n");
}
}
Mat[0][1] Mat[0][2]
1 2 3
Mat[0][0]

Mat[1][0] Mat[1][1] Mat[1][2]


4 5 6
Mat[2][0] Mat[2][1] Mat[2][2]
7 8 9
Where
Row=column

sum of diagonal elements=15


Void main() // program to calculate the sum of diagonal elements from left to right.
{
int mat[3][3], i,j,sum=0;
printf("enter the elements of array");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&mat[i][j]);
}
}
printf("sum of diagonal elements is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
{
sum=sum+mat[i][j];
}
}
}
printf("%d",sum); }
1 2 3 Mat[0][0] Mat[0][1] Mat[0][2]

4 5 6 Mat[1][0] Mat[1][1] Mat[1][2]

7 8 9 Mat[2][0] Mat[2][1] Mat[2][2]

Transpose

1 4 7 Mat[0][0] Mat[1][0] Mat[2][0]

2 5 8 Mat[0][1] Mat[1][1] Mat[2][1]

3 6 9 Mat[0][2] Mat[1][2] Mat[2][2]

Trans[3][3]
Mat[0][0] Mat[0][1] Mat[0][2] Mat[0][0] Mat[1][0] Mat[2][0]

Mat[1][0] Mat[1][1] Mat[1][2] Mat[0][1] Mat[1][1] Mat[2][1]

Mat[2][0] Mat[2][1] Mat[2][2] Mat[0][2] Mat[1][2] Mat[2][2]

Mat[3][3] Trans[3][3]

Mat[0][0] Mat[1][0] Mat[2][0]


Trans[0][0] Trans[0][1] Trans[0][2]

Mat[0][1] Mat[1][1] Mat[2][1]


Trans[1][0] Trans[1][1] Trans[1][2]

Trans[2][0] Trans[2][1] Trans[2][2] Mat[0][2] Mat[1][2] Mat[2][2]


Write a program to accept the elements of 3x3 matrix and print the original and
its transpose matrix.
#include<stdio.h>
#include<conio.h>
int main()
{
int matrix[3][3],trans[3][3],i, j;
printf("enter the elements of matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&matrix[i][j]);
}
}
printf("the original matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",matrix[i][j]);
}
printf("\n");
}
1 2 3
for(i=0;i<3;i++)
4 5 6
{ 7 8 9
for(j=0;j<3;j++)
//matrix[3][3]
{
trans[i][j]=matrix[j][i];
}
}
trans[0][0] trans[0][1] trans[0][2] matrix[0][0] matrix[1][0] matrix[2][0]
=1 =4 =7
printf("the transpose of the matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",trans[i][j]);
}
printf("\n");
}

getch();
}
Matrix addition

c[0][0] c[0][1] c[0][2] a[0][0] a[0][1] a[0][2] b[0][0] b[0][1] b[0][2]

c[1][0] c[1][1] c[1][2] a[1][0] a[1][1] a[1][2] b[1][0] b[1][1] b[1][2]

c[2][0] c[2][1] c[2][2] a[2][0] a[2][1] a[2][2] b[2][0] b[2][1] b[2][2]

2 3 4 1 2 3 1 1 1
6 7 8 4 5 6 2 2 2
10 11 12 7 8 9 3 3 3

a[3][3]
C[3][3] b[3][3]
#include<stdio.h> //Write a program to add elements of two 3X3 matrix
#include<conio.h>
main ()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the elements of first matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of second matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("The sum of two matrix is as follows:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
WRITE A PROGRAM TO FIND THE SUM OF SQUARES IN A DIAGONAL
OF A SQUARE MATRIX
Matrix Multiplication
M N N P

M N N P M P

A[M][N]*B[N][P]=C[M][P]
First[2][3] Second[3][2]

1 4
1 2 3
2 5
4 5 6
3 6

1*1+2*2+3*3 1*4+2*5+3*6

Mult[2][2]
4*1+5*2+6*3 4*4+5*5+6*6

14 32

32 77
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int r1,c1,r2,c2,i,j,k,sum=0;
int first[10][10],second[10][10],mult[10][10];
printf("enter the row and column of first matrix\n");
scanf("%d%d",&r1,&c1);
printf("enter the elements of first matrix\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&first[i][j]);
}
}
printf("enter the row and column of second
matrix\n");
scanf("%d%d",&r2,&c2);
printf("enter the elements of second matrix\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&second[i][j]);
}
}
if(c1!=r2)
{
printf("matrix multiplication is not possible\n");
getch();
exit(0);
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
for(k=0;k<c1;k++) //c1=r2
{

sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
sum=0;
}
}
printf("the matrix after the multiplication is:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",mult[i][j]);
}
printf("\n");
}

}
1 2 3 1 4
4 5 6 2 5 for(i=0;i<r1;i++)
First[2][3] 3 6 {
second[3][2]
for(j=0;j<c2;j++)
i=0,j=0,k=0 {
sum=sum+first[i][k]*second[k][j]; for(k=0;k<c1;k++) //c1=r2=3
Sum=sum+first[0][0]*second[0][0] {
Sum=0+1*1=1 sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
i=0,j=0,k=1 sum=0;
sum=sum+first[i][k]*second[k][j]; }
Sum=sum+first[0][1]*second[1[0] }
Sum=1+2*2=5

i=0,j=0,k=2
sum=sum+first[i][k]*second[k][j];
Sum=sum+first[0][2]*second[2][0]
Sum=5+3*9=14

14 Mult[i][j] // i=0,j=0

Mult[0][0]=sum=14
1 2 3 1 4
4 5 6 2 5 for(i=0;i<r1;i++)
First[2][3] 3 6 {
second[3][2]
for(j=0;j<c2;j++)
i=0,j=1,k=0 {
sum=sum+first[i][k]*second[k][j]; for(k=0;k<c1;k++) //c1=r2=3
Sum=sum+first[0][0]*second[0][1] {
Sum=0+1*4=4 sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
i=0,j=1,k=1 sum=0;
sum=sum+first[i][k]*second[k][j]; }
Sum=sum+first[0][1]*second[1[1] }
Sum=4+2*5=14

i=0,j=1,k=2
sum=sum+first[i][k]*second[k][j];
Sum=sum+first[0][2]*second[2][1]
Sum=14+3*6=32

14 32
1 2 3 1 4
4 5 6 2 5 for(i=0;i<r1;i++)
First[2][3] 3 6 {
second[3][2]
for(j=0;j<c2;j++)
i=1,j=0,k=0 {
sum=sum+first[i][k]*second[k][j]; for(k=0;k<c1;k++) //c1=r2=3
Sum=sum+first[1][0]*second[0][0] {
Sum=0+4*1=4 sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
i=1,j=0,k=1 sum=0;
sum=sum+first[i][k]*second[k][j]; }
Sum=sum+first[1][1]*second[1[0] }
Sum=4+5*2=14

i=1,j=0,k=2
sum=sum+first[i][k]*second[k][j];
Sum=sum+first[1][2]*second[2][0]
Sum=14+6*3=32

14 32

32
1 2 3 1 4
4 5 6 2 5 for(i=0;i<r1;i++)
First[2][3] 3 6 {
second[3][2]
for(j=0;j<c2;j++)
i=1,j=1,k=0 {
sum=sum+first[i][k]*second[k][j]; for(k=0;k<c1;k++) //c1=r2=3
Sum=sum+first[1][0]*second[0][1] {
Sum=0+4*4=16 sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
i=1,j=1,k=1 sum=0;
sum=sum+first[i][k]*second[k][j]; }
Sum=sum+first[1][1]*second[1[1] }
Sum=16+5*5=41

i=1,j=1,k=2
sum=sum+first[i][k]*second[k][j];
Sum=sum+first[1][2]*second[2][1]
Sum=41+6*6=77

14 32

32 77
Mat[0][1] Mat[0][2]
1 2 3
Mat[0][0]

Mat[1][0] Mat[1][1] Mat[1][2]


0 5 6
Mat[2][0] Mat[2][1] Mat[2][2]
0 0 9
Where
Row<=column

sum of element of upper triangle =26


int main() // c program to calculate the sum of element of upper triangle of 3X3 matrix
{
int mat[3][3], i,j,sum=0;
printf("enter the elements of array\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&mat[i][j]);
}
}
printf("sum of element of upper triangle is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i<=j)
{
sum=sum+mat[i][j];
}
}
}
printf("%d",sum); }
ARRAYS AND STRINGS
• Strings are array of characters i.e. they are
characters arranged one after another in
memory. Thus, a character array is called
string.
• Each character within the string is stored
within one element of the array successively.
• A string is always terminated by a null
character (i.e. slash zero \0).
• Operations performed on character strings
include:
–—
Reading and writing strings
–—
Copying one string to another
–—
Combining strings together
–—
Comparing strings for equality
–—
Extracting a portion of a string
• DECLARING STRING VARIABLES
• A string variable is declared as an array of
characters.
• Syntax:
char string_name[size];
• The size determines the number of characters in
the string_name.
E.g. char name[20];
char city[15];
• When the compiler assigns a character string to a
character array, it automatically supplies a null
character (‘\0’) at the end of the string. Thus, the
size should be equal to the maximum number of
characters in the string plus one.
INITIALIZING STRING VARIABLES
Strings are initialized in either of the following two
forms:
char name[4]={‘R’,‘A’,‘M’, ‘\0’};
char name[]={‘R’,‘A’,‘M’, ‘\0’};
char city[9]={‘N’,‘E’,‘W’, ‘ ’,‘Y’,‘O’,‘R’,‘K’,‘\0’};
OR
char name[4]=“RAM”;
char name[]=“RAM”;
char city[9]=“NEW YORK”;

When we initialize a character array by listing its


elements, the null terminator or the size of the
array must be provided explicitly.
STRING INITIALIZATION EXAMPLE

#include <stdio.h>
#include <conio.h>
void main()
{
char city[9]={'N','E','W',' ','Y','O','R','K','\0'};
int i=0;
while(city[i]!='\0')
{
printf("%c\t ",city[i]);
i++;
}
getch();
}
READING STRING FROM TERMINAL
• The input function scanf can be used with %s
format specification to read in a string of
characters.
• E.g.
char name[20];
scanf(“%s”, name);
• No ampersand(&) is required before variable
name.
• Problem:
“scanf() terminates its input on the first white
space it encounters”
#include <stdio.h>
#include <conio.h>
void main()
{
char name[20];
printf("\n Enter your name:");
scanf("%s", name);
printf("\n Your name is %s", name);
getch();
}
READING STRING FROM TERMINAL…
• Some versions of scanf() support the following
conversion specification for strings:
%[characters]
%[^characters]
• The specification %[characters] means that only
the characters specified within the brackets are
allowed in the input of string. If the input string
contains any other characters, the reading of
string will be terminated at the first encounter of
such a character.
• The specification %[^characters] means that the
characters specified after the caret(^) are not
allowed in the string and reading will be
terminated.
#include <stdio.h>
#include <conio.h>
void main()
{
char name[20];
printf("\nEnter your name (in uppercase):");
scanf("%[A-Z]",name);
printf("\nYour name is %s",name);
getch();
}
THIS PROGRAM CAN READ STRINGS WITH
BLANK SPACES
#include <stdio.h>
#include <conio.h>
void main()
{
char name[30];
printf("\n Enter your full name:");
scanf("%[^\n]", name);
printf("\n Your name is %s", name);
getch();
}
WRITING STRING TO SCREEN
• The printf() function with %s format is used to
print strings to the screen.
• The format %s can be used to display an array
of characters that is terminated by the null
character.
• E.g.
char name[19]=“Ram Prasad Adhikari”;
printf(“%s”, name);
gets() and puts ()
• The gets() function is used to read a string of
text, containing whitespaces, until a newline
character is encountered.
Syntax: gets(variable_name);
• It takes a string from user and stores in a string
variable variable_name.
• The puts() function is used to display the string
onto the screen.
Syntax: puts(variable_name);
COUNTING THE LENGTH OF THE STRING
#include <stdio.h>
#include <conio.h>
void main()
{
char input_string[50];
int i=0, length=0;
printf("\nEnter your text:\t");
gets(input_string);
while(input_string[i]!='\0') R A M \0
{
length++;
i++;
}
printf("\nThe length of your text is: %d character(s)", length);
getch();
}
strlen()
The function strlen() returns an integer which
denotes the length of the string passed into the
function.
• The length of the string is defined as the number
of characters present in the string, excluding the
null character.
• Syntax:
integer_variable=strlen(input_string);
• Use header file <string.h>.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int length=0;
char string1[20];
printf("enter the string\n");
gets(string1);
length=strlen(string1);
printf("\nthe length of string is %d",length);
getch();
return 0;
}
PROGRAM TO READ YOUR NAME FROM KEYBOARD AND OUTPUT A LIST OFASCII
CODES THAT REPRESENT YOUR NAME

void main()
{
char name[30];
int length, i;
printf("Enter your name:\t");
gets(name);
length=strlen(name);
printf("\nThe ASCIIvalues of characters in the name %s are:\n",name);
for(i=0;i<length;i++)
printf("%c = %d\n", name[i], name[i]); R A M \0
getch(); Name[0] Name[1] Name[2]
}
PROGRAM TO READ A STRING FROM KEYBOARD(UNTIL ENTER KEY) AND
COUNT THE NUMBERS OF VOWELS, CONSONANTS, SPACES, SEMICOLONS AND
COMMAS IN THAT STRING
#include <string.h>
void main()
{
char s[80];
int len, i, space=0, vowel=0, consonant=0, semicolon=0, comma=0;
printf("Enter string:\t");
gets(s);
len=strlen(s);
for(i=0;i<len;i++)
{
if(s[i]=='a'||s[i]=='e'||s[i]== 'i'||s[i]=='o'||s[i]=='u')
vowel++;
else if(s[i]==';')
semicolon++;
else if(s[i]==',')
comma++;
else if(s[i]==' ')
space++;
else
consonant++;
}
printf("\nThe number of vowel(s):%d", vowel);
printf("\nThe number of semicolon(s):%d", semicolon);
printf("\nThe number of comma(s):%d", comma);
printf("\nThe number of space(s):%d", space);
printf("\nThe number of consonant(s):%d", consonant);
getch();
}
COPYING ONE STRING TO ANOTHER
#include <stdio.h>
#include <conio.h>
void main()
{
char copy[50], paste[50];
int i;
printf("\n Enter your name (to copy):\t");
gets(copy); R A M \0
for(i=0;copy[i]!='\0';i++) copy[4]
{
paste[i]=copy[i];
paste[4]
}
paste[i]='\0';
printf("\n The name is (pasted as):\t");
puts(paste);
getch();
}
Another Way: strcpy()
• The strcpy() function copies one string to
another.
• It accepts two strings as parameters and
copies the second string character by
character into the first string including the
null character of the second string.
• The source string may be a string constant
like “Ramesh Kumar”.
• Syntax:
strcpy(destination_string, source_string);
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char copy[50], paste[50];
int i;
printf("\nEnter your name (to copy):\t");
gets(copy);
strcpy(paste, copy);
printf("\nThe name is (pasted as):\t");
puts(paste);
getch();
}
COMBINING STRINGS
• Also called String Concatenation.
• Just as we cannot assign one string to another
directly, we cannot join two strings together by
the simple arithmetic addition. So, the statements
such as
string3=string1+string2;
string1=string2+“hey”;
are completely invalid.
• Here, the characters from string1 and string2
should be copied into string3 one after another.
Also the size of string3 should be large enough to
hold the total characters.
#include <stdio.h> //COMBINING STRINGS
#include <conio.h>
void main()
{ First_name[7]
int i, j;
R A M E S H \0
char first_name[7]=“Ramesh" ;
char last_name[9]=“Adhikari"; A D H I K A R I \0
char name[16]; Last_name[9]
for(i=0;first_name[i]!='\0';i++)
R A M E S H A D H I K A R I \0
name[i]=first_name[i];
name[i]=' '; //name[6] i.e i=6 name[16]
for(j=0;last_name[j]!='\0';j++)
name[i+j+1]=last_name[j];
name[i+j+1]='\0';
printf("%s", name);
getch(); }
Another Way: strcat()
• The strcat() function concatenates
two strings i.e. it appends one string
at the end of another.
• It accepts two strings as parameters
and stores the contents of the second
string at the end of the first string.
• Syntax:
strcat(first_string, second_string);
#include <string.h>
void main()
{
char first_name[30]= “Ramesh" ;
char last_name[]= "Adhikari";
strcat(first_name, last_name);
puts(first_name);
getch();
}
COMPARISON OF TWO STRINGS
• C does not permit the comparison of two
strings directly; i.e. statements such as
if(name1==name2)
(name==“abc”)
are not permitted.
• The comparison of two strings has to be done
character by character.
• The comparison is done until there is a
mismatch or one of the strings terminates into
a null character, whichever occurs first.
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[30], str2[40];
int i=0;
printf("Enter first string:\t");
gets(str1);
printf("\n Enter second string:\t");
gets(str2);
while(str1[i]==str2[i] && str1[i]!='\0' &&str2[i]!='\0') R A M \0

i++;
R A M \0
if(str1[i]=='\0' && str2[i]=='\0')
printf("\n Strings are equal.");
else
printf("\n Strings are unequal");
getch();
}
Another Way: strcmp()
• The strcmp() function compares two strings
to find out whether they are same or
different.
• It accepts two strings as parameters and
returns an integer 0 if the strings are equal.
• If the two strings are unequal, then it
returns an integer that has the numeric
difference (ASCII value difference) between
the first non-matching characters in the
strings.
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[30],str2[40];
int i=0,value;
printf("Enter first string:\t");
gets(str1);
printf("\n Enter second string:\t");
gets(str2);
value=strcmp(str1,str2);
if(strcmp(str1,str2)==0)
printf("\n Strings are equal.");
else
printf("\n Strings are unequal");
getch();
}
Reversing a String

#include <stdio.h>
#include <conio.h>
void main()
{
char string[25], reverse_string[25]; R A M \0
int length, i, j;
printf("\nInput string to be reversed:");
gets(string); M A R \0
length=strlen(string);
for(j=0,i=length-1;j<length;j++,i--)
reverse_string[j]=string[i]; //Reverse_sring[0]=string[2]
reverse_string[j]='\0';
//Reverse_sring[1]=string[1]
puts(reverse_string);
getch(); //Reverse_sring[2]=string[0]
}
Another Way: strrev()
• The function strrev() is used to reverse all
characters in a string except the null
character at the end of string.
• E.g. The reverse of string “CSIT” is “TISC”.
• Syntax:
• strrev(string);
• Here, the characters in the string “string” are
reversed and the reversed string is stored in
“string”.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[25];
printf("\n Input string to be reversed:");
gets(string);
strrev(string);
printf("\n The reversed string is: %s", string);
getch(); }
/*Program to read a string and check for palindrome*/
#include <stdio.h>
#include <conio.h>
void main()
{
char string[50];
int len, i, p=1;
printf("Enter string:\t");
gets(string);
len=strlen(string);
for(i=0;i<(len/2);i++)
{
if(string[i]!=string[len-i-1])
{
p=0;
}
} R A H A R \0

if(p==0)
printf("\nThe input string is not palindrome.");
else //String[0]=string[5-0-1]
printf("\nThe input string is palindrome."); //String[1]=string[5-1-1]
getch();
} //String[2]=string[5-2-1]

You might also like