C Programming

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Module 5

MODULE 5

STRING TAXONOMY

Fixed – length Strings

When storing fixed – length strings we need to specify an appropriate size for the string
variable. If the size is too small, then we will not able to store all the elements in the string. If
the string size is large, then unnecessarily memory space will be wasted.

Variable – length Strings

To use a variable length string format we need a technique to indicate the end of
elements that are a part of the string. This can be done either by using length controlled string
or a delimiter.

Length – controlled Strings

Here, we need to specify the number of characters in the string. This count is used by
string manipulation functions to determine the actual length of the string variable.

Delimited Strings

In this format, the string is ended with a delimiter. The delimiter is then used to identify
the end of the string.

OPERATIONS ON STRINGS

FINDING THE LENGTH OF A STRING

The number of characters in the string is the length of the string. Even blank spaces will
be counted. The size of string “ C PROGRAMMING IS FUN “ is 20.

Prof. Praneetha G N, Dept of ISE, SCE 1


Module 5

Write a program to find the length of a string

#include<stdio.h>
void main()
{
char str[100];
int i , length;
clrscr();
printf(“enter the string : ”);
gets(str);
while( str[i] ! = ‘\0’ )
i++;
length = i;
printf(“length of string is “ %d”, length);
}
Output
enter the string : hello
length of string is 5

CONVERTING CHARACTERS OF A STRING INTO UPPERCASE

The ASCII code for A – Z varies from 65 to 91 and for a –z is from 97 to 123. So to
convert a lower case character to upper case, we just need to subtract 32 from ASCII value of
the character.

Write a program to convert characters of a string to uppercase.

#include<stdio.h>
void main()
{
char str[100], upper_str[100];
int i=0,j=0;
printf("enter the string");
gets(str);
while( str[i]!='\0' )
{

Prof. Praneetha G N, Dept of ISE, SCE 2


Module 5

if(str[i]>='a' && str[i]<='z')


upper_str[j] = str[i] - 32;
else
upper_str[j] = str[i];
i++;
j++;
}
str[i]= '\0';
printf("\n Sting converted into upper case is");
puts(upper_str);
}
Output:
enter the string: Hello
Sting converted into upper case is: HELLO

CONVERTING CHARACTERS OF A STRING INTO LOWERCASE

To convert a upper case character to lower case, we just need to add 32 from ASCII value of
the character.

Write a program to convert characters of a string to lowercase.

#include<stdio.h>
void main()
{
char str[100], lower_str[100];
int i=0,j=0;
printf("enter the string: ");
gets(str);
while( str[i]!='\0' )
{
if(str[i]>='A' && str[i]<='Z')
lower_str[j] = str[i] + 32;
else
lower_str[j] = str[i];

Prof. Praneetha G N, Dept of ISE, SCE 3


Module 5

i++;
j++;
}
str[i]= '\0';
printf("\n Sting converted into upper case is: ");
puts(lower_str);
}
Output:
enter the string: HAI
Sting converted into upper case is: hai

CONCATENATING TWO STRINGS TO FORM A NEW STRING


If s1 and s2 are two strings, then concatenation operation produces a string which
contains characters of s1 followed by the character of s2.
Write a program to concatenate two strings
#include<stdio.h>
void main()
{
char str1[100], str2[100], str3[100];
int i=0,j=0;
printf("enter the first string: ");
gets(str1);
printf("enter the second string: ");
gets(str2);
while( str1[i]!='\0' )
{
str3[j] = str1[i];
i++;
j++;
}
i=0;
while( str2[i]!='\0' )
{
str3[j] = str2[i];

Prof. Praneetha G N, Dept of ISE, SCE 4


Module 5

i++;
j++;
}
str3[j]= '\0';
printf("\n Concatenated string is: ");
puts(str3);
}
Output:
enter the first string: hai
enter the second string: hello
Concatenated string is: haihello

APPENDING A STRING TO ANOTHER


