PPS
Unit 5Strings & Structure Q1) What are strings? In C programming, a string is a sequence of characters terminated with a null character \0. For example:char c[] = "c string";When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.Memory diagram of strings in C programmingTo declare strings:char s[5];
You can initialize strings in the following ways: char c[] = "abcd"; char c[50] = "abcd"; char c[] = {'a', 'b', 'c', 'd', '\0'}; char c[5] = {'a', 'b', 'c', 'd', '\0'};Q2) Write a program to read a string? #include <stdio.h>int main(){ char name[20]; printf("Enter name: "); scanf("%s", name); printf("Your name is %s.", name); return 0;}OutputEnter name: Dennis RitchieYour name is Dennis. Q3) Explain pointers and strings? In the following example we are creating a string str using char character array of size 6.char str[6] = "Hello";The above string can be represented in memory as follows.
Creating a pointer for the stringThe variable name of the string str holds the address of the first element of the array i.e., it points at the starting memory address.So, we can create a character pointer ptr and store the address of the string str variable in it. This way, ptr will point at the string str.In the following code we are assigning the address of the string str to the pointer ptr.char *ptr = str;
The pointer variable ptr is allocated memory address 8000 and it holds the address of the string variable str i.e., 1000.Accessing string via pointerTo access and print the elements of the string we can use a loop and check for the \0 null character. Q4) Explain the following string functions?i) Strlen ii) strcpy() iiii) strcmp() iv) strcat() v) strcmp() strlen():strlen() function gives the length of the given string. Syntax:Strlen() size_t_strlen(const char* str)strlen() function counts the number of characters in a given string and returns integer value.It stops counting the character when null character is found. Because, null character indicates the end of the string in C. strcpy():The syntax of the strcpy() function is:Syntax: char* strcpy (char* destination, const char* source);The strcpy() function is used to copy strings. It copies string pointed to by source into the destination. This function accepts two arguments of type pointer to char or array of characters and returns a pointer to the first string i.e destination. Notice that source is preceded by the const modifier because strcpy() function is not allowed to change the source string. strcat():In C programming, the strcat() function contcatenates (joins) two strings.The function definition of strcat() is:char *strcat(char *destination, const char *source)It is defined in the string.h header file.strcat() argumentsthe strcat() function takes two arguments:destination - destination stringsource - source stringThe strcat() function concatenates the destination string and the source string, and the result is stored in the destination string. strcmp():The C library function int strcmp(const char *str1, const char *str2) compares the string pointed to, by str1 to the string pointed to by str2.DeclarationFollowing is the declaration for strcmp() function.int strcmp(const char *str1, const char *str2)Parameters str1 − This is the first string to be compared. str2 − This is the second string to be compared. Return ValueThis function return values that are as follows − if Return value < 0 then it indicates str1 is less than str2. if Return value > 0 then it indicates str2 is less than str1. if Return value = 0 then it indicates str1 is equal to str2. Q5) Write a program to compare string? #include <stdio.h>#include <string.h>int main () { char str1[15]; char str2[15]; int ret; strcpy(str1, "abcdef"); strcpy(str2, "ABCDEF"); ret = strcmp(str1, str2); if(ret < 0) { printf("str1 is less than str2"); } else if(ret > 0) { printf("str2 is less than str1"); } else { printf("str1 is equal to str2"); } return(0);}Let us compile and run the above program that will produce the following result −str2 is less than str1 Q6) Explain array of pointers? An array of pointers to strings is an array of character pointers where each pointer points to the first character of the string or the base address of the string.To declare and initialize an array of pointers to strings.char *sports[5] = { "golf", "hockey", "football", "cricket", "shooting" };Here sports is an array of pointers to strings. If initialization of an array is done at the time of declaration, then we can omit the size of an array. So, the above statement can also be written as:char *sports[] = { "golf", "hockey", "football", "cricket", "shooting" };It is important to note that each element of the sports array is a string literal and since a string literal points to the base address of the first character, the base type of each element of the sports array is a pointer to char or (char*).The 0th element i.e arr[0] points to the base address of string "golf". Similarly, the 1st element i.e arr[1] points to the base address of string "hockey" and so on.Here is how an array of pointers to string is stored in memory.
Q7) What is structure ? Why do we use structures? 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. Explain structure initialization? 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 variablein different ways –Way 1 : Declare and Initializestruct 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 wehave initialized the structure variable.std1 = { "Poonam",89,78.3 }This is the code for initializing structure variable in C programmingWay 2 : Declaring and Initializing Multiple Variablesstruct 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 memberstruct student{int mark1;int mark2;int mark3;} sub1={67};Though there are three members of structure,only one is initialized , Then remaining two membersare initialized with Zero. Q8) How we access structure elements? Array elements are accessed using the Subscript variable , Similarly Structure members are accessed using dot [.] operator. (.) is called as “Structure member Operator”. Use this Operator in between “Structure variable” & “member name” struct employee { int id; char name[50]; float salary; } ; void main() { struct employee e= { 1, “ABC”, 50000 }; printf(“%d”, e. id); printf(“%s”, e. name); printf(“%f”, e. salary); } Q9) Explain how structure elements are stored? Members of a structure are always stored in consecutive memory locations but the memory occupied by each member may vary. Consider the following program:#include<stdio.h> struct book{ char title[5]; int year; double price;}; int main(){ struct book b1 = {"Book1", 1988, 4.51}; printf("Address of title = %u\n", b1.title); printf("Address of year = %u\n", &b1.year); printf("Address of price = %u\n", &b1.price); printf("Size of b1 = %d\n", sizeof(b1)); // signal to operating system program ran fine return 0;} Expected Output:
Q10) Explain array of structures? Structure is collection of different data type. An object of structure represents a single record in memory, if we want more than one record of structure type, we have to create an array of structure or object. As we know, an array is a collection of similar type, therefore an array can be of structure type.Syntax for declaring structure arraystruct struct-name{datatype var1;datatype var2;- - - - - - - - - -- - - - - - - - - -datatype varN;};struct struct-name obj [ size ];
1 2 3 4 | Address of title = 2686728 Address of year = 2686736 Address of price = 2686744 Size of b1 = 24
|
Unit 5Strings & Structure Q1) What are strings? In C programming, a string is a sequence of characters terminated with a null character \0. For example:char c[] = "c string";When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.Memory diagram of strings in C programmingTo declare strings:char s[5];
You can initialize strings in the following ways: char c[] = "abcd"; char c[50] = "abcd"; char c[] = {'a', 'b', 'c', 'd', '\0'}; char c[5] = {'a', 'b', 'c', 'd', '\0'};Q2) Write a program to read a string? #include <stdio.h>int main(){ char name[20]; printf("Enter name: "); scanf("%s", name); printf("Your name is %s.", name); return 0;}OutputEnter name: Dennis RitchieYour name is Dennis. Q3) Explain pointers and strings? In the following example we are creating a string str using char character array of size 6.char str[6] = "Hello";The above string can be represented in memory as follows.
Creating a pointer for the stringThe variable name of the string str holds the address of the first element of the array i.e., it points at the starting memory address.So, we can create a character pointer ptr and store the address of the string str variable in it. This way, ptr will point at the string str.In the following code we are assigning the address of the string str to the pointer ptr.char *ptr = str;
The pointer variable ptr is allocated memory address 8000 and it holds the address of the string variable str i.e., 1000.Accessing string via pointerTo access and print the elements of the string we can use a loop and check for the \0 null character. Q4) Explain the following string functions?i) Strlen ii) strcpy() iiii) strcmp() iv) strcat() v) strcmp() strlen():strlen() function gives the length of the given string. Syntax:Strlen() size_t_strlen(const char* str)strlen() function counts the number of characters in a given string and returns integer value.It stops counting the character when null character is found. Because, null character indicates the end of the string in C. strcpy():The syntax of the strcpy() function is:Syntax: char* strcpy (char* destination, const char* source);The strcpy() function is used to copy strings. It copies string pointed to by source into the destination. This function accepts two arguments of type pointer to char or array of characters and returns a pointer to the first string i.e destination. Notice that source is preceded by the const modifier because strcpy() function is not allowed to change the source string. strcat():In C programming, the strcat() function contcatenates (joins) two strings.The function definition of strcat() is:char *strcat(char *destination, const char *source)It is defined in the string.h header file.strcat() argumentsthe strcat() function takes two arguments:destination - destination stringsource - source stringThe strcat() function concatenates the destination string and the source string, and the result is stored in the destination string. strcmp():The C library function int strcmp(const char *str1, const char *str2) compares the string pointed to, by str1 to the string pointed to by str2.DeclarationFollowing is the declaration for strcmp() function.int strcmp(const char *str1, const char *str2)Parameters str1 − This is the first string to be compared. str2 − This is the second string to be compared. Return ValueThis function return values that are as follows − if Return value < 0 then it indicates str1 is less than str2. if Return value > 0 then it indicates str2 is less than str1. if Return value = 0 then it indicates str1 is equal to str2. Q5) Write a program to compare string? #include <stdio.h>#include <string.h>int main () { char str1[15]; char str2[15]; int ret; strcpy(str1, "abcdef"); strcpy(str2, "ABCDEF"); ret = strcmp(str1, str2); if(ret < 0) { printf("str1 is less than str2"); } else if(ret > 0) { printf("str2 is less than str1"); } else { printf("str1 is equal to str2"); } return(0);}Let us compile and run the above program that will produce the following result −str2 is less than str1 Q6) Explain array of pointers? An array of pointers to strings is an array of character pointers where each pointer points to the first character of the string or the base address of the string.To declare and initialize an array of pointers to strings.char *sports[5] = { "golf", "hockey", "football", "cricket", "shooting" };Here sports is an array of pointers to strings. If initialization of an array is done at the time of declaration, then we can omit the size of an array. So, the above statement can also be written as:char *sports[] = { "golf", "hockey", "football", "cricket", "shooting" };It is important to note that each element of the sports array is a string literal and since a string literal points to the base address of the first character, the base type of each element of the sports array is a pointer to char or (char*).The 0th element i.e arr[0] points to the base address of string "golf". Similarly, the 1st element i.e arr[1] points to the base address of string "hockey" and so on.Here is how an array of pointers to string is stored in memory.
Q7) What is structure ? Why do we use structures? 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. Explain structure initialization? 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 variablein different ways –Way 1 : Declare and Initializestruct 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 wehave initialized the structure variable.std1 = { "Poonam",89,78.3 }This is the code for initializing structure variable in C programmingWay 2 : Declaring and Initializing Multiple Variablesstruct 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 memberstruct student{int mark1;int mark2;int mark3;} sub1={67};Though there are three members of structure,only one is initialized , Then remaining two membersare initialized with Zero. Q8) How we access structure elements? Array elements are accessed using the Subscript variable , Similarly Structure members are accessed using dot [.] operator. (.) is called as “Structure member Operator”. Use this Operator in between “Structure variable” & “member name” struct employee { int id; char name[50]; float salary; } ; void main() { struct employee e= { 1, “ABC”, 50000 }; printf(“%d”, e. id); printf(“%s”, e. name); printf(“%f”, e. salary); } Q9) Explain how structure elements are stored? Members of a structure are always stored in consecutive memory locations but the memory occupied by each member may vary. Consider the following program:#include<stdio.h> struct book{ char title[5]; int year; double price;}; int main(){ struct book b1 = {"Book1", 1988, 4.51}; printf("Address of title = %u\n", b1.title); printf("Address of year = %u\n", &b1.year); printf("Address of price = %u\n", &b1.price); printf("Size of b1 = %d\n", sizeof(b1)); // signal to operating system program ran fine return 0;} Expected Output:
Q10) Explain array of structures? Structure is collection of different data type. An object of structure represents a single record in memory, if we want more than one record of structure type, we have to create an array of structure or object. As we know, an array is a collection of similar type, therefore an array can be of structure type.Syntax for declaring structure arraystruct struct-name{datatype var1;datatype var2;- - - - - - - - - -- - - - - - - - - -datatype varN;};struct struct-name obj [ size ];
1 2 3 4 | Address of title = 2686728 Address of year = 2686736 Address of price = 2686744 Size of b1 = 24
|
0 matching results found