[go: up one dir, main page]

0% found this document useful (0 votes)
2 views63 pages

Chapter 6.1 Array and String

Chapter 6 covers arrays in C programming, detailing their types, declaration, initialization, and memory representation. It explains one-dimensional, two-dimensional, and multidimensional arrays, along with string handling and pointer relationships. The chapter includes examples and code snippets for practical understanding of array operations and string manipulation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views63 pages

Chapter 6.1 Array and String

Chapter 6 covers arrays in C programming, detailing their types, declaration, initialization, and memory representation. It explains one-dimensional, two-dimensional, and multidimensional arrays, along with string handling and pointer relationships. The chapter includes examples and code snippets for practical understanding of array operations and string manipulation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Chapter 6

Arrays
Array (11 Marks)
6.1 Introduction to an Array
6.2 One-dimensional Array
6.3 Two-dimensional Array
6.4 Multidimensional Array
6.5 Introduction to String
6.6 String and String Handling Functions
6.7 Array of String
6.7 Definition and Declaration of a Pointer
6.8 Types of Pointer
6.9 Pointer Arithmetic
6.10 Relationship between Pointer and Arrays
Background
• If we deal with similar type of variables in more number at a time, we
may have to write lengthy programs along with long list of variables.
• There should be more number of assignment statements in order to
manipulate on variables.
• When the number of variables increases, the length of program also
increase.
• In the above situations described above, where more number of same
types of variables is used, the concept of ARRAYS is employed in C
language.
• These are very much helpful to store as well as retrieve the data of
similar type of data.
•Why arrays is necessary?
•If we have to store information of 100 students.
•Without array:
int a1,a2,a3,a4,a5, … ,a100;
•With array:
int a[100];
a[0],a[1],…a[99]
Index 0-99
Array
• An array is the collective name given to a group of similar quantities.
• An array is a set of similar data elements which are stored in consecutive
memory locations under a common variable name.
• The individual values in an array are called elements.
• Array is sets of values of the same type, which have single name followed
by an index.
• The similar element of an array would be all integers or all floats or all
characters. Usually, the array of character is called string.
• The elements of an array are of same data type and each item can be
accessed using the same name.
Array Declaration
• Declaring the name and type of an array and setting the number of
elements in the array is known as dimensioning(declaring) the array.
• It must be declared before it is used like other variables.
• In the array declaration, we must define the type of the array, name of
the array and number of subscripts in the array. In general, one-
dimensional array may be expressed as:
Syntax: data_type array_name[size]; Similarly,
Declaring Arrays
Array variables are declared identically to variables of their data type,
except that the variable name is followed by one pair of square [ ]
brackets for each dimension of the array.

data_type array_name[array_size];

For example: if you want to store marks of 100 students, you can create an
array for it.

float marks[100];
The size and type of arrays cannot be changed after its declaration
Initialization of Array
• Arrays may be initialized when they are declared, just as any other variables.
• Place the initialization data in curly { } braces following the equals sign.
• An array may be partially initialized by providing fewer data items than the size of the
array. The remaining array elements will be automatically initialized to null values.
Initializing Arrays

Arrays may be initialized when they are declared,
just as any other variables.

Place the initialization data in curly { } braces following the

equals sign. An array may be partially initialized, by providing
fewer data items than the size of the array. The remaining
array elements will be automatically initialized to zero.

If an array is to be completely initialized, the dimension of the
array is not required.
int Arrayname[ 6 ] = { 1, 2, 3, 4, 5, 6 };
float Arrayname[ 100 ] = { 1.0f, 5.0f, 20.0f };
double piFractions[ ] = { 3.141592654, 1.570796327, 0.785398163 };
Compile Time Initialization
Syntax:
Data_Type array_name[]={list of arguments};
Example: int arrayname[ 6 ] = { 1, 2, 3, 4, 5, 6 };
Global and local initialization
Just like local and global variable initialization
Runtime Initialization
Data_type arrayname[];
arrayname[index]=value;
Array Memory Diagrams
Suppose the following array declaration and code to
initialize it.
int a[5]; // Allocates memory for 5 ints.
...
a[0] = 1;
for (int i=1; i<5; i++) {
a[i] = a[i-1] * 2;
}