Appending one string to another involves copying the contents of the source string at
the end of the destination string.
Write a program to append a string to another string
#include<stdio.h>
void main()
{
char dest_str[100], source_str[100];
int i=0,j=0;
printf("enter the source string: ");
gets(source_str);
printf("enter the destination string: ");
gets(dest_str);
while( dest_str[i]!='\0' )
i++;
while( source_str[j]!='\0' )
{
dest_str[i] = source_str[j];
i++;
j++;
}

Prof. Praneetha G N, Dept of ISE, SCE 5


Module 5

dest_str[i]= '\0';
printf("\n After appending , the destination string is: ");
puts(dest_str);
}

Output:
enter the source string: hello
enter the destination string: hai
After appending , the destination string is: haihello

COMPARING TWO STRINGS

If S1 and S2 are two strings then comparing two strings will give either of these results:

 S1 and S2 are equal


 S1 > S2, i.e., when in dictionary order S1 will come after S2
 S1 < S2 i.e., when in dictionary order S1 precedes S2

Write a c program to compare two strings.


#include<stdio.h>
int main()
{
char str1[30], str2[30];
int i;
printf("\nEnter string1:");
gets(str1);
printf("\nEnter string2:");
gets(str2);
i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("str1 is greater than str2");
else if (str1[i] < str2[i])
printf("str1 is lesser than str2");

Prof. Praneetha G N, Dept of ISE, SCE 6


Module 5

else
printf("str1 is equal to str2");
return (0);
}
Output
Enter string1:hai

Enter string2:hello

str1 is lesser than str2

REVERSING A STRING

To reverse a string we just need to swap the first character with the last, second
character with the last second character and so on.

Write a program to reverse a string

#include<stdio.h>

#include<string.h>

void main()
{
char str[30], reverse_str[30],temp;
int i=0, j=0;
printf("\nEnter string:");
gets(str);
j=strlen(str)-1;
while(i<j)
{
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
}

Prof. Praneetha G N, Dept of ISE, SCE 7


Module 5

printf("the reversed string is ");


puts(str);
}
Output:
Enter string:sapthagiri
the reversed string is irigahtpas

EXTRACTING A SUBSTRING FROM LEFT


In order to extract a substring from the main string, the content of the string starting
from the first position to the nth position is copied where n is the number of characters to be
extracted.
Write a program to extract the first n characters of a string.
#include<stdio.h>
void main()
{
char str[30], substr[30];
int i=0,n;
printf("\nEnter string:");
gets(str);
printf("enter the number of characters to be copied:");
scanf("%d",&n);
i=0;
while(str[i]!= '\0' && i<n)
{
substr[i]=str[i];
i++;
}
substr[i]='\0';
printf("the substring is: ");
puts(substr);
}
Output:
Enter string:hi there
enter the number of characters to be copied:2

Prof. Praneetha G N, Dept of ISE, SCE 8


Module 5

the substring is: hi

EXTRACTING A SUBSTRING FROM RIGHT OF THE STRING


In order to extract a substring from right side of the main string, the content of the string
starting from the last position n characters are extracted n is the number of characters to be
extracted.
Write a program to extract the last n characters of a string.
#include<stdio.h>
#include<string.h>
void main()
{
char str[30], substr[30];
int i=0,j=0,n;
printf("\nEnter string:");
gets(str);
printf("enter the number of characters to be copied:");
scanf("%d",&n);
j=strlen(str)-n;

while(str[j]!= '\0')
{
substr[i]=str[j];
i++;
j++;
}
substr[i]='\0';
printf("the substring is: ");
puts(substr);
}
Output:
Enter string:hi there
enter the number of characters to be copied:5
the substring is: there

Prof. Praneetha G N, Dept of ISE, SCE 9


Module 5

EXTRACTING A SUBSTRING FROM MIDDLE OF THE STRING


In order to extract a substring from the main string 3 things are required. The main
string, position of the first character of the substring in the given string and the length of the
substring.
For example: str[]= “Welcome to the world of programming”;
Then SUBSTRING(str,15,5)= World
Write a c program to extract a substring from a given string
#include<stdio.h>
void main()
{
char str[30], substr[30];
int i=0,j=0,n,m;
printf("\nEnter string:");
gets(str);
printf("enter the position from where substring should start:");
scanf("%d",&m);
printf("enter the length of substring:");
scanf("%d",&n);
i=m;
while(str[i]!= '\0' && n>0)
{
substr[j]=str[i];
i++;
j++;
n--;
}
substr[j]='\0';
printf("the substring is: ");
puts(substr);
}

