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

Unit 4

Thank you

Uploaded by

Laxman Pagare
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)
35 views

Unit 4

Thank you

Uploaded by

Laxman Pagare
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/ 41

unit-4

Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and


number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element in
an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.

Declaring Arrays
Why we need Array in C Programming?
Consider a scenario where you need to find out the average of 100 integer
numbers entered by user. In C, you have two ways to do this: 1) Define 100
variables with int data type and then perform 100 scanf() operations to store the
entered values in the variables and then at last calculate the average of them. 2)
Have a single integer array to store all the values, loop the array to store all the
entered values in array and later calculate the average.
Which solution is better according to you? Obviously the second solution, it is
convenient to store same data types in one single variable and later access them
using array index (we will discuss that later in this tutorial).

How to declare Array in C


int num[35]; /* An integer array of 35 elements */
char ch[10]; /* An array of characters for 10 elements */
Similarly an array can be of any data type such as double, float, short etc.
How to access element of an array in C
You can use array subscript (or index) to access any element stored in array.
Subscript starts with 0, which means arr[0] represents the first element in the
array arr.

In general arr[n-1] can be used to access nth element of an array. where n is


any integer number.

For example:

int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/

Example of Array In C programming to find out the average of 4 integers


#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output:

Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
Lets discuss the important parts of the above program:

Input data into the array


Here we are iterating the array from 0 to 3 because the size of the array is 4.
Inside the loop we are displaying a message to the user to enter the values. All
the input values are stored in the corresponding array elements using scanf
function.

for (x=0; x<4;x++)


{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
printf("num[%d]\n", num[x]);
}

Various ways to initialize an array


In the above example, we have just declared the array and later we initialized it
with the values input by user. However you can also initialize the array during
declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};


OR (both are same)

int arr[] = {1, 2, 3, 4, 5};


Un-initialized array always contain garbage values.

C Array – Memory representation


To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a
10-element array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is
an example to assign a single element of the array −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All
arrays have 0 as the index of their first element which is also called the base index and
the last index of an array will be total size of the array minus 1. Shown below is the
pictorial representation of the array we discussed above −

Accessing Array Elements


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 −
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to
salary variable. The following example Shows how to use all the three above
mentioned concepts viz. declaration, assignment, and accessing arrays −

C Program to Check Array bounds while Inputing Elements into


the Array

Accessing array out of bounds in C/C++


What if programmer accidentally accesses any index of array which is out of
bound ?

C don’t provide any specification which deal with problem of accessing invalid index. As
per ISO C standard it is called Undefined Behavior.
An undefined behavior (UB) is a result of executing computer code whose behavior is
not prescribed by the language specification to which the code can adhere to, for the
current state of the program (e.g. memory). This generally happens when the translator
of the source code makes certain assumptions, but these assumptions are not satisfied
during execution.
Examples of Undefined Behavior while accessing array out of bounds
1. Access non allocated location of memory: The program can access some piece of
memory which is owned by it.
// Program to demonstrate

// accessing array out of bounds

#include <stdio.h>

int main()

int arr[] = {1,2,3,4,5};

printf("arr [0] is %d\n", arr[0]);

// arr[10] is out of bound

printf("arr[10] is %d\n", arr[10]);

return 0;

Output :
arr [0] is 1
arr[10] is -1786647872
It can be observed here, that arr[10] is accessing a memory location containing a
garbage value.
2. Segmentation fault: The program can access some piece of memory which is not owned
by it, which can cause crashing of program such as segmentation fault.

// Program to demonstrate

// accessing array out of bounds

#include <stdio.h>

int main()

int arr[] = {1,2,3,4,5};

printf("arr [0] is %d\n",arr[0]);

printf("arr[10] is %d\n",arr[10]);
// allocation memory to out of bound

// element

arr[10] = 11;

printf("arr[10] is %d\n",arr[10]);

return 0;

Output :
Runtime Error : Segmentation Fault (SIGSEGV)
Important Points:
● Stay inside the bounds of the array in C programming while using arrays to avoid any such
errors.
● C++ however offers the std::vector class template, which does not require to perform
bounds checking. A vector also has the std::at() member function which can perform
bounds-checking.
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like
to contribute, you can also write an article using contribute.geeksforgeeks.org or mail
your article to [email protected]. See your article appearing on the
GeeksforGeeks main page and help other Geeks.
Please w

