Introduction To C-Module 4 and 5 Notes
Introduction To C-Module 4 and 5 Notes
Strings
String variable:
A string is an array of characters. Any group of characters defined between double quotation
marks is called a constant string. String in C programming is a sequence of characters
terminated with a null character „\0‟. Strings are defined as an array of characters. The
difference between a character array and a string is the string is terminated with a unique
character „\0‟.
Example:
“Good Morning Everybody”
Character strings are often used to build meaningful and readable programs. A string variable
is any valid C variable name and is always declared as an array.
Writing strings:
The printf function with %s can be used to display an array of characters that is
terminated by the null character.
Example:
printf(“%s”, text);
Can be used to display the entire contents of the array name.
String functions:
C library supports a large number of string functions. The list given below depicts the
string functions
Function Action
strcat( ) concatenates two strings
strcmp( ) compares two strings
strcpy( ) copies one string with another
The strcat function joins two strings together. The general form is
strcat(string1,string2);
string1 and string2 are character arrays. When the function strcat is executed. String2 is
appended to string1. It does so by removing the null character at the end of string1 and placing
string2 from there. The string at string2 remains unchanged.
Example
#include<string.h>
int main()
{
char src[20]= “ before”;
char dest[20]= “after ”;
strcat(dest, src);
puts(dest);
return 0;
}
The output will be: after before
The strcmp function compares two strings identified by the arguments and has a value 0
if they are equal.
The general form is :
strcmp(string1,string2);
String1 and string2 may be string variables or string constants.
On comparing the return value be determined basis the strings setup as shown below.
The function returns a definite value that may be either 0, >0, or <0. In this function, the two
values passed are treated as case sensitive means „A‟ and „a‟ are treated as different letters.
The values returned by the function are used as:
i) 0 is returned when two strings are the same
ii) If str1<str2 then a negative value is returned
iii) If str1>str2 then a positive value is returned
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]=”copy”;
Function strrev()
If you want to reverse any string without writing any huge or extensive program manually,
then you can use this function. The rev in the strrev() stands for reverse and it is used to
reverse the given string. Function strrev() is used to reverse the content of the string. Strrev
function is used to check the nature of the string, whether the given string is a palindrome or
not. Several other uses and applications are also present in the string reverse function. One of
its uses is given below:
#include<stdio.h>
#include<string.h>
int main()
{
char temp[20]=”Reverse”;
printf(“String before reversing is : %s\n”, temp);
printf(“String after strrev() :%s”, strrev(temp));
return 0;
}
Output
Enter a character=A
You typed an alphabet
6. isupper()
8. toupper()
This function converts lowercase alphabet into uppercase alphabet.
9. tolower()
This function converts an uppercase alphabet into lowercase alphabet.
Program to use of islower,isupper,tolower(),toupper().
#include<ctype.h>
#include<stdio.h>
int main()
{
char n;
printf("\nEnter an alphabet=");
n=getche();
if(islower(n))
n=toupper(ch);
else
ch=tolower(ch);
printf("\nNow alphabet=%c",n);
return(0);
}
Output
Enter an alphabet=A
Now alphabet=a
Pointers:
Pointers in C are easy and fun to learn. Some C programming tasks are performed more
easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed
without using pointers. As we know, every variable is a memory location and every memory
location has its address defined which can be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following example, which will print the address of
the variables defined:
#include <stdio.h>
int main ()
{
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Basics of pointers:
A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location. In other words, a pointer is a variable that represent the location (rather
than the value) of a data item, such as a variable or an array element. It is a variable that holds a
memory address. This address is the location of another variable or an array element in memory.
For example, if one variable contains the address of another variable, the first variable is said to
point to the second.
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of
the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Following are the valid pointer declaration:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
In the above example, ptr is the name of our variable. The „*‟ informs the compiler that we want
a pointer variable. i.e. to set aside number of bytes required to store an address in memory. The
Types of Pointer:
There are majorly four types of pointers, they are:
Null Pointer
Void Pointer
Wild Pointer
Dangling Pointer
Null Pointer:
A pointer can also be initialized by assigning a NULL value. It is always a good practice
to assign a NULL value to a pointer variable in case we do not have exact address to be assigned.
This is done at the time of variable declaration. A pointer that is assigned NULL is called
a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program:
#include <stdio.h>
int main ()
{
return 0;
}
When the above code is compiled and executed, it produces the following result:
Void Pointer:
When a pointer is declared with a void keyword, then it is called a void pointer. To print the
value of this pointer, you need to typecast it.
Syntax:
void *var;
Example:
#include<stdio.h>
int main()
{
int a=2;
void *ptr;
ptr= &a;
printf("After Typecasting, a = %d", *(int *)ptr);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Wild Pointer:
A wild pointer is only declared but not assigned an address of any variable. They are very tricky,
and they may cause segmentation errors.
Example:
#include<stdio.h>
When the above code is compiled and executed, it produces the following result:
Dangling Pointer
Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this
memory, then this p is called a dangling pointer.
You can deallocate a memory using a free() function.
Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int *)malloc(sizeof(int));
int a=5;
ptr=&a;
free(ptr);
//now this ptr is known as dangling pointer.
printf(“After deallocating its memory *ptr=%d”,*ptr);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Scansets in C
scanf family functions support scanset specifiers which are represented by %[]. Inside scanset,
we can specify single character or range of characters. While processing scanset, scanf will
process only those characters which are part of scanset. We can define scanset by putting
characters inside square brackets. Please note that the scansets are case-sensitive.
We can also use scanset by providing comma in between the character you want to add.
example: scanf(%s[A-Z,_,a,b,c]s,str);
This will scan all the specified character in the scanset.
Let us see with example. Below example will store only capital letters to character array 'str',
any other character will not be stored inside character array.
int main(void)
{
char str[128];
return 0;
}
Output:
Enter a string: GEEKs_for_geeks
You entered: GEEK
If first character of scanset is '^', then the specifier will stop reading after first occurrence of
that character. For example, given below scanset will read all characters but stops after first
occurrence of 'o'.
scanf("%[^o]s", str);
Let us see another example:
/* Another scanset example with ^ */
#include <stdio.h>
int main(void)
{
char str[128];
return 0;
}
Output:
Enter a string: http://geeks for geeks
You entered: http://geeks f
Review Questions
1. What is string? How is it declared and initialized? (5 Marks)
2. Explain the functions used to read strings with examples. (5 Marks)
3. Explain the functions used to display string on screen with examples. (5 Marks)
4. List the most used string handling functions and explain their usage. (8 Marks)
5. Explain the character functions in C with examples. (8 Marks)
6. Write a C program to check the given string is palindrome or not. (6 Marks)
7. Write a C program to count the number of vowels and consonants in a given string. (imp)
8. What is pointer? What is its purpose? (4 Marks)
9. How is pointer variable declared in C? (4 Marks)
10. Explain the process of initialization of pointer variable. (4 Marks)
11. Write a short note on operations on pointers. (4 Marks)
12. What do you mean pointer to pointer? Explain. (4 Marks)
13. Write a note on arrays and pointers. (4 Marks)
14. Write a C program to find sum, mean and standard deviation of array elements using
pointer. (8 Marks)
15. Explain scanset in C language.
Structure in C
C arrays allow us to define type of variables that can hold several data items of the same kind
but structure is another user defined data type available in C programming, which allows us
to combine data items of different kinds.
Defining a Structure:
Structure is the collection of variables of different types under a single name for better handling.
For example: we want to store the information about person about his/her name, citizenship
number and salary. We can create these information separately but, better approach will be
collection of these information under single name because all these information are related to
person.
In C, a structure is a derived data type consisting of a collection of member elements and their
data types. Thus, a variable of a structure type is the name of a group of one or more members
which may or may not be of the same data type. In programming terminology, a structure data
type is referred to as a record data type and the members are called fields.
Keyword struct is used for creating a structure.
Syntax of structure:
struct structure_name
{
data_type member1;
data_type member2;
….
data_type memeber;
};
We can create the structure for a person as mentioned above as:
struct person
{
char name[50];
int cit_no;
float salary;
};
This declaration above creates the derived data type struct person.
Structure variable declaration:
When a structure is defined, it creates a user -defined type but, no storage is allocated.
For the above structure of person, variable can be declared as:
struct person
{
char name[50];
int cit_no;
float salary;
};
Inside main function:
struct person p1, p2, p[20];
Another way of creating sturcture variable is:
struct person
{
char name[50];
int cit_no;
float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct
person are created.
Accessing members of a structure
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->)
Any member of a structure can be accessed as: structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:
p2.salary
Example of structure
Write a C program to add two complex numbers using structure.
#include <stdio.h>
struct complex {
float real;
float imag;
};
void main()
{
struct complex n1,n2,sum;
printf("For 1st complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);
sum.real=n1.real+n2.real;
sum.imag=n1.imag+n2.imag;
printf("Sum = %.1f + %.1fi", sum.real, sum.imag);
}
std1 = { "Pritesh",67,78.3 }
std1 = {"Pritesh",67,78.3};
std2 = {"Don",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 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
integer 0
float 0.00
char NULL
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;
};
Array of Structures:
When we are working with a group of entities and their attributes, we need to create array
of structures. C Structure is collection of different data types (variables) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This is also called as
structure array in C.
For example, if we want to work with students data base we can create a structure student, in
which we can store the information about the address, age, marks obtained by ther student and so
on. By creating an array of structure student we can store information of group of students. Then
by accessing aray of structure student we can quickly and easily work with student‟s
information.
Student A[0]
Student A[1]
Student A[39]
Structure is used to store the information of One particular object but if we need to store such
100 objects then Array of Structure is used.
Example :
struct Bookinfo
{
char bname[20];
int pages;
int price;
}Book[100];
Explanation :
1. Here Book structure is used to Store the information of one Book.
2. In case if we need to store the Information of 100 books then Array of Structure is used.
3. b1[0] stores the Information of 1st Book , b1[1] stores the information of 2nd Book and So
on We can store the information of 100 books.
Accessing Pages field of Second Book :
Book[1].pages