Output:
Enter string:Hi there
enter the position from where substring should start:1

Prof. Praneetha G N, Dept of ISE, SCE 10


Module 5

enter the length of substring:7


the substring is: i there

INSERTING A STRING IN ANOTHER STRING


The insertion operation insets a string S in the main text at some position. General
Syntax is INSERT(text, position, string)
Ex: INSERT(“XYZXYZ”,3,”AAA) = XYZAAAXYZ
Write a c program to insert a string in the main text
#include<stdio.h>
void main()
{
char text[100],str[30], ins_text[30];
int i=0,j=0,k=0,pos;
printf("\nEnter main text:");
gets(text);
printf("enter the string to be inserted:");
gets(str);
printf("enter the position at which string has to be inserted:");
scanf("%d",&pos);
while(text[i]!= '\0' )
{
if(i==pos)
{
while(str[k]!= '\0')
{
ins_text[j]=str[k];
j++;
k++;
}
}
else
{
ins_text[j]=text[i];
j++;

Prof. Praneetha G N, Dept of ISE, SCE 11


Module 5

i++;
}
ins_text[j]='\0';
printf("the new string is: ");
puts(ins_text);
}
Output:
nter main text:How you?
enter the string to be inserted:are
enter the position at which string has to be inserted:3
the new string is: Howareyou?

INDEXING
Index operation return the position in the string where the string pattern first occurs.
For example:
INDEX(“Welcome to the world of programming”, “world”) = 15
If the pattern is not found it returns 0.
DELETING A STRING FROM THE MAIN STRING
The deletion operation deletes a substring from a given text.
DELETE(text, position, length)
DELETE(“ABCDXXXABCD”,4,3) = “ABCDABCD”

Write a c program to delete a substring from a text


#include<stdio.h>
void main()
{
char text[100],str[30], new_text[30];
int i=0,j=0,k,n=0,copy_loop=0;
printf("\nEnter main text:");
gets(text);
printf("enter the string to be deleted:");
gets(str);
while(text[i]!= '\0' )

Prof. Praneetha G N, Dept of ISE, SCE 12


Module 5

{
j=0;k=i;
while(text[k]==str[j] && str[j]!='\0')
{
k++;
j++;
}
if(str[j]== '\0')
copy_loop=k;
new_text[n]=text[copy_loop];
i++;
copy_loop++;
n++;
}
new_text[n]='\0';
printf("the new string is:");
puts(new_text);
}
Output:
Enter main text:Hai, how are you?
enter the string to be deleted:, how are you?
the new string is:Hai

REPALCING A PATTERN WITH ANOTHER PATTERN IN A STRING


Replacement operation is used to replace the pattern p1 by another pattern p2.
REPLACE(“AAABBBCCC”, “BBB”, “x”) = AAAXCCC

Write a c program to replace a pattern with another pattern in the text.


#include<stdio.h>
void main()
{
char str[30],pat[30], new_str[30],rep_pat[30];
int i=0,j=0,k,n=0,copy_loop=0,rep_index=0;
printf("\nEnter the string:");

Prof. Praneetha G N, Dept of ISE, SCE 13


Module 5

gets(str);
printf("enter the pattern to be replaced:");
gets(pat);
printf("enter the replacing pattern:");
gets(rep_pat);
while(str[i]!= '\0' )
{
j=0;k=i;
while(str[k]==pat[j] && pat[j]!='\0')
{
k++;
j++;
}
if(pat[j]== '\0')
{
copy_loop=k;
while(rep_pat[rep_index]!='\0')
{
new_str[n]= rep_pat[rep_index];
rep_index++;
n++;
}
}

new_str[n]=str[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("the new string is:");
puts(new_str);
}
Output

Prof. Praneetha G N, Dept of ISE, SCE 14


Module 5

Enter the string:How are you?


enter the pattern to be replaced:are
enter the replacing pattern:ARE
the new string is:How ARE you?

MISCELLANEOOUS STRING AND CHARACTER FUNCTIONS


CHARACTER MANIPULATION FUNCTIONS
Function Usage Example
isalnum(int c) Checks whether character c is an isalpha(‘A’);
alphanumeric character
isalpha(int c) Checks whether character c is an isalpha(‘z’);
alphabetic character
isdigit(int c) Checks whether character c is digit isdigit(3);
isgraph(int c) Checks whether character c is graphic isgraph(‘!’);
character
isprint(char c) Checks whether character c is printable isprint(‘!’);
character
islower(char c) Checks whether character c is lowercase islower(‘K’);
character
isupper(char c) Checks whether character c is uppercase isupper (‘a’);
character
ispunc(char c) Checks whether character c is a ispunc(‘?’);
punctuation character
isspace(char c) Checks whether character c is a white isspace(‘ ‘);
sapce character
tolower(char c) Converts the character c to lower case tolower(‘K’)
toupper(char c) Converts the character c to upper case tolower(‘a’)

STRING MANIPULATION FUNCTIONS


Strcat Function
Syntax: char *strcat(char *str1, const char *str2);

Prof. Praneetha G N, Dept of ISE, SCE 15


Module 5

This function appends the string pointed to by str2 to the end of the string pointed to by str1.
The terminating null character of str1 is overwritten. The process stops when the terminating
null character of str2 is copied.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Programming";
char str2[]= "In C";
strcat(str1,str2);
printf("\n str1: %s",str1);
}
Output:
str1: ProgrammingIn C
strncat Function
Syntax: char *strncat(char *str1, const char *str2, size_t n);
This function appends the string pointed to by str2 to the end of the string pointed to by str1
upto n characters long. The terminating null character of str1 is overwritten. The process stops
when the n characters are copied or null character of str2 is copied.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Programming";
char str2[]= "In C";
strncat(str1,str2,2);
printf("\n str1: %s",str1);
}
Output:
str1: ProgrammingIn
strchr Function
Syntax: char *strchr(const char *str, int c);

Prof. Praneetha G N, Dept of ISE, SCE 16


Module 5

This function searches for the first occurrence of the character in the string pointed to by the
argument str. It returns a pointer pointing to the first matching character or NULL if no match
is found.
#include<stdio.h>
#include<string.h>
void main()
{
char str[50]="Programming In C";
char *pos;
pos=strchr(str,'n');
if(pos)
printf("\n string after n is %s",pos);
else
printf("\n char not found in the string");
}
Output:
string after n is ng In C
strrchr Function
Syntax: char *strrchr(const char *str, int c);
This function searches for the first occurrence of the character in the string beginning at the
rear end and working towards the front. It returns a pointer pointing to the last matching
character or NULL if no match is found.
#include<stdio.h>
#include<string.h>
void main()
{
char str[50]="Programming In C Lab";
char *pos;
pos=strrchr(str,'n');
if(pos)
printf("\n string after last position of n %s",pos);
else
printf("\n char not found in the string");
}

Prof. Praneetha G N, Dept of ISE, SCE 17


Module 5

Output
string after last position of n n C Lab
strcmp Function
Syntax: int *strcmp(const char *str1, const char *str2);
This function compares the string pointed to by str1 to the string pointed by str2. The function
returns zero if the strings are equal, less than zero if str1 is less than str2, greater than zero if
str1 is greater than str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Hello";
char str2[50]="Bye";
int n;
n=strcmp(str1,str2);
if(n==0)
printf("\n Strings are identical");
else if(n>0)
printf("\n string 1 is greater than str2");
else
printf("\n string 1 is lesser than str2");

}
Output
string 1 is greater than str2
strncmp Function
Syntax: int *strcmp(const char *str1, const char *str2, size_t n);
This function compares the string at most the first n bytes of str1 and str2. The function returns
zero if the strings are equal, less than zero if str1 is less than str2, greater than zero if str1 is
greater than str2.
#include<stdio.h>
#include<string.h>
void main()
{

Prof. Praneetha G N, Dept of ISE, SCE 18


Module 5

char str1[50]="Hello";
char str2[50]="Hai";
int n;
n=strncmp(str1,str2,1);
if(n==0)
printf("\n Strings are identical");
else if(n>0)
printf("\n string 1 is greater than str2");
else
printf("\n string 1 is lesser than str2");
}
Output
Strings are identical
Strcpy Function
Syntax: char *strcpy(char *str1, const char *str2);
This function copies the string pointed by str2 to str1 including the null character of str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50],str2[50]="Hai";
strcpy(str1,str2);
printf("string 1 is %s",str1);
}
Output:
string 1 is Hai
Strncpy Function
Syntax: char *strncpy(char *str1, const char *str2, size_t n);
This function copies up to n characters from the string pointed by str2 to str1 including the null
character of str2.
#include<stdio.h>
#include<string.h>
void main()
{

Prof. Praneetha G N, Dept of ISE, SCE 19


Module 5

char str1[50],str2[50]="Hello";
strncpy(str1,str2,2);
printf("string 1 is %s",str1);
}
Output:
string 1 is He
strlen Function
Syntax: size_t strlen(const char *str);
This function calculates the length of the string str up to but not including the null character
i.e, it returns the number of characters in the string.
#include<stdio.h>
#include<string.h>
void main()
{
char str[50]="Hello";
printf("length of the string is %d",strlen(str));
}
Output:
length of the string is 5
strcspn Function
Syntax: size_t strcspn(const char *str1, const char *str2);
This function returns the index of the first character in str1 that matches any of the characters
in str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Programming";
char str2[50]="ro";
printf("Position of first character in str1 that matches with that in str2 is
%d",strcspn(str1,str2));
}
Output:
Position of first character in str1 that matches with that in str2 is 1