Initializing 2D Array
Two dimensional (2D) arrays in C programming with example
BY CHAITANYA SINGH | FILED UNDER: C-PROGRAMMING

An array of arrays is known as 2D array. The two dimensional (2D) array in C


programming is also known as matrix. A matrix can be represented as a table of
rows and columns. Before we discuss more about two Dimensional array lets
have a look at the following C program.

Simple Two dimensional(2D) Array Example


For now don’t worry how to initialize a two dimensional array, we will discuss that
part later. This program demonstrates how to store the elements entered by user
in a 2d array and how to display the elements of a two dimensional array.
#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
Output:

Enter value for disp[0][0]:1


Enter value for disp[0][1]:2
Enter value for disp[0][2]:3
Enter value for disp[1][0]:4
Enter value for disp[1][1]:5
Enter value for disp[1][2]:6
Two Dimensional array elements:
1 2 3
4 5 6
Initialization of 2D Array
There are two ways to initialize a two Dimensional arrays during declaration.

int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Although both the above declarations are valid, I recommend you to use the first
method as it is more readable, because you can visualize the rows and columns
of 2d array in this method.

Things that you must consider while initializing a 2D array


We already know, when we initialize a normal array (or you can say one
dimensional array) during declaration, we need not to specify the size of it.
However that’s not the case with 2D array, you must always specify the second
dimension even if you are specifying elements during the declaration. Let’s
understand this with the help of few examples –

/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
How to store user input data into 2D array
We can calculate how many elements a two dimensional array can have by using
this formula:
The array arr[n1][n2] can have n1*n2 elements. The array that we have in the
example below is having the dimensions 5 and 4. These dimensions are known
as subscripts. So this array has first subscript value as 5 and second
subscript value as 4.
So the array abc[5][4] can have 5*4 = 20 elements.

To store the elements entered by user we are using two for loops, one of them is
a nested loop. The outer loop runs from 0 to the (first subscript -1) and the inner
for loops runs from 0 to the (second subscript -1). This way the the order in which
user enters the elements would be abc[0][0], abc[0][1], abc[0][2]…so on.

