Unit 2
- What is an array explain in detail?
An array is a collection of data items, all of the same type, accessed using a common name.
A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may.
Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.
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.
Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.
Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.
In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allocated only once, at the time the array is declared. The array does NOT change sizes later if the variable used to declare it changes. )
Examples:
int i, j, intArray[ 10 ], number;
float floatArray[ 1000 ];
int tableArray[ 3 ][ 5 ]; /* 3 rows by 5 columns */
const int NROWS = 100; // ( Old code would use #define NROWS 100 )
const int NCOLS = 200; // ( Old code would use #define NCOLS 200 )
float matrix[ NROWS ][ NCOLS ];
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 −
#include <stdio.h>
Int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
1-D array has 1 row and multiple columns but multidimensional array has of multiple rows and multiple columns.
2. What is 2 dimensional array?
Two Dimensional array:
It is the simplest multidimensional array. They are also called as matrix.
Declaration:
Data-type array_name[no.of rows][no. Of columns];
Total no of elements= No.of rows * No. Of Columns
Example 3: int a[2][3]
This example illustrates two dimensional array a of 2 rows and 3 columns.
Col 0Col 1Col 2
Row 0
a[0][0]
| a[0][1]
| a[0][2]
|
a[1][0]
| a[1][1]
| a[1][2]
|
Row 1
Fig.2: Index positions of elements of a[2][3]
Total no of elements: 2*3=6
Total no of bytes occupied: 6( total no.of elements )*2(Size of one element)=12
Initialization and Storage Representation:
In C, two dimensional arrays can be initialized in different number of ways. Specification of no. Of columns in 2 dimensional array is mandatory while no of rows is optional.
Int a[2][3]={{1,3,0}, // Elements of 1st row
{-1,5,9}}; // Elements of 2nd row
OR
Int a[][3]={{1,3,0}, // Elements of 1st row
{-1,5,9}}; // Elements of 2nd row
OR
Int a[2][3]={1,3,0,-1,5,9};
Fig. 3 gives general storage representation of 2 dimensional array
Col 0 Col 1 Col n
Row 0
a[0][0]
| a[0][1]
|
--- | a[0][n]
|
a[1][0]
| a[1][1]
|
--- | a[1][n]
|
- | -
| - | - |
a[m][0] |
a[m][1] |
|
a[m][n] |
Row 1
-
-
Row m
Fig.3 General Storage Representation of 2 dimensional array.
Eg 4. int a[2][3]={1,3,0,-1,5,9}
1
| 3 | 0 |
-1
| 5 | 9 |
Row 0
Row 1
Col 0 col1 col2
Accessing Two-Dimensional Array Elements:
An element in 2-dimensional array is accessed by using the subscripts i.e. row index and column index of the array. For example:
Int val = A[1][2];
The above statement will access element from the 2nd row and third column of the array A i.e. element 9.
3. Explain String in detail with example
The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character ('\0') is important in a string since it is the only way to identify where the string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.
There are two ways to declare a string in c language.
- By char array
- By string literal
Let's see the example of declaring string by char array in C language.
- Char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.
While declaring string, size is not mandatory. So we can write the above code as given below:
- Char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
We can also define the string by the string literal in C language. For example:
- Char ch[]="javatpoint";
In such case, '\0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
There are two main differences between char array and literal.
- We need to add the null character '\0' at the end of the array by ourself whereas, it is appended internally by the compiler in the case of the character array.
- The string literal cannot be reassigned to another set of characters whereas, we can reassign the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is used as a format specifier for the string in c language.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
- Char ch2[11]="javatpoint";
- Printf("Char Array Value is: %s\n", ch);
- Printf("String Literal Value is: %s\n", ch2);
- Return 0;
- }
Output
Char Array Value is: javatpoint
String Literal Value is: javatpoint
Traversing String
Traversing the string is one of the most important aspects in any of the programming languages. We may need to manipulate a very large text which can be done by traversing the text. Traversing string is somewhat different from the traversing an integer array. We need to know the length of the array to traverse an integer array, whereas we may use the null character in the case of string to identify the end the string and terminate the loop.
Hence, there are two ways to traverse a string.
- By using the length of string
- By using the null character.
Let's discuss each one of them.
Using the length of string
Let's see an example of counting the number of vowels in a string.
- #include<stdio.h>
- Void main ()
- {
- Char s[11] = "javatpoint";
- Int i = 0;
- Int count = 0;
- While(i<11)
- {
- If(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
- {
- Count ++;
- }
- i++;
- }
- Printf("The number of vowels %d",count);
- }
Output
The number of vowels 4
4. Explain pointers with strings
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far. However, pointers can be used to point to the strings. There are various advantages of using pointers to point strings. Let us consider the following example to access the string via the pointer.
- #include<stdio.h>
- Void main ()
- {
- Char s[11] = "javatpoint";
- Char *p = s; // pointer p is pointing to string s.
- Printf("%s",p); // the string javatpoint is printed if we print p.
- }
Output
Javatpoint
As we know that string is an array of characters, the pointers can be used in the same way they were used with arrays. In the above example, p is declared as a pointer to the array of characters s. P affects similar to s since s is the base address of the string and treated as a pointer internally. However, we can not change the content of s or copy the content of s into another string directly. For this purpose, we need to use the pointers to store the strings. In the following example, we have shown the use of pointers to copy the content of a string into another.
- #include<stdio.h>
- Void main ()
- {
- Char *p = "hello javatpoint";
- Printf("String p: %s\n",p);
- Char *q;
- Printf("copying the content of p into q...\n");
- q = p;
- Printf("String q: %s\n",q);
- }
Output
String p: hello javatpoint
Copying the content of p into q...
String q: hello javatpoint
Once a string is defined, it cannot be reassigned to another set of characters. However, using pointers, we can assign the set of characters to the string. Consider the following example.
- #include<stdio.h>
- Void main ()
- {
- Char *p = "hello javatpoint";
- Printf("Before assigning: %s\n",p);
- p = "hello";
- Printf("After assigning: %s\n",p);
- }
Output
Before assigning: hello javatpoint
After assigning: hello
5. Explain handling string as array of character
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
Char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
Char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string −
#include <stdio.h>
Int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings −
Sr.No. | Function & Purpose |
1 | Strcpy(s1, s2); Copies string s2 into string s1. |
2 | Strcat(s1, s2); Concatenates string s2 onto the end of string s1. |
3 | Strlen(s1); Returns the length of string s1. |
4 | Strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. |
5 | Strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. |
6 | Strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. |
The following example uses some of the above-mentioned functions −
#include <stdio.h>
#include <string.h>
Int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Strcpy( str3, str1) : Hello
Strcat( str1, str2): HelloWorld
Strlen(str1) : 10
6. Explain function of string in detail with examples
There are many important string functions defined in "string.h" library.
No. | Function | Description |
1) | Strlen(string_name) | Returns the length of string name. |
2) | Strcpy(destination, source) | Copies the contents of source string to destination string. |
3) | Strcat(first_string, second_string) | Concats or joins first string with second string. The result of the string is stored in first string. |
4) | Strcmp(first_string, second_string) | Compares the first string with second string. If both strings are same, it returns 0. |
5) | Strrev(string) | Returns reverse string. |
6) | Strlwr(string) | Returns string characters in lowercase. |
7) | Strupr(string) | Returns string characters in uppercase. |
C String Length: strlen() function
The strlen() function returns the length of the given string. It doesn't count null character '\0'.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
- Printf("Length of string is: %d",strlen(ch));
- Return 0;
- }
Output:
Length of string is: 10
C Copy String: strcpy()
The strcpy(destination, source) function copies the source string in destination.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
- Char ch2[20];
- Strcpy(ch2,ch);
- Printf("Value of second string is: %s",ch2);
- Return 0;
- }
Output:
Value of second string is: javatpoint
C String Concatenation: strcat()
The strcat(first_string, second_string) function concatenates two strings and result is
Returned to first_string.
#include<stdio.h>
#include <string.h>
Int main(){
Char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
Char ch2[10]={'c', '\0'};
Strcat(ch,ch2);
Printf("Value of first string is: %s",ch);
Return 0;
}
Output:
Value of first string is: helloc
C Compare String: strcmp()
The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are equal.
Here, we are using gets() function which reads string from the console.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str1[20],str2[20];
- Printf("Enter 1st string: ");
- Gets(str1);//reads string from console
- Printf("Enter 2nd string: ");
- Gets(str2);
- If(strcmp(str1,str2)==0)
- Printf("Strings are equal");
- Else
- Printf("Strings are not equal");
- Return 0;
- }
Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal
C Reverse String: strrev()
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev() function.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str[20];
- Printf("Enter string: ");
- Gets(str);//reads string from console
- Printf("String is: %s",str);
- Printf("\nReverse String is: %s",strrev(str));
- Return 0;
- }
Output:
Enter string: javatpoint
String is: javatpoint
Reverse String is: tnioptavaj
C String Lowercase: strlwr()
The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr() function.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str[20];
- Printf("Enter string: ");
- Gets(str);//reads string from console
- Printf("String is: %s",str);
- Printf("\nLower String is: %s",strlwr(str));
- Return 0;
- }
Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint
C String Uppercase: strupr()
The strupr(string) function returns string characters in uppercase. Let's see a simple example of strupr() function.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str[20];
- Printf("Enter string: ");
- Gets(str);//reads string from console
- Printf("String is: %s",str);
- Printf("\nUpper String is: %s",strupr(str));
- Return 0;
- }
Output:
Enter string: javatpoint
String is: javatpoint
Upper String is: JAVATPOINT
C String strstr()
The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is used to return substring from first match till the last character.
Syntax:
- Char *strstr(const char *string, const char *match)
String strstr() parameters
String: It represents the full string from where substring will be searched.
Match: It represents the substring to be searched in the full string.
String strstr() example
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str[100]="this is javatpoint with c and java";
- Char *sub;
- Sub=strstr(str,"java");
- Printf("\nSubstring is: %s",sub);
- Return 0;
- }
Output:
Javatpoint with c and java
7. Explain structure with examples
A structure can be considered as a template used for defining a collection of variables under a single name. Structures help programmers to group elements of different data types into a single logical unit (Unlike arrays which permit a programmer to group only elements of same data type).
- Why Use Structures
• Ordinary variables can hold one piece of information
• arrays can hold a number of pieces of information of the same data type.
For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int).
If data about say 3 such books is to be stored, then we can follow two approaches:
Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages.
Use a structure variable.
Suppose we want to create a employee database. Then, we can define a structure
Called employee with three elements id, name and salary. The syntax of this structure is as
Follows:
Struct employee
{ int id;
Char name[50];
Float salary;
};
Note:
Struct keyword is used to declare structure.
Members of structure are enclosed within opening and closing braces.
Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined or maintained in separate header file.
Declaration of Structure reserves no space.
It is nothing but the “ Template / Map / Shape ” of the structure .
Memory is created , very first time when the variable is created / Instance is created.
- Structure variable declaration:
We can declare the variable of structure in two ways
- Declare the structure inside main function
- Declare the structure outside the main function.
1. Declare the structure inside main function
Following example show you, how structure variable is declared inside main function
Struct employee
{
Int id;
Char name[50];
Float salary;
};
Int main()
{
Struct employee e1, e2;
Return 0;
}
In this example the variable of structure employee is created inside main function that e1 ,e2.
2. Declare the structure outside main function
Following example show you, how structure variable is declared outside the main function
Struct employee
{
Int id;
Char name[50];
Float salary;
}e1,e2;
8. Explain structure initialization with different ways and with examples
- Structure Initialization
1. When we declare a structure, memory is not allocated for un-initialized variable.
2. Let us discuss very familiar example of structure student , we can initialize structure variable
In different ways –
Way 1 : Declare and Initialize
Struct student
{
Char name[20];
Int roll;
Float marks;
}std1 = { "Poonam",89,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration we
Have initialized the structure variable.
Std1 = { "Poonam",89,78.3 }
This is the code for initializing structure variable in C programming
Way 2 : Declaring and Initializing Multiple Variables
Struct student
{
Char name[20];
Int roll;
Float marks;
}
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
In this example, we have declared two structure variables in above code. After declaration of variable we have initialized two variable.
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
Way 3 : Initializing Single member
Struct student
{
Int mark1;
Int mark2;
Int mark3;
} sub1={67};
Though there are three members of structure,only one is initialized , Then remaining two members
Are initialized with Zero. If there are variables of other data type then their initial values will be –
Data Type Default value if not initialized
Integer 0
Float 0.00
Char NULL
Way 4 : Initializing inside main
Struct student
{
Int mark1;
Int mark2;
Int mark3;
};
Void main()
{
Struct student s1 = {89,54,65};
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won’t be allocated for the structure. i.e only writing below
Declaration statement will never allocate memory
Struct student
{
Int mark1;
Int mark2;
Int mark3;
};
We need to initialize structure variable to allocate some memory to the structure.
Struct student s1 = {89,54,65};
9. What is union explain in detail?
Unions are quite similar to the structures in C. Union is also a derived type as
Structure. Union can be defined in same manner as structures just the keyword
Used in defining union in union where keyword used in defining structure was struct.
Union car
{
Char name[50];
Int price;
};
Union variables can be created in similar manner as structure variable.
Union car
{
Char name[50];
Int price;
}c1, c2, *c3;
OR;
Union car
{
Char name[50];
Int price;
};
-------Inside Function-----------
Union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union
Car is created.
- Memory allocation for union
Like structure memory is allocated to union only when we create the variable of it.
The memory is allocated to union according to the largest data members of the union.
- Accessing members of an union
Array elements are accessed using the Subscript variable , Similarly Union members are accessed using dot [.] operator.
(.) is called as “union member Operator”.
Use this Operator in between “Union variable” & “member name”
Union employee
{
Int id;
Char name[50];
Float salary;
} ;
Void main()
{
union employee e1= { 1, “ABC”, 50000 };
printf(“%d”, e. Id);
printf(“%s”, e. Name);
}
O/P- garbage value, ABC
10. Explain array with structure with example
Structure is collection of different data type. An object of structure represents a singlerecord in memory, if we want more than one record of structure type, we have tocreate an array of structure or object. As we know, an array is a collection of similartype, therefore an array can be of structure type.
Syntax for declaring structure array
Struct struct-name
{
Datatype var1;
Datatype var2;
- - - - - - - - - -
- - - - - - - - - -
Datatype varN;
};
Struct struct-name obj [ size ];
Example for declaring structure array
#include<stdio.h>
Struct Employee
{
Int Id;
Char Name[25];
Int Age;
Long Salary;
};
Void main()
{
Int i;
Struct Employee Emp[ 3 ]; //Statement 1
For(i=0;i<3;i++)
{
Printf("\nEnter details of %d Employee",i+1);
Printf("\n\tEnter Employee Id : ");
Scanf("%d",&Emp[i].Id);
Printf("\n\tEnter Employee Name : ");
Scanf("%s",&Emp[i].Name);
Printf("\n\tEnter Employee Age : ");
Scanf("%d",&Emp[i].Age);
Printf("\n\tEnter Employee Salary : ");
Scanf("%ld",&Emp[i].Salary);
}
Printf("\nDetails of Employees");
For(i=0;i<3;i++)
Printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :
Enter details of 1 Employee
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
Enter details of 3 Employee
Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
In the above example, we are getting and displaying the data of 3 employee using
Array of object. Statement 1 is creating an array of Employee Emp to store the records
Of 3 employees.
Unit 2
- What is an array explain in detail?
Unit 2
- What is an array explain in detail?
An array is a collection of data items, all of the same type, accessed using a common name.
A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may.
Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.
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.
Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.
Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.
In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allocated only once, at the time the array is declared. The array does NOT change sizes later if the variable used to declare it changes. )
Examples:
int i, j, intArray[ 10 ], number;
float floatArray[ 1000 ];
int tableArray[ 3 ][ 5 ]; /* 3 rows by 5 columns */
const int NROWS = 100; // ( Old code would use #define NROWS 100 )
const int NCOLS = 200; // ( Old code would use #define NCOLS 200 )
float matrix[ NROWS ][ NCOLS ];
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 −
#include <stdio.h>
Int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
1-D array has 1 row and multiple columns but multidimensional array has of multiple rows and multiple columns.
2. What is 2 dimensional array?
Two Dimensional array:
It is the simplest multidimensional array. They are also called as matrix.
Declaration:
Data-type array_name[no.of rows][no. Of columns];
Total no of elements= No.of rows * No. Of Columns
Example 3: int a[2][3]
This example illustrates two dimensional array a of 2 rows and 3 columns.
Col 0Col 1Col 2
Row 0
a[0][0]
| a[0][1]
| a[0][2]
|
a[1][0]
| a[1][1]
| a[1][2]
|
Row 1
Fig.2: Index positions of elements of a[2][3]
Total no of elements: 2*3=6
Total no of bytes occupied: 6( total no.of elements )*2(Size of one element)=12
Initialization and Storage Representation:
In C, two dimensional arrays can be initialized in different number of ways. Specification of no. Of columns in 2 dimensional array is mandatory while no of rows is optional.
Int a[2][3]={{1,3,0}, // Elements of 1st row
{-1,5,9}}; // Elements of 2nd row
OR
Int a[][3]={{1,3,0}, // Elements of 1st row
{-1,5,9}}; // Elements of 2nd row
OR
Int a[2][3]={1,3,0,-1,5,9};
Fig. 3 gives general storage representation of 2 dimensional array
Col 0 Col 1 Col n
Row 0
a[0][0]
| a[0][1]
|
--- | a[0][n]
|
a[1][0]
| a[1][1]
|
--- | a[1][n]
|
- | -
| - | - |
a[m][0] |
a[m][1] |
|
a[m][n] |
Row 1
-
-
Row m
Fig.3 General Storage Representation of 2 dimensional array.
Eg 4. int a[2][3]={1,3,0,-1,5,9}
1
| 3 | 0 |
-1
| 5 | 9 |
Row 0
Row 1
Col 0 col1 col2
Accessing Two-Dimensional Array Elements:
An element in 2-dimensional array is accessed by using the subscripts i.e. row index and column index of the array. For example:
Int val = A[1][2];
The above statement will access element from the 2nd row and third column of the array A i.e. element 9.
3. Explain String in detail with example
The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character ('\0') is important in a string since it is the only way to identify where the string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.
There are two ways to declare a string in c language.
- By char array
- By string literal
Let's see the example of declaring string by char array in C language.
- Char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.
While declaring string, size is not mandatory. So we can write the above code as given below:
- Char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
We can also define the string by the string literal in C language. For example:
- Char ch[]="javatpoint";
In such case, '\0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
There are two main differences between char array and literal.
- We need to add the null character '\0' at the end of the array by ourself whereas, it is appended internally by the compiler in the case of the character array.
- The string literal cannot be reassigned to another set of characters whereas, we can reassign the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is used as a format specifier for the string in c language.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
- Char ch2[11]="javatpoint";
- Printf("Char Array Value is: %s\n", ch);
- Printf("String Literal Value is: %s\n", ch2);
- Return 0;
- }
Output
Char Array Value is: javatpoint
String Literal Value is: javatpoint
Traversing String
Traversing the string is one of the most important aspects in any of the programming languages. We may need to manipulate a very large text which can be done by traversing the text. Traversing string is somewhat different from the traversing an integer array. We need to know the length of the array to traverse an integer array, whereas we may use the null character in the case of string to identify the end the string and terminate the loop.
Hence, there are two ways to traverse a string.
- By using the length of string
- By using the null character.
Let's discuss each one of them.
Using the length of string
Let's see an example of counting the number of vowels in a string.
- #include<stdio.h>
- Void main ()
- {
- Char s[11] = "javatpoint";
- Int i = 0;
- Int count = 0;
- While(i<11)
- {
- If(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
- {
- Count ++;
- }
- i++;
- }
- Printf("The number of vowels %d",count);
- }
Output
The number of vowels 4
4. Explain pointers with strings
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far. However, pointers can be used to point to the strings. There are various advantages of using pointers to point strings. Let us consider the following example to access the string via the pointer.
- #include<stdio.h>
- Void main ()
- {
- Char s[11] = "javatpoint";
- Char *p = s; // pointer p is pointing to string s.
- Printf("%s",p); // the string javatpoint is printed if we print p.
- }
Output
Javatpoint
As we know that string is an array of characters, the pointers can be used in the same way they were used with arrays. In the above example, p is declared as a pointer to the array of characters s. P affects similar to s since s is the base address of the string and treated as a pointer internally. However, we can not change the content of s or copy the content of s into another string directly. For this purpose, we need to use the pointers to store the strings. In the following example, we have shown the use of pointers to copy the content of a string into another.
- #include<stdio.h>
- Void main ()
- {
- Char *p = "hello javatpoint";
- Printf("String p: %s\n",p);
- Char *q;
- Printf("copying the content of p into q...\n");
- q = p;
- Printf("String q: %s\n",q);
- }
Output
String p: hello javatpoint
Copying the content of p into q...
String q: hello javatpoint
Once a string is defined, it cannot be reassigned to another set of characters. However, using pointers, we can assign the set of characters to the string. Consider the following example.
- #include<stdio.h>
- Void main ()
- {
- Char *p = "hello javatpoint";
- Printf("Before assigning: %s\n",p);
- p = "hello";
- Printf("After assigning: %s\n",p);
- }
Output
Before assigning: hello javatpoint
After assigning: hello
5. Explain handling string as array of character
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
Char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
Char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string −
#include <stdio.h>
Int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings −
Sr.No. | Function & Purpose |
1 | Strcpy(s1, s2); Copies string s2 into string s1. |
2 | Strcat(s1, s2); Concatenates string s2 onto the end of string s1. |
3 | Strlen(s1); Returns the length of string s1. |
4 | Strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. |
5 | Strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. |
6 | Strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. |
The following example uses some of the above-mentioned functions −
#include <stdio.h>
#include <string.h>
Int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Strcpy( str3, str1) : Hello
Strcat( str1, str2): HelloWorld
Strlen(str1) : 10
6. Explain function of string in detail with examples
There are many important string functions defined in "string.h" library.
No. | Function | Description |
1) | Strlen(string_name) | Returns the length of string name. |
2) | Strcpy(destination, source) | Copies the contents of source string to destination string. |
3) | Strcat(first_string, second_string) | Concats or joins first string with second string. The result of the string is stored in first string. |
4) | Strcmp(first_string, second_string) | Compares the first string with second string. If both strings are same, it returns 0. |
5) | Strrev(string) | Returns reverse string. |
6) | Strlwr(string) | Returns string characters in lowercase. |
7) | Strupr(string) | Returns string characters in uppercase. |
C String Length: strlen() function
The strlen() function returns the length of the given string. It doesn't count null character '\0'.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
- Printf("Length of string is: %d",strlen(ch));
- Return 0;
- }
Output:
Length of string is: 10
C Copy String: strcpy()
The strcpy(destination, source) function copies the source string in destination.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
- Char ch2[20];
- Strcpy(ch2,ch);
- Printf("Value of second string is: %s",ch2);
- Return 0;
- }
Output:
Value of second string is: javatpoint
C String Concatenation: strcat()
The strcat(first_string, second_string) function concatenates two strings and result is
Returned to first_string.
#include<stdio.h>
#include <string.h>
Int main(){
Char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
Char ch2[10]={'c', '\0'};
Strcat(ch,ch2);
Printf("Value of first string is: %s",ch);
Return 0;
}
Output:
Value of first string is: helloc
C Compare String: strcmp()
The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are equal.
Here, we are using gets() function which reads string from the console.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str1[20],str2[20];
- Printf("Enter 1st string: ");
- Gets(str1);//reads string from console
- Printf("Enter 2nd string: ");
- Gets(str2);
- If(strcmp(str1,str2)==0)
- Printf("Strings are equal");
- Else
- Printf("Strings are not equal");
- Return 0;
- }
Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal
C Reverse String: strrev()
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev() function.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str[20];
- Printf("Enter string: ");
- Gets(str);//reads string from console
- Printf("String is: %s",str);
- Printf("\nReverse String is: %s",strrev(str));
- Return 0;
- }
Output:
Enter string: javatpoint
String is: javatpoint
Reverse String is: tnioptavaj
C String Lowercase: strlwr()
The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr() function.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str[20];
- Printf("Enter string: ");
- Gets(str);//reads string from console
- Printf("String is: %s",str);
- Printf("\nLower String is: %s",strlwr(str));
- Return 0;
- }
Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint
C String Uppercase: strupr()
The strupr(string) function returns string characters in uppercase. Let's see a simple example of strupr() function.
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str[20];
- Printf("Enter string: ");
- Gets(str);//reads string from console
- Printf("String is: %s",str);
- Printf("\nUpper String is: %s",strupr(str));
- Return 0;
- }
Output:
Enter string: javatpoint
String is: javatpoint
Upper String is: JAVATPOINT
C String strstr()
The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is used to return substring from first match till the last character.
Syntax:
- Char *strstr(const char *string, const char *match)
String strstr() parameters
String: It represents the full string from where substring will be searched.
Match: It represents the substring to be searched in the full string.
String strstr() example
- #include<stdio.h>
- #include <string.h>
- Int main(){
- Char str[100]="this is javatpoint with c and java";
- Char *sub;
- Sub=strstr(str,"java");
- Printf("\nSubstring is: %s",sub);
- Return 0;
- }
Output:
Javatpoint with c and java
7. Explain structure with examples
A structure can be considered as a template used for defining a collection of variables under a single name. Structures help programmers to group elements of different data types into a single logical unit (Unlike arrays which permit a programmer to group only elements of same data type).
- Why Use Structures
• Ordinary variables can hold one piece of information
• arrays can hold a number of pieces of information of the same data type.
For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int).
If data about say 3 such books is to be stored, then we can follow two approaches:
Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages.
Use a structure variable.
Suppose we want to create a employee database. Then, we can define a structure
Called employee with three elements id, name and salary. The syntax of this structure is as
Follows:
Struct employee
{ int id;
Char name[50];
Float salary;
};
Note:
Struct keyword is used to declare structure.
Members of structure are enclosed within opening and closing braces.
Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined or maintained in separate header file.
Declaration of Structure reserves no space.
It is nothing but the “ Template / Map / Shape ” of the structure .
Memory is created , very first time when the variable is created / Instance is created.
- Structure variable declaration:
We can declare the variable of structure in two ways
- Declare the structure inside main function
- Declare the structure outside the main function.
1. Declare the structure inside main function
Following example show you, how structure variable is declared inside main function
Struct employee
{
Int id;
Char name[50];
Float salary;
};
Int main()
{
Struct employee e1, e2;
Return 0;
}
In this example the variable of structure employee is created inside main function that e1 ,e2.
2. Declare the structure outside main function
Following example show you, how structure variable is declared outside the main function
Struct employee
{
Int id;
Char name[50];
Float salary;
}e1,e2;
8. Explain structure initialization with different ways and with examples
- Structure Initialization
1. When we declare a structure, memory is not allocated for un-initialized variable.
2. Let us discuss very familiar example of structure student , we can initialize structure variable
In different ways –
Way 1 : Declare and Initialize
Struct student
{
Char name[20];
Int roll;
Float marks;
}std1 = { "Poonam",89,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration we
Have initialized the structure variable.
Std1 = { "Poonam",89,78.3 }
This is the code for initializing structure variable in C programming
Way 2 : Declaring and Initializing Multiple Variables
Struct student
{
Char name[20];
Int roll;
Float marks;
}
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
In this example, we have declared two structure variables in above code. After declaration of variable we have initialized two variable.
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
Way 3 : Initializing Single member
Struct student
{
Int mark1;
Int mark2;
Int mark3;
} sub1={67};
Though there are three members of structure,only one is initialized , Then remaining two members
Are initialized with Zero. If there are variables of other data type then their initial values will be –
Data Type Default value if not initialized
Integer 0
Float 0.00
Char NULL
Way 4 : Initializing inside main
Struct student
{
Int mark1;
Int mark2;
Int mark3;
};
Void main()
{
Struct student s1 = {89,54,65};
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won’t be allocated for the structure. i.e only writing below
Declaration statement will never allocate memory
Struct student
{
Int mark1;
Int mark2;
Int mark3;
};
We need to initialize structure variable to allocate some memory to the structure.
Struct student s1 = {89,54,65};
9. What is union explain in detail?
Unions are quite similar to the structures in C. Union is also a derived type as
Structure. Union can be defined in same manner as structures just the keyword
Used in defining union in union where keyword used in defining structure was struct.
Union car
{
Char name[50];
Int price;
};
Union variables can be created in similar manner as structure variable.
Union car
{
Char name[50];
Int price;
}c1, c2, *c3;
OR;
Union car
{
Char name[50];
Int price;
};
-------Inside Function-----------
Union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union
Car is created.
- Memory allocation for union
Like structure memory is allocated to union only when we create the variable of it.
The memory is allocated to union according to the largest data members of the union.
- Accessing members of an union
Array elements are accessed using the Subscript variable , Similarly Union members are accessed using dot [.] operator.
(.) is called as “union member Operator”.
Use this Operator in between “Union variable” & “member name”
Union employee
{
Int id;
Char name[50];
Float salary;
} ;
Void main()
{
union employee e1= { 1, “ABC”, 50000 };
printf(“%d”, e. Id);
printf(“%s”, e. Name);
}
O/P- garbage value, ABC
10. Explain array with structure with example
Structure is collection of different data type. An object of structure represents a singlerecord in memory, if we want more than one record of structure type, we have tocreate an array of structure or object. As we know, an array is a collection of similartype, therefore an array can be of structure type.
Syntax for declaring structure array
Struct struct-name
{
Datatype var1;
Datatype var2;
- - - - - - - - - -
- - - - - - - - - -
Datatype varN;
};
Struct struct-name obj [ size ];
Example for declaring structure array
#include<stdio.h>
Struct Employee
{
Int Id;
Char Name[25];
Int Age;
Long Salary;
};
Void main()
{
Int i;
Struct Employee Emp[ 3 ]; //Statement 1
For(i=0;i<3;i++)
{
Printf("\nEnter details of %d Employee",i+1);
Printf("\n\tEnter Employee Id : ");
Scanf("%d",&Emp[i].Id);
Printf("\n\tEnter Employee Name : ");
Scanf("%s",&Emp[i].Name);
Printf("\n\tEnter Employee Age : ");
Scanf("%d",&Emp[i].Age);
Printf("\n\tEnter Employee Salary : ");
Scanf("%ld",&Emp[i].Salary);
}
Printf("\nDetails of Employees");
For(i=0;i<3;i++)
Printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :
Enter details of 1 Employee
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
Enter details of 3 Employee
Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
In the above example, we are getting and displaying the data of 3 employee using
Array of object. Statement 1 is creating an array of Employee Emp to store the records
Of 3 employees.