Prof. Praneetha G N, Dept of ISE, SCE 20


Module 5

strpbrk Function
Syntax: char *strpbrk(const char *str1, const char *str2);
This function returns a pointer to the first occurrence in str1 of any character in str2, or NULL
if none are present. The only difference between strpbrk() and strcspn() is that strcspn() returns
the index of the character and strpbrk() returns a pointer to the first occurrence of a character
in str2.
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Programming in C";
char str2[50]="Program";
char *ptr=strpbrk(str1,str2);
if(ptr==NULL)
printf("No character mathces in two strings");
else
printf("character in str2 matches with that in str1");
}
Output:
character in str2 matches with that in str1
strtok Function
Syntax: char *strtok(const char *str1, const char *delimiter);
This function is used to isolate sequential tokens in a null-terminated string
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]="Hello, to, the, world of, programming";
char result[50];
char delim[]=",";
result=strtok(str1,delim);
while(result!=NULL)
{
printf("\n %s",result);

Prof. Praneetha G N, Dept of ISE, SCE 21


Module 5

result=strtok(NULL,delim);
}
}
Output:
Hello
to
the
world
of
programming
strtol Function
Syntax: long strtol(const char *str, char **end, int base);
This function converts the string pointed by str to a long value. The function skips leading
white space characters and stops when it encounters the first non-numeric character.
#include<stdio.h>
#include<string.h>
void main()
{
long num;
num=strtol("12345 decimal value",NULL,10);
printf("%ld \n",num);
num=strtol("65432 octal value",NULL,8);
printf("%ld \n",num);
num=strtol("10110101 binary value",NULL,2);
printf("%ld \n",num);
num=strtol("A7CB4 hexadecimal value",NULL,16);
printf("%ld \n",num);
}
Output
12345
27418
181
687284
strtod Function