#include<stdio.h>
int main(){
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++) {
for(j=0;j<4;j++) {
printf("Enter value for abc[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
return 0;
}
In above example, I have a 2D array abc of integer type. Conceptually you can
visualize the above array like this:
However the actual representation of this array in memory would be something
like this:

Poin

We have divided the concept into three different types –


Method 1 : Initializing all Elements rowwise
For initializing 2D Array we can need to assign values to each element of an array using
the below syntax.

int a[3][2] = {
{ 1 , 4 },
{ 5 , 2 },
{ 6 , 5 }
};

Consider the below program –

#include<stdio.h>

int main() {
int i, j;
int a[3][2] = { { 1, 4 },
{ 5, 2 },
{ 6, 5 }};

for (i = 0; i < 3; i++) {


for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}

Output :

1 4
5 2
6 5

We have declared an array of size 3 X 2, It contain overall 6 elements.


Row 1 : { 1 , 4 },
Row 2 : { 5 , 2 },
Row 3 : { 6 , 5 }

We have initialized each row independently

a[0][0] = 1
a[0][1] = 4

Method 2 : Combine and Initializing 2D Array


Initialize all Array elements but initialization is much straight forward. All values are
assigned sequentially and row-wise

int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };

Consider the below example program –

#include <stdio.h>

int main() {
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };

for (i = 0; i < 3; i++) {


for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}

Output will be same as that of above program #1

Method 3 : Some Elements could be initialized

int a[3][2] = {
{ 1 },
{ 5 , 2 },
{ 6 }
};

Now we have again going with the way 1 but we are removing some of the elements
from the array. In this case we have declared and initialized 2-D array like this

#include <stdio.h>

int main() {
int i, j;
int a[3][2] = { { 1 },
{ 5, 2 },
{ 6 }};

for (i = 0; i < 3; i++) {


for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}

Output :

1 0
5 2
6 0

Uninitialized elements will get default 0 value.

C programming language allows multidimensional arrays. Here is the general form of a


multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −
int threedim[5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A
two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a
two-dimensional integer array of size [x][y], you would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A
two-dimensional array can be considered as a table which will have x number of rows
and y number of columns. A two-dimensional array a, which contains three rows and
four columns can be shown as follows −

Thus, every element in the array a is identified by an element name of the form a[ i ][ j
], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely
identify each element in 'a'.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the subscripts, i.e., row
index and column index of the array. For example −
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array. You can
verify it in the above figure. Let us check the following program where we have used a
nested loop to handle a two-dimensional array −
Live Demo

#include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is
likely that most of the arrays you create will be of one or two dimensions.
Previous Page
Difference Between One-Dimensional (1D) and Two-Dimensional (2D)
Array

April 27, 2016 1 Comment

An array is a collection of
variables that are of similar data types and are alluded by a common name.
The main topic of our discussion is the difference between One-dimension
and Two-Dimension array. A one-dimensional array is a list of variables with
the same data type, whereas the two-Dimensional array is ‘array of arrays’
having similar data types. A specific element in an array is accessed by a
particular index of that array. Arrays in Java work differently as compared to
C++. C++ do not have bound checking on arrays whereas, Java have strict
bound checking on arrays.

There are several factors according to which the one-dimensional and


two-dimensional arrays can be differentiated, such as the way these are
initialized, accessed, implemented, inserted, deleted, traversed. So, let’s
begin with the differences between One-dimension and Two-Dimension array
along with a comparison chart.

Content: One-Dimensional (1d) Vs Two-dimensional (2d)


Array
1. Comparison Chart
2. Definition
3. Key Differences
4. Calculation of address
5. Conclusion
Comparison Chart:

BASIS FOR
ONE-DIMENSIONAL TWO-DIMENSIONAL
COMPARISON

Basic Store single list of elements of Store 'list of lists' or 'array of arrays' or 'array of

similar data type. one dimensional arrays'.

Declaration /*declaration in C++ /*declaration in C++

type variable_name[ size ];*/ type variable_name[size1][size2]; */

/*declaration in Java

type variable_name [ ]; /*declaration in Java

variable_name = new type[size]; type variable_name= new int[size1][size2]; */

*/

Alternative /* In Java /* In Java

Declaration int [ ] a= new int [10]; */ int [ ] [ ] a= new int [10][20]; */

Total Size in Bytes Total Bytes =sizeof(datatype of Total Bytes= sizeof(datatype of array variable)*

array variable)* size of array. size of first index*size of second index.

Receiving It can be received in a pointer, Parameter receiving it should define the

parameter sized array or an unsized array. rightmost dimension of an array.

Dimensions One dimensional. Two dimensional.


Memory Map of a 2-Dimensional Array

The arrangement of array elements in a two dimensional array of


students, which contains roll nos. in one column and the marks in
the other This is because memory doesn’t contain rows and
columns. In memory whether it is a one-dimensional or a
two-dimensional array the array elements are stored in one
continuous chain.

In C programming, you can create an array of arrays. These arrays are known as
multidimensional arrays. For example,

1. float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can
think the array as a table with 3 rows and each row has 4 columns.

Similarly, you can declare a three-dimensional (3d) array. For example,

1. float y[2][4][3];
Here, the array y can hold 24 elements.
Initializing a multidimensional array
Here is how you can initialize two-dimensional and three-dimensional arrays:

Initialization of a 2d array
1. // Different ways to initialize two-dimensional array
2.
3. int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
4.
5. int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
6.
7. int c[2][3] = {1, 3, 0, -1, 5, 9};

Initialization of a 3d array

You can initialize a three-dimensional array in a similar way like a two-dimensional


array. Here's an example,

1. int test[2][3][4] = {
2. {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
3. {{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

Example 1: Two-dimensional array to store and print


values
1. // C program to store temperature of two cities of a week and display it.
2. #include <stdio.h>
3. const int CITY = 2;
4. const int WEEK = 7;
5. int main()
6. {
7. int temperature[CITY][WEEK];
8.
9. // Using nested loop to store values in a 2d array
10. for (int i = 0; i < CITY; ++i)
11. {
12. for (int j = 0; j < WEEK; ++j)
13. {
14. printf("City %d, Day %d: ", i + 1, j + 1);
15. scanf("%d", &temperature[i][j]);
16. }
17. }
18. printf("\nDisplaying values: \n\n");
19.
20. // Using nested loop to display vlues of a 2d array
21. for (int i = 0; i < CITY; ++i)
22. {
23. for (int j = 0; j < WEEK; ++j)
24. {
25. printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
26. }
27. }
28. return 0;
29. }
Output

City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26

Displaying values:

City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26

Example 2: Sum of two matrices


1. // C program to find the sum of two matrices of order 2*2
2.
3. #include <stdio.h>
4. int main()
5. {
6. float a[2][2], b[2][2], result[2][2];
7.
8. // Taking input using nested for loop
9. printf("Enter elements of 1st matrix\n");
10. for (int i = 0; i < 2; ++i)
11. for (int j = 0; j < 2; ++j)
12. {
13. printf("Enter a%d%d: ", i + 1, j + 1);
14. scanf("%f", &a[i][j]);
15. }
16.
17. // Taking input using nested for loop
18. printf("Enter elements of 2nd matrix\n");
19. for (int i = 0; i < 2; ++i)
20. for (int j = 0; j < 2; ++j)
21. {
22. printf("Enter b%d%d: ", i + 1, j + 1);
23. scanf("%f", &b[i][j]);
24. }
25.
26. // adding corresponding elements of two arrays
27. for (int i = 0; i < 2; ++i)
28. for (int j = 0; j < 2; ++j)
29. {
30. result[i][j] = a[i][j] + b[i][j];
31. }
32.
33. // Displaying the sum
34. printf("\nSum Of Matrix:");
35.
36. for (int i = 0; i < 2; ++i)
37. for (int j = 0; j < 2; ++j)
38. {
39. printf("%.1f\t", result[i][j]);
40.
41. if (j == 1)
42. printf("\n");
43. }
44. return 0;
45. }
Output

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0

Example 3: Three-dimensional array


1. // C Program to store and print 12 values entered by the user
2.
3. #include <stdio.h>
4. int main()
5. {
6. int test[2][3][2];
7.
8. printf("Enter 12 values: \n");
9.
10. for (int i = 0; i < 2; ++i)
11. {
12. for (int j = 0; j < 3; ++j)
13. {
14. for (int k = 0; k < 2; ++k)
15. {
16. scanf("%d", &test[i][j][k]);
17. }
18. }
19. }
20.
21. // Printing values with proper index.
22.
23. printf("\nDisplaying values:\n");
24. for (int i = 0; i < 2; ++i)
25. {
26. for (int j = 0; j < 3; ++j)
27. {
28. for (int k = 0; k < 2; ++k)
29. {
30. printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
31. }
32. }
33. }
34.
35. return 0;
36. }
Output

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

Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
Strings in C
Strings are defined as an array of characters. The difference between a character array
and a string is the string is terminated with a special character ‘\0’.

Declaration of strings: Declaring a string is as simple as declaring a one dimensional


array. Below is the basic syntax for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used
define the length of the string, i.e the number of characters strings will store. Please
keep in mind that there is an extra terminating character which is the Null character (‘\0’)
used to indicate termination of string which differs strings from normal character arrays.

Initializing a String: A string can be initialized in different ways. We will explain this
with the help of an example. Below is an example to declare a string with name as str
and initialize it with “GeeksforGeeks”.
1. char str[] = "GeeksforGeeks";

2. char str[50] = "GeeksforGeeks";

3. char str[] =
{'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. char str[14] =
{'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Below is the memory representation of a string “Geeks”.

Let us now look at a sample program to get a clear understanding of declaring and
initializing a string in C and also how to print a string.

filter_none
edit
play_arrow
brightness_4
// C program to illustrate strings

#include<stdio.h>

int main()

// declare and initialize string

char str[] = "Geeks";

// print string

printf("%s",str);

return 0;
}

Output:
Geeks
We can see in the above program that strings can be printed using a normal printf
statements just like we print any other variable. Unlike arrays we do not need to print a
string, character by character. The C language does not provide an inbuilt data type for
strings but it has an access specifier “%s” which can be used to directly print and read
strings.
Below is a sample program to read a string from user:
filter_none
brightness_4
// C program to read strings

#include<stdio.h>

int main()

// declaring string

char str[50];

// reading string

scanf("%s",str);

// print string

printf("%s",str);

return 0;

}
You can see in the above program that string can also be read using a single scanf
statement. Also you might be thinking that why we have not used the ‘&’ sign with string
name ‘str’ in scanf statement! To understand this you will have to recall your knowledge
of scanf. We know that the ‘&’ sign is used to provide the address of the variable to the
scanf() function to store the value read in memory. As str[] is a character array so using
str without braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have
not used ‘&’ in this case as we are already providing the base address of the string to
scanf.
manipulate strings in C using library functions such as gets(), puts, strlen() and
more. You'll learn to get string from the user and perform operations on the string.

You need to often manipulate strings according to the need of a problem. Most, if
not all, of the time string manipulation can be done manually but, this makes
programming complex and large.
To solve this, C supports a large number of string handling functions in
the standard library "string.h".

Few commonly used string handling functions are discussed below:


Function Work of Function

strlen() computes string's length

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings

strlwr() converts string to lowercase

strupr() converts string to uppercase

Strings handling functions are defined under "string.h" header file.

#include <string.h>

Note: You have to include the code below to run string handling functions.

gets() and puts()


Functions gets() and puts() are two string functions to take string input from the
user and display it respectively as mentioned in the previous chapter.
1. #include<stdio.h>
2.
3. int main()
4. {
5. char name[30];
6. printf("Enter name: ");
7. gets(name); //Function to read string from user.
8. printf("Name: ");
9. puts(name); //Function to display string.
10. return 0;
11. }
Note: Though, gets() and puts() function handle strings, both these functions are
defined in "stdio.h" header file.
String is an array of characters. In this guide, we learn how to declare strings,
how to work with strings in C programming and how to use the pre-defined string
handling functions.

We will see how to compare two strings, concatenate strings, copy one string to
another & perform various string manipulation operations. We can perform such
operations using the pre-defined functions of “string.h” header file. In order to use
these string functions you must include string.h file in your C program.

String Declaration

Method 1:

char address[]={'T', 'E', 'X', 'A', 'S', '\0'};


Method 2: The above string can also be defined as –

char address[]="TEXAS";
In the above declaration NULL character (\0) will automatically be inserted at the
end of the string.

What is NULL Char “\0”?


'\0' represents the end of the string. It is also referred as String terminator & Null
Character.

String I/O in C programming


Read & write Strings in C using Printf() and Scanf() functions
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");

/* I am reading the input string and storing it in nickname


* Array name alone works as a base address of array so
* we can use nickname instead of &nickname here
*/
scanf("%s", nickname);

/*Displaying String*/
printf("%s",nickname);

return 0;
}
Output:

Enter your Nick name:Negan


Negan
Note: %s format specifier is used for strings input/output

Read & Write Strings in C using gets() and puts() functions


#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

/* Console display using puts */


puts("Enter your Nick name:");

/*Input using gets*/


gets(nickname);

puts(nickname);

return 0;
}

C – String functions
C String function – strlen
Syntax:

size_t strlen(const char *str)


size_t represents unsigned short
It returns the length of the string without including end character (terminating
char ‘\0’).

Example of strlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:

Length of string str1: 13


strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns
the total allocated size assigned to the array. So if I consider the above example
again then the following statements would return the below values.

strlen(str1) returned value 13.


sizeof(str1) would return value 20 as the array size is 20 (see the first statement in
main function).

C String function – strnlen


Syntax:

size_t strnlen(const char *str, size_t maxlen)


size_t represents unsigned short
It returns length of the string if it is less than the value specified for maxlen
(maximum length) otherwise it returns maxlen value.
Example of strnlen:

#include <stdio.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));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the string
length was 13 it returned only 10 because the maxlen was 10.

C String function – strcmp


int strcmp(const char *str1, const char *str2)
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 OR string1 is a substring of string2 then it would result in


a negative value. If string1 > string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for
compare strings.

Example of strcmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string 1 and 2 are different


C String function – strncmp
int strncmp(const char *str1, const char *str2, size_t n)
size_t is for unassigned short
It compares both the string till n characters or in other words it compares first n
characters of both the strings.

Example of strncmp:

#include <stdio.h>
#include <string.h>
int 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");
}
return 0;
}
Output:

string1 and string 2 are equal


C String function – strcat
char *strcat(char *str1, char *str2)
It concatenates two strings and returns the concatenated string.

Example of strcat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:

Output string after concatenation: HelloWorld


C String function – strncat
char *strncat(char *str1, char *str2, int 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.

Example of strncat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:

Concatenation using strncat: HelloWor


C String function – strcpy
char *strcpy( char *str1, char *str2)
It copies the string str2 into string str1, including the end character (terminator
char ‘\0’).

Example of strcpy:

#include <stdio.h>
#include <string.h>
int 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);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m gonna copied into s1


C String function – strncpy
char *strncpy( char *str1, char *str2, size_t n)
size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1 and
appends several terminator chars(‘\0’) to accumulate the length of str1 to make it
n.

Example of strncpy:

#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m


● strlwr( ) function converts a given string into lowercase. Syntax for strlwr( ) function is
given below.
char *strlwr(char *string);
● strlwr( ) function is non standard function which may not available in standard library in C.

EXAMPLE PROGRAM FOR STRLWR() FUNCTION IN C:


In this program, string “MODIFY This String To LOwer” is converted into lower case using
strlwr( ) function and result is displayed as “modify this string to lower”.

1 #include<stdio.h>

2 #include<string.h>
3 int main()

4{

5 char str[ ] = "MODIFY This String To LOwer";

6 printf("%s\n",strlwr (str));

7 return 0;

8}

COMPILE & RUN


OUTPUT:
modify this string to lower

● strupr( ) function converts a given string into uppercase. Syntax for strupr( ) function is
given below.
char *strupr(char *string);
● strupr( ) function is non standard function which may not available in standard library in C.
EXAMPLE PROGRAM FOR STRUPR() FUNCTION IN C:
In this program, string “Modify This String To Upper” is converted into uppercase using
strupr( ) function and result is displayed as “MODIFY THIS STRING TO UPPER”.

1 #include<stdio.h>

2 #include<string.h>

4 int main()

5{

6 char str[ ] = "Modify This String To Upper";

7 printf("%s\n",strupr(str));

8 return 0;

9}

COMPILE & RUN


OUTPUT:
MODIFY THIS STRING TO UPPER

C STRING
2D CHARACTER ARRAY-STRING ARRAY-DECLARATION AND INITIALIZATION
We have successfully learned the basic concepts and different library functions that C Programming
offers. Another interesting concept is the use of 2D character arrays. In the previous tutorial, we
already saw that string is nothing but an array of characters which ends with a ‘\0’. 2D character
arrays are very similar to the 2D integer arrays. We store the elements and perform other operations
in a similar manner. A 2D character array is more like a String array. It allows us to store multiple
strings under the same name.

Table of Contents
● Declaration and Initialization of a 2D character array
● Taking Data input from user
● Printing the array elements
● Program to search for a string in the string array
● Recommended -
DECLARATION AND INITIALIZATION OF A 2D CHARACTER
ARRAY
A 2D character array is declared in the following manner:

char name[5][10];

The order of the subscripts is to kept in mind during declaration. The first subscript [5] represents
the number of Strings that we want our array to contain and the second subscript [10] represents
the length of each String.This is static memory allocation. We are giving 5*10=50 memory locations
for the array elements to be stored in the array.

Initialization of the character array occurs in this manner:


1. char name[5][10]={
2. "tree",
3. "bowl",
4. "hat",
5. "mice",
6. "toon"
7. };
see the diagram below to understand how the elements are stored in the memory location:
The areas marked in green shows the memory locations that are reserved for the array but are not
used by the string. Each character occupies 1 byte of storage from the memory.

TAKING DATA INPUT FROM USER


In order to take string data input from the user we need to follow the following syntax:
1. for(i=0 ;i<5 ;i++ )
2. scanf("%s",&name[i][0]);
Here we see that the second subscript remains [0]. This is because it shows the length of the string
and before entering any string the length of the string is 0.

PRINTING THE ARRAY ELEMENTS


The way a 2D character array is printed in not the same as a 2D integer array. This is because we
see that all the spaces in the array are not occupied by the string entered by the user. If we display it
in the same way as a 2D integer array we will get unnecessary garbage values in unoccupied
spaces. Here is how we can display all the string elements:
1. for(i=0 ;i<5 ;i++)
2. printf("%s\n",name[i]);
This format will print only the string contained in the index numbers specified and eliminate any
garbage values after ‘\0’. All the string library functions that we have come across in the previous
tutorials can be used for the operations on strings contained in the string array. Each string can be
referred to in this form:

name[i][0];

where [i] is the index number of the string that needs to be accessed by library functions.

First you need to create an array of strings.

char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];
Then, you need to enter the string into the array

int i;
for (i=0; i<NUMBER_OF_WORDS; i++) {
scanf ("%s" , arrayOfWords[i]);
}
Finally in oreder to print them use

for (i=0; i<NUMBER_OF_WORDS; i++) {


printf ("%s" , arrayOfWords[i]);
}

You might also like