Unit 4
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.
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).
For example:
int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
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:
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 −
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
#include <stdio.h>
int main()
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
#include <stdio.h>
int main()
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
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.
/* 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
int a[3][2] = {
{ 1 , 4 },
{ 5 , 2 },
{ 6 , 5 }
};
#include<stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1, 4 },
{ 5, 2 },
{ 6, 5 }};
Output :
1 4
5 2
6 5
a[0][0] = 1
a[0][1] = 4
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };
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 }};
Output :
1 0
5 2
6 0
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'.
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 () {
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
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.
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
/*declaration in Java
*/
Total Size in Bytes Total Bytes =sizeof(datatype of Total Bytes= sizeof(datatype of array variable)*
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.
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
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}}};
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
Sum Of Matrix:
2.2 0.5
-0.9 25.0
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’.
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";
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()
// 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".
#include <string.h>
Note: You have to include the code below to run 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[]="TEXAS";
In the above declaration NULL character (\0) will automatically be inserted at the
end of the string.
/*Displaying String*/
printf("%s",nickname);
return 0;
}
Output:
puts(nickname);
return 0;
}
C – String functions
C String function – strlen
Syntax:
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:
#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.
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:
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:
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:
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:
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:
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:
1 #include<stdio.h>
2 #include<string.h>
3 int main()
4{
6 printf("%s\n",strlwr (str));
7 return 0;
8}
● 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{
7 printf("%s\n",strupr(str));
8 return 0;
9}
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.
name[i][0];
where [i] is the index number of the string that needs to be accessed by library functions.
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