Prof. Praneetha G N, Dept of ISE, SCE 22


Module 5

Syntax: double strtod(const char *str, char **end);


The function accepts a string str that has an optional plus and minus sign followed by either
 A decimal number containing a sequence of decimal digits optionally consisting of a
decimal point or
 A hexadecimal number consisting of a “OX” or “ox” followed by a sequence of
hexadecimal digits optionally containing a decimal point
#include<stdio.h>
#include<string.h>
void main()
{
double num;
num=strtod("123.345abcdefg",NULL);
printf("%lf",num);
}
Output
123.345000
atoi() function
Syntax: int atoi(const char *str);
This function converts a given string passed to it as an argument into a integer.
#include<stdio.h>
#include<string.h>
void main()
{
int num;
num=atoi("123.456");
printf("%d",num);
}
Output
123
atof() function
Syntax: double atof(const char *str);
This function converts a given string passed to it as an argument into a double value.
Example: x=atof(“12.39 is the answer”);

Prof. Praneetha G N, Dept of ISE, SCE 23


Module 5

Result: x=12.39
atol() function
Syntax: long atol(const char *str);
This function converts a given string passed to it as an argument into a long int value.
Example: x=atol(“12345.6789”);
Result: x=12345L

POINTERS

Understanding the Computer’s Memory