Arrays are often represented with


diagrams that represent their memory
use.
The actual array variable, a in this
example, is a
pointer to the memory for all of its
elements.
Dimension of Array
• The dimension denotes the size of array that is classified as one or two or more dimension
according to the number of subscript using on it.
• One dimensional array:- Array whose dimension is classified by one subscript are called single
dimension array. Data are stored in either row or column form.
For example: int array[5];
• Two dimensional array:- Array whose elements are specified by two subscripts are called 2D
array. The two dimensional array is called Matrix in which first array declare the number of rows
and second array declare the number of columns in the matrix. Data are stored in either rows
and columns form
For example: int array[6][3];
2-D Array
1-D Array
One Dimension Array
• The array is initialized by assigning values to the array element. The value is
enclosed in braces and separated by commas.
• The values must appear in the same order in which they will be assigned to
the individual array elements. The array starts from 0 to n-1, where n is the
maximum size of the array declared. The general format of the array
initialization is:
data_type array_name[size]={element1, element2,………elementN};
• For example: int values[3]={10,11,12};
or int values[]={10,11,13}; //full of array
where, values[0]=10
values[1]=11
values[2]=12
Input and Accessing array elements
• In C programming, arrays can be accessed and treated like variables in C.
• For example: scanf("%d",&age[0]);
//statement to insert value in the first element of array age[]
• For example: scanf("%d",&age[2]);
//statement to insert value in the third element of array age[]
• For Example: printf("%d",age[0]);
//statement to print first element of an array.
• For Example: printf("%d",age[2]);
//statement to print third element of an array.
• Arrays can be accessed and updated using its index.
• An array of n elements, has indices ranging from 0 to n-1.
Example 1: Write a program to read 10 numbers in an 1-D array and display it
Example 2: Write a program to create reverse list of 10 elements in an array
Example 3: WAP to find the average of n number input by user using the concept of array.
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, avg;
printf("Enter the numbers of elements: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf(" Enter the elements of array: ");
scanf("%f", &num[i]);
sum += num[i];
}
avg = sum / n;
printf("Average = %.2f", avg);
return 0;
}
Example 4: Write a program to read n numbers in an array and find the largest and smallest number.
Example 5: Write a program to read 5 integer numbers in an array and sort it in ascending order.
Example 6: WAP to accept n number and arrange them in ascending order.
#include <stdio.h> if (number[i] > number[j])
main() {
{ a = number[i];
number[i] = number[j];
int i, j, a, n, number[30]; number[j] = a;
printf("Enter the value of N\n");
scanf("%d", &n); }
printf("Enter the numbers \n"); }
for (i = 0; i < n; ++i)
scanf("%d", &number[i]); }
for (i = 0; i < n; ++i)
{ printf("The numbers in ascending
order are \n");
for (i = 0; i < n; ++i)
for (j = i + 1; j < n; ++j) printf("%d\n", number[i]);
{
}
Example 7: WAP to calculate mean and standard deviation
}
/* Calculate mean and standard /* calculate mean */
deviation */ sum= 0.0;
#include <stdio.h> for(i = 0; i < n; i++)
#include <math.h> {
main() sum+= x[i];
{ mean = sum / n;
float x [50]; }
int n; /* calculate standard deviation */
float sum, mean, sd; sum= 0.0;
int i; for(i = 0; i < n; i++) {
printf("How many numbers (max sum+= (x[i] - mean) * (x[i] - mean);
50)? "); sd = sqrt(sum / n); }
scanf("%d", &n); printf("Mean = %6.3f\n", mean);
printf ("Enter numbers: "); printf("Standard Deviation: %6.3f\n",
for(i = 0; i<n; i++) sd);
{ return 0;
Multidimensional Array
• Multidimensional arrays are defined in the same manner as one-
dimensional arrays, except that a separate pair of square brackets is
required for each subscript.
• Thus, a two-dimensional array requires two pairs of square brackets; a
three-dimensional array will require three pairs of square brackets
and so on. Two-dimensional array can be expressed as:
data_type array_name [rowsize][columnsize];
Example1: Write a program to read a 3x3 matrix and display it on the screen.
Example2 : Write a program to read a 3x3 matrix and add it.
Example 3: WAP to add two matrix of order r*C and display it.
#include<stdio.h> scanf("%d",&m2[i][j]);
#include<conio.h> }
int main() }
{ for(i=0;i<r;i++)
int m1[20][20],m2[20][20],m3[20][20]={0},i,j,r,c; {
printf("enter the row and column of matrix\n"); for(j=0;j<c;j++)
scanf("%d%d",&r,&c); {
printf("enter the first matrix of order %d*%d rowwise\
m3[i][j]=m1[i][j]+m2[i][j];
n",r,c); }
for(i=0;i<r;i++) }
{ printf("the summation matrix is \n");
for(j=0;j<c;j++) for(i=0;i<r;i++)
{ {
scanf("%d",&m1[i][j]); for(j=0;j<c;j++)
} {
} printf("%d\t",m3[i][j]);
printf("enter the second matrix of order %d*%d }
rowwise\n",r,c); printf("\n");
for(i=0;i<r;i++) }
{ getch();
for(j=0;j<c;j++) return 0;
{ }
Example 4: WAP to find the transpose of matrix of order r*c and display the transposed
matrix printf("%d\t",m[i][j]);
}
#include<stdio.h>
printf("\n");
#include<conio.h>
}
int main()
for(i=0;i<c;i++)
{
{
int m[20][20],t[20][20],r,c,i,j;
for(j=0;j<r;j++)
printf("enter the row and column of matrix\n");
{
scanf("%d%d",&r,&c);
t[i][j]=m[j][i];
printf("enter the matrix of order %d*%d\n",r,c);
}
for(i=0;i<r;i++)
}
{
printf("the transpose matrix is \n");
for(j=0;j<c;j++)
for(i=0;i<c;i++)
{
{
scanf("%d",&m[i][j]);
for(j=0;j<r;j++)
}
}
{
printf("the original matrix of order %d*%d is\n",r,c);
printf("%d\t",t[i][j]);
for(i=0;i<r;i++)
}
{
printf("\n");
for(j=0;j<c;j++)
}
{
}
Example 5: : WAP to multiply two 3x3 matrices and display it.
#include<stdio.h> scanf("%d",&m1[i][j]);
#include<conio.h> }
int main() }
{ printf("enter the element of second matrix\n");
int m1[20][20],m2[20][20],m3[20] for(i=0;i<r2;i++)
[20]={0},i,j,k,r1,c1,r2,c2; {
printf("enter the row and column of first and for(j=0;j<c2;j++)
second matrix\n"); { printf("the resultant matrix is\n");
scanf("%d%d%d%d",&r1,&c1,&r2,&c2); scanf("%d",&m2[i][j]); for(i=0;i<r1;i++)
if(c1!=r2) } {
{ } for(j=0;j<c2;j++)
printf("the matrix multiplication is not {
//to multiply
possible\n"); printf("%d\t",m3[i][j]);
for(i=0;i<r1;i++)
} }
{
else printf("\n");
for(j=0;j<c2;j++)
{ }
{
printf("enter the element of first matrix\n"); }
for(k=0;k<c1;k++)
for(i=0;i<r1;i++) getch();
{
{ }
m3[i][j]=m3[i][j]+m1[i][k]*m2[k][j];
for(j=0;j<c1;j++)
}
{
}
}
Example 6: Write a program to find the norm of a matrix. (Norm of a matrix is the square
root of sum of square of individual elements.)
Example 7: WAP to find sum of even elements of 3*3 matrix.
Example 8:WAP to find the average of all the elements of m*n matrix
Example 9 :WAP to find the sum of diagonal elements from the left (the trace of a matrix)
String

• Strings are sequence of characters used in programming language for storing and
manipulating texts such as words, sentence, names etc.
• In C, there is no built-in data type for strings.
• String can be represented as a one-dimensional array of characters.
• A character string is stored in an array of character type.
• String should always have a NULL character (‘\0’) at the end, to represent the end of
string.
• The elements of the string are stored in continuous memory locations.
• When we initialize the string, the compiler automatically puts a null
character (‘\0’) at the end of last character of the array.
• The '\0' represents the end of the string. We can declare it as one or multi-
dimensional array. Recall : getchar(),putchar(),puts() and gets() function

The getchar() function is used to read a single character


from the keyboard and putchar() is used to display the
single character on the screen. The execution of scanf() and
printf() functions terminates if it found the whitespaces like
new line, tab, enter, space etc. So, gets() and puts() are
used in place of scanf() and printf() function respectively.
The gets() reads a string from the keyboard and puts
display the string on the screen. For using these functions,
the header file is used.
String Functions

• There are various built in functions related to the string. They are available
in string.h header file. Some of them are:
Declare, Initialize Array of Char Type
•A string variable is any valid C variable name and is always declared as an array.
The syntax of declaration of a string variable is:
• Data_type string-name[size];
The size determines the number of character in the string name
Example:
•An array of char type to store the string “Program” is to be declared
as follows:
char str[8];

An array of char is also called as a string variable, since it can store a string
and it permits us to change its contents. In contrast, a sequence of characters
enclosed within a pair of double quotes is called a string constant
Initialization of Arrays of char Type
The syntax of initializing a string variable has two
variations:
a. Variation 1

char str1 [6] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

Here, str1 is declared to be a string variable with size six. It can store
maximum six characters. The initializer – list consists of comma
separated character constants. Note that the null character ‘\0’ is
clearly listed. This is required in this variation.
b. Variation 2
char str2 [6] = { “Hello” };

Here, str2 is also declared to be a string variable of size six. It


can store maximum six characters including null character.
2*2 Matrix
addition
String Handling Functions in ‘C’
To perform manipulations on string data, there are built-in-fraction
(library function) supported by ‘c’ compiler.
The string functions are:

1. STRLEN (S1)
2. STRCMP (S1,
S2)
3. STRCPY (S1, S2)
4. STRCAT (S1, S2)
5. STRREV(S)
6. STRLWR(S)
7. STRUPR(S)
Strlen(s1)
This function is used to return the length of the string
name S1.
strcmp(S1, S2)
This is a library function used to perform comparison between two strings.
This function returns a value < zero when string S1 is less than S2, return a
value 0 whenS1=S2 and return a value > 0 when S1>S2.
strcpy (S1, S2)
This is a library function used to copy the string
S2 to S1
strcat(S1, S2)
This is a library functionused to join two strings one after the other. This
function concatenates string S2 at the end of string S1
strrev(s)
The strrev() function is used to reverse the given string.
Strlwr(s)
• The strlwr( ) function is a built-in function in C and is used to convert
a given string into lowercase.
• This is a non-standard function that works only with older versions of
Microsoft C.
• It returns the modified string obtained after converting the characters
of the given string “s” to lowercase.
• Same as lower() which is defined in <ctype.h>
Strupr(s1)
• The strupr( ) function is used to converts a given string to uppercase.
// Compare two string without using strcmp() function
#include <stdio.h>
int main()
{ if(c==0)
char s1[20],s2[20],c=0,i=0; printf("strings are
printf("Enter the first string : "); same");
scanf("%s",s1); else
printf("Enter the second string : "); printf("strings are
scanf("%s",s2); not same");
while(s1[i]!='\0' &&s2[i]!='\0') return 0;
{ }
if(s1[i]!=s2[i])
{
c=1;
break;
}
i++;
}
Example 1. WAP to reverse a string Example 2. WAP to reverse a string entered from
entered from keyboard using in build keyboard without using strrev() function
string function
Example 3. WAP to copy string Example 4. WAP to copy string from one array
from one array onto another onto another without using in build string function
using in build string function
Example 5. A program to calculate the Example 6. A program to calculate the length
length of the string entered from keyboard. of the string entered from keyboard.

#include <stdio.h>
int main()
{
char s[] = "Programming is fun";
int i;

for (i = 0; s[i] != '\0'; ++i)


{
printf("Length of the string: %d", i);
}
return 0;
}
Example 7. WAP to concatenate two strings Example 8. WAP to input a string and check whether it is
inputted through keyboard. The result of palindrome or not.
concatenation should be displayed after #include<stdio.h>
copying on third variable. #include<conio.h>
#include<string.h>
int main()
{
char str[20],temp[20];
printf("enter a string\n");
scanf("%s",&str);
strcpy(temp,str);
strrev(str);
if(strcmp(temp,str)==0)
{
printf("the string %s is palindrome",temp);
}
else
{
printf("the string %s is not palindrome",temp);
}
getch();
return(0);
}
Example 9: WAP to scan a string and sort its character in alphabetical
order and display it.
temp=str[i];
#include<stdio.h> str[i]=str[j];
#include<conio.h> str[j]=temp;
#include<string.h> }
int main() }
{ }
char str[300],temp; printf("The sorted string is %s",str);
int l,i,j; getch();
printf("Enter a string\n"); return 0;
scanf("%s",&str); }
l=strlen(str);
for(i=0;i<l;i++)
{
for(j=i+1;j<l;j++)
{
if(str[i]>str[j])
{
Example 10:WAP to scan the name
of five cities and sort them on the if(strcmp(cities[i],cities[j])>0)
basis of alphabetical order and {
strcpy(tempstr,cities[i]);
display it.
strcpy(cities[i],cities[j]);
#include<stdio.h>
strcpy(cities[j],tempstr);
#include<conio.h>
}
#include<string.h>
}
int main()
}
{
printf("the cities in alphabetical order is \n");
char cities[5][20],tempstr[20];
for(i=0;i<5;i++)
int i,j;
{
printf("enter the name of 5 cities\n");
printf("%s\n",cities[i]);
for(i=0;i<5;i++)
}
{
getch();
scanf("%s",&cities[i]);
}
}
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
Find the output of following program:
a. b.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
#include<string.h> #include<string.h>
int main() int main()
{
{
char str[10]="hello";
char str[10]="hello"; int i;
int i; for(i=0;i<5;i++)
for(i=0;i<5;i++) {
{ printf("%c\n",str[i]);
printf("%d\n",str[i]); }
} return 0;
return 0;
}
Example 11. Program to print ENGINEERING as
Example 12. Program to print NEPAL as
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[10]="NEPAL";
int i,j;
for(i=0;i<strlen(str);i++)
{
for(j=0;j<=i;j++)
{
printf("%c",str[i]);
}
printf("\n");
}
getch();
return 0;

}
Example 13: Program to print NEPAL as #include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[10]="NEPAL";
int i,j;
for(i=0;i<strlen(str);i++)
{
printf("%d",i+1);
for(j=0;j<=i;j++)
{
printf("%c",str[i]);
}
printf("\n");
}
getch();
return 0;
}
Example 14: Program to print pulchowk as
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int i,j,k=7;
char str[10]="pulchowk";

for(i=7;i>=0;i--)
{

for(j=k;j<=7;j++)
{
putchar(str[j]);
}
putchar('\n');
k--;
}
return 0;

}
Example 15: Program to print pulchowk as
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int i,j,k=7;
char str[10]="pulchowk";

for(i=7;i>=0;i--)
{
for(j=i;j>=0;j--)
{
putchar(' ');
}
for(j=k;j<=7;j++)
{
putchar(str[j]);
}
putchar('\n');
k--;
}
return 0;
}

You might also like