Every computer has a primary memory. All data and programs need to be placed in the
primary memory for execution. RAM (Random Access Memory) is a part of primary memory.
It is a collection of memory locations and each location has a specific address. The computer
has 3 areas of memory each of which is used for a specific task. They are stack, heap and global
memory.

Stack

A fixed size of memory called system stack is allocated by the system and is filled as
needed from the bottom to the top, one element at a time. These elements are removed from
the top to the bottom by removing one element at a time i.e., last element added to the stack is
removed first. When a program has used the variables or data stored in the stack, it can be
discarded to enable the stack to be used by other programs to store their data. It is a section of
memory that is allocated for automatic variables within functions.

Heap

It is a contiguous block of memory that is available for use by programs when the need
arises. A fixed size heap is allocated by the system and is used by the system in random fashion.
The addresses of the memory locations in heap that are not currently allocated to any program
for use are stored in a free list. When a program requests a block of memory, the dynamic
allocation technique takes a block from heap and assigns it to the program. When the program
has finished using the block, it returns the memory block to the heap and address are added to
the free list. Compared to heaps, stacks are faster but smaller and expensive.

Global Memory

Prof. Praneetha G N, Dept of ISE, SCE 24


Module 5

The block of code that is the main() program is stored in the global memory. The
memory in the global area is allocated randomly to store the code of different functions in the
program in such a way that one function is not contiguous to another function. All global
variables declared in the program are stored in the global area.

INTRODUCTION TO POINTERS

A Pointer is a variable that contains the memory location of another variable. A pointer
is a variable that represents the location of a data item, such as variable or an array element.
Pointer are useful for the following applications:

 To pass information back and forth between a function and its reference point
 Enable programmers to return multiple data items rom a function via function
arguments.
 Provide an alternate way to access individual elements of the array.
 To pass arrays and strings as function arguments
 Enable references to functions.
 To create complex data structures such as trees, linked lists, linked stacks, linked queues
and graphs.
 For dynamic memory allocations of a variable.

Write a program to find the size of various data types on your system.

#include<stdio.h>
int main()
{
printf("Size of short int: %d \n", sizeof(short int));
printf("Size of unsigned int: %d \n", sizeof(unsigned int));
printf("Size of signed int: %d \n", sizeof(signed int));
printf("Size of int: %d \n", sizeof(int));
printf("Size of long int: %d \n", sizeof(long int));
printf("Size of char: %d \n", sizeof(char));
printf("Size of char: %d \n", sizeof(char));

Prof. Praneetha G N, Dept of ISE, SCE 25


Module 5

printf("Size of unsigned char: %d \n", sizeof(unsigned char));


printf("Size of signed char: %d \n", sizeof(signed char));
printf("Size of floating point number: %d \n", sizeof(float));
printf("Size of double number: %d \n", sizeof(double));
return 0;
}

Ouput
Size of short int: 2
Size of unsigned int: 2
Size of signed int: 2
Size of int: 2
Size of long int: 4
Size of char: 1
Size of char: 1
Size of unsigned char: 1
Size of signed char: 1
Size of floating point number: 4
Size of double number: 8

DECLARING POINTER VARIABLES


A pointer variable provides access to a variable by using the address of that variable.
The general syntax of declaring pointer variables can be given as below:
data_type *ptr_name;
Where data_type is the data type of the value that the pointer will point to.

Example: int *pnum;


char *pch;
pnum and pch point to different data types, they will occupy the same amount of space in
memory.
#include<stdio.h>
int main()
{

Prof. Praneetha G N, Dept of ISE, SCE 26


Module 5

int *pnum;
char *pch;
float *pfnum;
double *pdnum;
long *plnum;
printf("Size of integer pointer: %d \n", sizeof(pnum));
printf("Size of character pointer: %d \n", sizeof(pch));
printf("Size of float pointer: %d \n", sizeof(pfnum));
printf("Size of double pointer: %d \n", sizeof(pdnum));
printf("Size of long pointer: %d \n", sizeof(plnum));
return 0;
}

Output:
Size of integer pointer: 2
Size of character pointer: 2
Size of float pointer: 2
Size of double pointer: 2
Size of long pointer: 2

Consider the following code:


int x=84;
int *ptr;
ptr= &x;

In the above statement, ptr is the name of pointer variable. The ‘*’ informs the compiler that
ptr is a pointer variable and the int specifies that it will store the address of an integer variable.

We can deference a pointer i.e., refer to the value of the variable to which it points, by using
unary * pointer ( also known as indirection operator) as *ptr. %p prints the argument as a
memory address in hexadecimal form.

#include<stdio.h>
int main()

Prof. Praneetha G N, Dept of ISE, SCE 27


Module 5

{
int num, *pnum;
pnum = &num;
printf(“enter the number:”);
scanf(“%d”, &num);
printf(“ \n The number that was entered is: %d”, *pnum);
printf(“ \n The address of number in memory is : %p”, &num);
return 0;
}

Ouput:
Enter the number: 10
The number that was entered is: 10
The address of number in memory is : FFDC

We can also assign values to variables using pointer variables and modify their values. The
code given below shows this.

#include<stdio.h>
int main()
{
int num, *pnum;
pnum = &num;
*pnum=10;
printf(“\n *pnum=%d”,*pnum);
printf(“\n num = %d”, num);
*pnum= *pnum +1;
printf(“\n after increment *pnum=%d”,*pnum);
printf(“\n after increment num = %d”,num);
return 0;
}

Output:
*pnum=10

Prof. Praneetha G N, Dept of ISE, SCE 28


Module 5

num = 10
after increment *pnum=11
after increment num = 11

STRUCTURES
A Structure is a collection of variable under a single name. The variables within a
structure are of different data types and each has a name that is used to select it from the
structure. Structure is a user defined data type.

Structure Declaration
A structure is declared using the keyword struct followed by the structure name. All the
variables of the structure are declared within the structure.
Syntax:
struct structure_name
{
data_type var_name;
data_type var_name;
……
};

Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};

Structure variable can be declared as follows:


struct student stud1;
Here, struct student is a data type and stud1 is a variable.

Prof. Praneetha G N, Dept of ISE, SCE 29


Module 5

Another way of declaring variable is at the time of structure declaration.


struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}stud1, stud2;

Here, we have declared two variable stud1 and stud2 of the type student.

Typedef Declarations
The typedef keyword enables the programmer to create a new data type name from an
existing data type. By using typedef, no new data is created, rather an alternate name is given
to a known data type.
General syntax:
typedef existing data_type new data_type
Example:
typedef int INTEGER;
now, INTEGER is the new name of the data type. To declare variable using the new data type
name, following code should will be used.
INTEGER num=5;

When we precede a struct name with typedef keyword, then the struct becomes a new type.
typedef struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
To declare a variable of structure student we have to write
student stud1,stud2;

Prof. Praneetha G N, Dept of ISE, SCE 30


Module 5

INITIALIZATION OF STRUCTURE
Initializing a structure means assigning some constants to the members of the structure.
When the user does not explicitly initialize the structure, then C automatically does that. For
int and float the value is initialized to zero and character and string are initialized to ‘\0’.
General Syntax:

struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
…….
} struct_var = {constant1, constnat2,…..};

Or
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
…….
};
struct sturct_name struct_var = {constant1, constnat2,…..};
Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
} stud1 = {01, “Rahul”, “BCA”, 45000};
OR
struct student
{

Prof. Praneetha G N, Dept of ISE, SCE 31


Module 5

int r_no;
char name[20];
char course[20];
float fees;
}
struct student stud1 = {01, “Rahul”, “BCA”, 45000};
ACCESSING THE MEMBER OF STRUCTURE
A structure member variable is generally accessed using a ‘.’ (dot) operator. The syntax
of accessing a structure or a member of a structure can be given as follows:
struct_var.member_name
Example:
stud1.r_no = 01;
stud1.name= “RAHUL”;
stud1.course= “BCA”;
stud1.fees= 45000;
To input the values and print the values, we may write
scanf(“%d”,stud1.r_no);
scanf(“%f”,stud1.fees);
printf(“%s”,stud1.name);
printf(“%f”,stud1.fees);

COPYING AND COMPARING STRUCTURES


We can assign a structure to another structure of the same type. For example, if we have
two structure variables stud1 and stud2 of type struct student given as follows
struct student stud1= {01, “Rahul” , “BCA” , 45000};
struct student stud2;
stud2=stud1;
The above statement initializes the members of stud2 with the values of stud1.

C does not allow two structures to be compared. But, we can compare individual members of
one structure with individual members of another structure.

FINDING THE SIZE OF A STRUCTURE

Prof. Praneetha G N, Dept of ISE, SCE 32


Module 5

There are three different ways through which we can find the member of bytes of
structure will occupy in the memory.
Simple Addition
In this method, list of all data types are made and memory required by each of the items will
be added.
struct Employee
{
int emp_ID;
char name[20];
double salary;
char designation[20];
float experience;
};

SIZE = size of emp_ID + size of name + size of salary + size of designation + size of experience
size of emp_ID = 2
size of name = 20 X size of character
size of salary = 8
size of designation = 20 X size of character
size of experience = 4
= 2 + 20 (1) + 8 + 20 (1) + 4
= 54 bytes

Using sizeof Operator


sizeof Operator can be used to calculate the size of a data type, variable, or an
expression.
Syntax: sizeof(struct_name);
Example:
#include<stdio.h>
typedef struct Employee
{
int emp_ID;
char name[20];
double salary;

Prof. Praneetha G N, Dept of ISE, SCE 33


Module 5

char designation[20];
float experience;
};
void main()
{
struct Employee e;
printf(“ %d”, sizeof(e));
}

Ouput:
54

Subtracting the Addresses


In this technique we use an array of structure variables. We subtract the address of first
element of next consecutive variable from the address of the first element of preceding structure
variable.
#include<stdio.h>
typedef struct Employee
{
int emp_ID;
char name[20];
double salary;
char designation[20];
float experience;
};
void main()
{
struct Employee e[5];
int start, end, len;
start= & e[0].emp_ID;
end = & e[1].emp_ID;
len= start – end;
printf(“ size of structure= %d”, len);
}

Prof. Praneetha G N, Dept of ISE, SCE 34


Module 5

Ouput:
size of structure= 54

Programs
Write a program using structures to read and display the information about a student

#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
struct student s;
printf("Enter The Information of Students :\n\n");
printf("Enter Name : ");
scanf("%s",s.name);
printf("Enter Roll No. : ");
scanf("%d",&s.roll);
printf("Enter marks : ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
Output:
Enter The Information of Students :
Enter Name : Rahul
Enter Roll No. : 01

Prof. Praneetha G N, Dept of ISE, SCE 35


Module 5

Enter marks : 45
Displaying Information
Name : Rahul
Roll No. : 01
marks : 45

Write a C program to read and print an employee's detail using structure


#include <stdio.h>
struct employee{
char name[30];
int empId;
float salary;
};
int main()
{
struct employee emp;
printf("\nEnter details :\n");
printf("Name :");
gets(emp.name);
printf("ID :");
scanf("%d",&emp.empId);
printf("Salary :");
scanf("%f",&emp.salary);
printf("\nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);
return 0;
}
Output:
Enter details :
Name :Mike
ID :1120

Prof. Praneetha G N, Dept of ISE, SCE 36


Module 5

Salary :76543
Entered detail is:
Name: Mike
Id: 1120
Salary: 76543.000000

Prof. Praneetha G N, Dept of ISE, SCE 37

You might also like