Unit 2
Unit 2
ARRAYS
2.1 Arrays:
An array is a group of related data items that share a common name.
Ex:- Students
The complete set of students is represented using an array name students. A particular value
is indicated by writing a number called index number or subscript in brackets after array
name. The complete set of value is referred to as an array, the individual values are called
elements.
A list of items can be given one variable index is called single subscripted variable or a one-
dimensional array.
Declaration of One - Dimensional Arrays :
This array is of type float. Its name is avg. and it can contains 50 elements only. The range
starting from 0 – 49 elements.
The subscript value starts from 0. If we want 5 elements the declaration will be
int number[5];
The elements will be number[0], number[1], number[2], number[3], number[4] There will
not be number[5]
#include<stdio.h>
main(){
int i;
printf(“Enter 10 numbers\n”);
for(i=0;i<10;i++)
{
scanf(“%d”,&a[i]);
}
printf(“the entered numbers are\n”);
for(i=0;i<10;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
To store tables we need two dimensional arrays. Each table consists of rows and
columns. Two dimensional arrays are declare as
#include<stdio.h>
#include<math.h>
#define ROWS 5
#define COLS 5
main()
printf(“Multiplication table”);
for(j=1;j< =COLS;j++)
printf(“%d”,j);
for(i=0;i<ROWS;i++)
row = i+1;
printf(“%2d|”,row);
COLS=j;
They can be initialized by following their declaration with a list of initial values
enclosed in braces.
When all elements are to be initialized to zero, following short-cut method may be used.
MULTI-DIMENSIONAL ARRAYS:
#include <stdio.h>
void printArray( const int a[][ 3 ] );
int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
printf( "Values in array1 by row are:\n" );
printArray( array1 );
printf( "Values in array2 by row are:\n" );
printArray( array2 );
printf( "Values in array3 by row are:\n);
printArray( array3 );
return 0;
}
void printArray( const int a[][ 3 ] )
{
int i; int
j;
for ( i = 0; i <= 1; i++ ) { for
( j = 0; j <= 2; j++ ) {
}
APPLICATIONS OF ARRAYS:
FREQUENCY ARRAYS:
Two common statistical applications that use arrays are frequency distributions and
histograms. A frequency array shows the number of elements with an identical value found in
a series of numbers.
For example ,suppose we have taken a sample of 100 values between 0 and 19.We
want to know how many of the values are 0,how many are 1,how many are 2,and so forth up
through 19.
We can read these numbers into an array called numbers. Then we create an array of
20 elements that will show the frequency of each number in the series.
One way to do it is to assign the value from the data array to an index and then use the
index to access the frequency array.
F=numbers[i];
Frequency[F]++;
Since an index is an expression ,however ,we can simply use the value from our data
array to index us in to the frequency array .The value of numbers[i] is determined first ,and
then that value is used to index in to frequency.
Frequency[numbers[i]]++
HISTOGRAMS:
0 0
1 4 * * * * ————(four 1s)
2 7*******
3 7 * * * * * * *————(seven 3s)
18 2**
19 0 ————————(zero 19s)
RANDOM NUMBER PERMUTATIONS:
To generate a random integral in a range x to y, we must first scale the number and
then ,if x is greater than 0 ,shift the number within the range. We scale the number using the
modulus operator.
Ex: To produce a random number in the range 0 …50,we simply scale the random
number and scaling factor must be one greater than the highest number needed.
rand ( ) %51
modulus works well when our range starts at 0.for example ,suppose we want a random
number between 10 and 20.for this we will use one formula
range = ( 20 - 10 ) +1;
Only the first five random numbers have been placed in the permutation. For each
random number in the random number array ,its corresponding location in the have-random
array is set to 1. Those locations representing numbers that have not yet been generated are
still set to 0.
2.4 STRINGS
The group of characters, digits, and symbols enclosed with in double quotation marks are
called as strings.
Ex: “BVRITH”
“1234”
Every string terminates with “\0‟ (NULL) character. The decimal equivalent value of null
is zero. We use strings generally to manipulate text such as words and sentences. The
common operations that we can perform on strings are:
The last character of string is always “\0‟ (NULL). But it is not necessary to write “\0‟
character at the end of the string. The compiler automatically puts “\0” at the end of the
string / character array.
The characters or elements of the string are stored in contiguous memory locations.
\
H E L L O 0
3. Char name[9]={“H‟},{‟E‟},{‟L‟},{‟L‟},{‟O‟}};
In the above three formats we can initialize character arrays. We can also initialize
character array by using standard input functions like scanf( ), gets ( ) etc and we can
display strings by using puts ( ), printf ( ) functions.
The size of the character array: The argument / size of the character array or string =
Number of characters in the string + NULL character.
Note:
1. If NULL character is not taken in account then the successive string followed by the first
string will be displayed.
2. If we declare size of a string equal to the number of characters. i.e., without taking the
NULL character in to account and we print that will display some garbage value followed by
the string.
To read strings from terminal we can use scanf ( ) function with “%s‟ format specifier.
scanf(“%s”, name);
Limitation: If we use scanf ( ) function for reading string in runtime it terminates its input on
the first white space it finds. The scanf ( ) function automatically append NULL character at
the end of the input string, so we have to declare a (size of) character array which can
accommodate input string and NULL character.
(White space: blanks, tab space, carriage returns, new lines etc.)
By using gets ( ) function we can read a text which consists of more than one word which i
not possible with scanf ( ) function. This function is available in <stdio.h> header file.
Using printf ( ) function we can display the string on output screen with the help of format
specifier „%s‟.
Ex: printf(“%s”,name);
We can use different format specifications to display strings in various formats according to
requirements.
Using puts ( ) function we can display the string without using any format specifier. This
function is available in the <stdio.h> header file in C library.
Using putchar ( ) function we can display one character at a time. So, by using this function
repeatedly with the help of a loop statement we can display total string.
for (i=0;i<5;i++)
putchar (name[i]);
The following table provides frequently used string handling functions which are supported
by C compiler.
FUNCTION
DESCRIPTION
S
strlen ( ) Determines Length of a string
strcpy ( ) Copies a string from source to destination
strncpy ( ) Copies specified number of characters of a string to another string
strcmp ( ) Compares two strings (Discriminates between small and capital letters)
Compares two strings (Doesn‟t Discriminates between small and
stricmp ( )
capital letters)
strncmp ( ) Compares characters of two strings upto the specified length
Compares characters of two strings upto the specified length. Ignores
strnicmp ( )
case.
strlwr ( ) Converts upper case characters of a string to lower case
strupr ( ) Converts lower case characters of a string to upper case
strdup ( ) Duplicates a string
Determines first occurrence of a given character
strchr ( )
in a string
Determines last occurrence of a given character
strrchr ( )
in a string
strstr ( ) Determines first occurrence of a given string in another string
strcat ( ) Appends source string to destination string
strncat ( ) Appends source string to destination string upto specified length
strrev ( ) Reverses all characters of a string
strset ( ) Sets all characters of string with a given argument or symbol
Sets specified number of characters of string with a given argument or
strnset ( )
Symbol
strspn ( ) Finds up to what length two strings are identical
Searches the first occurrence of the character in a given string and
strpbrk ( )
then it display the string from that character.
1. strlen ( ) function: This function counts the number of characters in a given string.
Syntax: strlen(string); (or) strlen(“ string”);
void main( )
char a[80];
int len;
clrscr( );
printf(“enter string:”);
len=strlen(a);
getch( );
(OR )
void main()
int s;
clrscr( );
s=strlen(“KMIT”);
getch( );
}
Output:
Name = KMIT
Output:
Total no of char‟s = 4
Total no of char‟s = 4
2. strcpy ( ) function: This function copies the content of one string to another. Here
string1 is source string and string2 destination string. String1 and string2 are character
arrays. String1 is copied into string2.
void main( )
clrscr( );
strcpy(s2,s1);
getch( );
Output:-
or
strcpy(destination, source,n);
void main()
int n;
clrscr( );
gets(s1);
gets(s2);
getch( );
Destination string=wonderful
4. strcmp ( ) function: This function is used to compare two strings identified by the
arguments and it returns a value “0‟ if they are equal. If they are not equal it will return
numeric difference (ASCII) between the first non-matching characters.
void main( )
int s;
clrscr( );
s=strcmp(m1, m2);
printf(“ %d ”, s);
getch( );
Output:-
-1
void main( )
clrscr( );
m = strcmp(s1, s2);
if(m==0)
else if(m<0)
getch( );
Output:-
enter 2 strings
KMIT
computers
KMIT computers
This function returns zero when two strings are same and it returns non-zero value if they are
not equal
void main( )
or
void main( )
{
char sr[30], tr[30];
int s,n;
clrscr( );
printf (“\nEnter Source String:”);
gets(sr);
printf (“\nEnter Target String:”);
gets(tr);
printf(“\n Enter length up to which comparison is to be made:”); scanf(“%d”,&n);
s=strncmp(sr,tr,n);
if(s==0)
puts(“The two strings are Identical up to %d characters.”,n); else
puts(“The two strings are Different”);
getche( );}
Output:-
(or)
void main( )
int s,n;
clrscr( );
gets(sr);
gets(tr);
scanf(“%d”,&n);
s=strnicmp(sr,tr,n);
if(s==0)
getche( );
Output:-
Enter length upto which comparison is to be made5 The two strings are different.Enter
Source String: goodmorning
8. strlwr ( ) function: This function can be used to convert any string to a lower case.
When you are passing any uppercase string to this function it converts into lower case.
Syntax: strlwr(string);
strupr ( ) function: This function is the same as strlwr( ) but the difference is that strupr( )
converts lower case strings to upper case.
Syntax: strupr(string);
void main ( )
clrscr( );
strlwr(a);
strupr(b);
getch( );
Output:-
SACHIN Karan
sachin KARAN
9. strdup( ) function: This function is used for duplicating a given string at the allocated
memory which is pointed by a pointer variable.
void main( )
clrscr( );
printf(“Enter text:”);
gets(s1);
s2 = strdup(s1);
getch();
Output:
10. strchr( ) function: This function returns the pointer to a position in the first occurrence
of the character in the given string.
Where, string is character array, ch is character variable & chp is a pointer which collects
address returned by strchr( ) function.
void main( )
clrscr( );
printf(“Enter text:”);
gets(s);
ch = getchar( );
chp = strchr(string,ch);
if(chp)
else
getch( );}
Output:
Character to find: r
11. strrchr( ) function: In place of strchr( ) one can use strrchr( ). The difference between
them is that the strchr( ) searches occurrence of character from the beginning of the string
where as strrchr( ) searches occurrence of character from the end (reverse).
Syntax: chp = strrchr(string, ch);
12. strstr( ) function: This function finds second string in the first string. It returns the
pointer location from where the second string starts in the first string. In case the first
occurrence in the string is not observed, the function returns a NULL character.
Syntax: strstr(string1,string2);
void main( )
clrscr( );
printf(“Enter text:”);
gets(s1);
printf(“\nEnter text:”);
gets(s2);
chp = strstr(s1,s2);
if(chp)
getch( );}
13. strcat ( ) function: This function appends the target string to the source string.
Concatenation of two strings can be done using this function.
#include<string.h>
void main ( )
clrscr( );
getch( );
Output:-
Hello KMIT
HelloKMIT
Example Program: To append 2nd string with specified no. of characters at the end of
the string using strncat( ) function.
#include<string.h>
void main ( )
int n;
clrscr( );
scanf("%d",&n);
strcat(s," ");
strncat(s,a,n);
getch( );
Output:-
s= Hello a = KMIT
Hello Mr
Syntax: strrev(string);
#include<string.h>
char s[30]=”hello”;
clrscr( );
strrev(s);
getch( );
Output:-
s1=hello
s2=olleh
void main( )
char t[30];
clrscr( );
printf(“enter string:”);
getch( );
Output:
16. strset( ) function: This function replaces every character of a string with the symbol
given by the programmer i.e. the elements of the strings are replaced with the arguments
given by the programmer.
Syntax: strset(string,symbol);
Example:
void main( )
clrscr( );
puts(“Enter string:”);
gets(st);
scanf(“%c”,&symbol);
getch( );
Output:
17. strnset( ) function: This function is the same as that of strset( ). Here the specified
length is provided. Where, n is the no. of characters to be replaced.
Syntax: strnset(string,symbol,n);
Example:
void main( )
int n;
clrscr( );
puts(“Enter string:”);
gets(st);
scanf(“%c”,&symbol);
strnset(st,symbol,n);
getch( );
Output:
18. strspn( ): This function returns the position of the string from where the source array
does not match with the target one.
Syntax: strspn(string1,string2);
Example Program: To indicate after what character the lengths of the 2 strings have no
match.
void main( )
int len;
clrscr( );
printf(“Enter string1:”);
printf(“\nEnter string2:”);
gets(s2);
len = strspn(s1,s2);
getch( );
Output:
19. strpbrk( ) function: This function searches the first occurrence of the character in a
given string and then it display the string starting from that character.
Example Program: To print given string from first occurrence of given character.
void main( )
char *ptr;
clrscr( );
printf(“Enter string:”);
gets(string1);
ptr = strpbrk(string1,string2);
printf(ptr);
getch();
Output:
Enter a character: d
char x = “a‟;
printf (“%d”,x);
The above statement will display integer value 97 on the screen even though x is a character
variable, because when a character variable or character constant is used in an expression, it
is automatically converted in to integer value by the system. The integer value is equivalent
to ASCII code.
Ex: int x;
x=‟z‟-1;
printf(“%d”,x);
The above statement is valid statement and that will display 121 one as result, because ASCII
value of “z‟ is 122 and therefore the resultant value is 122 – 1 = 121.
This library function converts a string of digits into their integer values.
Ex: int x;
x = atoi(no);
printf(“%d”,x);
2.8 Structures:
Definition: In the C language structures are used to group together different types
of variables under the same name.
Structure is a collection of variables of different data types under single name. A structure
provides a convenience to group of related data types. A structure can contain variables,
pointers, other structures, arrays or pointers. All these variables may contain data items of
similar or dissimilar data types. Using these variables each item of a structure can be
selected. Each variable in the structure represents an item and is called member or field of the
structure. Each field has a type.
type1 member1;
type2 member2;
……..
……..
};
The members are declared with curly braces. The members can be any of the data types such
as int, char, float etc.There should be semicolon at the end of closing brace.
Example:
struct lib_books
char title[20];
char author[15];
int pages;
float price;
};
struct lib_books
char title[20];
char author[15];
int pages;
float price;
As variables are defined before they are used in the function, the structures are also defined
and declared before they are used. A structure can be declared using three different ways
Tagged structures
Structure Variables
Tagged structure means the structure definition associated with structure name is called
tagged structure (i.e. tag_name is the name of the structure).
char name[10];
int roll_number;
float avg_marks;
Here, student is an identifier representing the structure name. It is also called tagname.
char name[10];
int roll_number;
float avg_marks;
};
truct tag_name
type1 member1;
type2 member2;
Structure Variables:
struct student
char name[10];
int roll_number;
float avg_marks;
1. name, roll_number and average_marks are members of a structure and are not
variables. So, they themselves do not occupy any memory.
But, once the structure definition is associated with variables such as ece and cse the compiler
allocates memory for the structure variables
typedef struct
type1 member1;
type1 member1;
………}typeid;
- Using typedef it is not possible to declare a variable. Here, TYPE_ID can be treated
as the new date type.
- Normally all typedef statements are defined at the beginning of the file immediately
after #include and #define statements in a file.
typedef struct
char name[10];
int roll_number;
float avg_marks;
} student;
Initialization of structures
Consider the structure definition for an employee with three fields name, salary and is as
shown below,
struct employee
char name[10];
int id;
float salary;
} a = {“Shivashankar”,1686,20000.28};
( OR )
struct emp
char name[10];
int id;
float salary;
};
Struct emp b = {“Shiva”,1886,18898.28}; //structure declaration with more than one value
char title[20];
char author[20];
int pages;
float price;
strcpy(book1.title, “basic”);
strcpy(book1.author, “balagurusamy”);
book1.pages=250;
book1.price=120.50;
scanf(“%s \n”,book1.title);
scanf(“%s \n”,&book1.pages);
Example2:
struct library_books
char title[20];
char author[15];
int pages;
};
The keyword struct informs the compiler for holding fields ( title, author, pages and price in
the above example). All these are the members of the structure. Each member can be of
same or different data type.
The tag name followed by the keyword struct defines the data type of struct. The tag name
library_books in the above example is not the variable but can be visualized as template
for the structure. The tag name is used to declare struct variables.
The memory space is not occupied soon after declaring the structure, being it a template.
Memory is allocated only at the time of declaring struct variables, like book1 in the
above example. The members of the structure are referred as - book1.title, book1.author,
book1.pages, book1.price.
Two variables of the same structure type can be copied the same way as ordinary variables.
If person1 and person2 belong to the same structure, then the following statements are
valid:
book2=book1;
C does not permit any logical operations on structure variables. In case, we need to compare
them, we may do so by comparing members individually.
book1 == book2
book1 != book2
The individual members are identified using the members are identified using the member
operator. A member with the dot operator along with its structure variable can be treated like
any other variable name and therefore can be manipulated using expressions and operator.
We can also apply increment and decrement operators to numeric type members.
student1.number++;
++student1.number;
We have used the dot operator to access the members of structure variables. In fact, there are
two other ways. The identifier ptr is known as pointer that has been assigned the address of
the structure variable n. now members can be accessed in three ways:
Using indirection
notation : (*ptr).x
We may declare an array of structures, each element of the array representing a structure
variable. For example:
define an array called student, that consists of 100 elements. Each element is defined to be of
the type struct class.
Write a c program to calculate the subject wise and student wise totals and store them
as a part of the structure.
struct marks
int sub1;
int sub2;
int total;
};
void main( )
int i;
for(i=0;i<=2;i++)
student[i].total=student[i].sub1+ student[i].sub2+
student[i].sub3; total.sub1=total.sub1+student[i].sub1;
total.sub2=total.sub2+student[i].sub2;
total.sub3=total.sub3+student[i].sub3;
total.total=total.total+student[i].total;
printf(“Student Total\n\n”);
for(i=0;i<=2;i++)
printf(“student[%d
] %d\n”, i+1,student[i].total);
printf(“
%s %d\n%s %d\n%s %d\n”,
getch();
Output:
Student Total
student[
1] 193
student[
2] 197
student[
3] 164
Tot
Subject al
subject1 177
subject2 156
subject3 221
grand
total = 554
C permits the use of arrays as structure numbers. We have already used arrays of characters
inside a structure. Similarly, we can use single dimension or multidimensional arrays of type
int or float.
struct marks
int number;
} student[2];
Here, the member subject contains three elements, subject[0], subject[1] and subject[2].
Example program:
void main( )
struct marks
int sub[3];
int total;
};
int i, j;
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
student[i].total += student[i].sub[j];
total.sub[j] += student[i].sub[j];
total.total += student[i].total;
printf(“Student Total\n\n”);
for(i=0;i<=2;i++)
printf(“student[%d
] %d\n”, i+1,student[i].total);
printf(“subject -
%d %d\n”, j+1,total.sub[j]);
printf(“\n grand
total = %d \n”, total.total);
getch();
Output:
Student Total
student[1
] 193
student[2
] 197
student[3
] 164
Tot
Subject al
subject1 177
subject2 156
grand
total = 554
Write a C program to read and display car number, starting time and reaching time.
void main( )
struct time
int second;
int minute;
int hour;
};
struct tt
int carno;
};
struct tt r1;
scanf(“%d”,&r1.carno);
printf(“\t%d\t”,r1.carno);
getch(); }
Output:
Like variables of standard data type structure variables also can be passed to the function by
value or address.
struct book {
char n[30];
char author[30];
int pages;
};
void main()
show(&b1);
getch();
clrscr();
If you want a pointer to a structure you have to use the -> (infix operator) instead of a dot.
#include<stdio.h>
char *name;
int number;
}TELEPHONE;
void main()
TELEPHONE index;
ptr = &index;
ptr->number = 12345;
getch();
Note: The -> (infix operator) is also used in the printf statement.
A structure definition which includes at least one member as a pointer to the same structure
is known as self-referential structure.
Syntax: Example:
struct struct_name
Struct student
datatype datatypename;
Char n[50];
struct_name * pointer_name;
Int rollno;
};
Struct student
};
2.13 UNIONS
Unions are like structures, in which the individual data types may differ from each other. All
the members of the union share the same memory / storage area in the memory. Every
member has unique storage area in structures. In this context, unions are utilized to observe
the memory space. When all the values need not assign at a time to all members, unions are
efficient. Unions are declared by using the keyword union, just like structures.
union tag_name {
type1 member1;
type1 member2;
};
int code;
floa the memory space. When all the values need not assign at a time to all members,
unions are efficient. Unions are declared by using the keyword union, just like structures.
int code;
float price;
};
A union is utilized to use same memory space for all different members of union. Union
offers a memory section to be treated for one variable type , for all members of the union.
Union allocates the memory space which is equivalent to the member of the union, of large
memory occupancy.
A union is like a structure in which all members are stored at the same address. Members
of a union can only be accessed one at a time. The union data type was invented to prevent
memory fragmentation. The union data type prevents fragmentation by creating a standard
size for certain data. Just like with structures, the members of unions can be accessed with
the . and -> operators. For example:
#include<stdio.h>
double PI;
int B;
}MYUNION;
void main()
MYUNION numbers;
numbers.PI = 3.14;
numbers.B = 50;
getch();
t price;};
UNION OF STRUCTURE
We know that one structure can be nested within another structure. It the same way a union
can be nested another union. We can also create structure in a union or vice versa.
Write a program to use structure within union. Display the contents of structure
elements.
{ st.set.f = 5.5;
{ st.set.p[1] = 66;
clrscr(
float f; );
}; printf(“\n%c”,st.set.p[0]);
union z printf(“\t%c”,st.set.p[1]);
{ }
}; A B
Structure Union
a structure. a structure.
the sum of sizes of its members. The equal to the size of largest member.
slack bytes.
3
3. Each member within a structure is . Memory allocated is shared by
memory for each member will start at every member begins at offset values.
structure.
at a time. a time.
7
7. Several members of a structure can . Only the first member of a union can
One of the powerful features of C is ability to access the memory variables by their
memory address. This can be done by using Pointers. The real power of C lies in the proper
use of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say
that a pointer points to a variable that is stored at that address. A pointer itself usually
occupies 4 bytes of memory (then it can address cells from 0 to 232-1).
Advantages of Pointers :
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
2.15 Definition :
Declaration :
Datatype * Variable-name;
Eg:- int *ad; /* pointer to int */
char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */
Here ‘&’ is called address of a variable. ‘p’ contains the address of a variable i
The operator & returns the memory address of variable on which it is operated, this is
called Referencing.
int *p,x; x
=5; p= &x;
Assume that x is stored at the memory address 2000. Then the output for the
following printf statements is :
Output
Printf(“The Value of x is %d”,x); 5
Printf(“The Address of x is %u”,&x); 2000
Printf(“The Address of x is %u”,p); 2000
Printf(“The Value of x is %d”,*p); 5
Printf(“The Value of x is %d”,*(&x)); 5
Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then we
can make the pointer P to point to the array a by following assignment
P = a;
We can access every value of array a by moving P from one element to another.
i.e., P points to 0th element
P+1 points to 1st element
P+2 points to 2nd element
points to
P+3 3rd Element
points to
P +4 4th Element
#include <stdio.h>
void swap(int,int);
main()
{
int a,b;
printf(“Enter the Values of a and b:”);
scanf(“%d%d”,&a,&b); printf(“Before
Swapping \n”); printf(“a = %d \t b = %d”,
a,b); swap(a,b);
printf(“After Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
#include<stdio.h>
main()
{
int a,b; a =
10; b = 20;
swap (&a, &b); printf(“After
Swapping \n”);
ADDRESS ARITHIMETIC :
We can add and subtract integers to/from pointers – the result is a pointer to another element
of this type
NULL POINTER :
‘Zero’ is a special value we can assign to a pointer which does not point to anything
most frequently, a symbolic constant NULL is used. It is guaranteed, that no valid address is
equal to 0.The bit pattern of the NULL pointer does not have to contain all zeros usually it
does or it depends on the processor architecture. On many machines, dereferencing a NULL
pointer causes a segmentation violation.
if (psz1)
In C ,an additional type void *(void pointer) is defined as a proper type for generic
pointer. Any pointer to an object may be converted to type void * without loss of
information. If the result is converted back to the original type ,the original pointer is
recovered .
Ex:
main()
{
void *a; int
n=2,*m;
double d=2.3,*c;
a=&n;
m=a;
printf(“\n%d %d %d”,a,*m,m);
a=&d;
c=a;
printf(“\n%d %3.1f %d”,a,*c,c);
}
In the above program a is declared as a pointer to void which is used to carry the address of
an int(a=&n)and to carry the address of a double(a=&d) and the original pointers are
recovered with out any loss of information.
POINTERS TO POINTERS :
So far ,all pointers have been pointing directely to data.It is possible and with
advanced data structures often necessary to use pointers to that point to other pointers. For
example,we can have a pointer pointing to a pointer to an integer.This two level indirection
is seen as below:
//Local declarations
q p a
Ex: 23456 28765
0 0 58
There is no limit as to how many level of indirection we can use but practically we
seldom use morethan two.Each level of pointer indirection requires a separate indirection
operator when it is dereferenced .
In the above figure to refer to ‘a’ using the pointer ‘p’, we have to dereference it as
shown below.
*p
To refer to the variable ‘a’ using the pointer ‘q’ ,we have to dereference it twice toget
to the integer ‘a’ because there are two levels of indirection(pointers) involved.If we
dereference it only once we are referring ‘p’ which is a pointer to an integer .Another way to
say this is that ‘q’ is a pointer to a pointer to an integer.The doule dereference is shown
below:
**q
The data types defined by the user are known as the user-defined data types. C provides two
identifiers typedef and enum to create new data type names.
Typedef:
It allows the user to define an identifier that would represent an existing data type. The user-
defined data type identifier can later be used to declare variables.
Typedef cannot create a new type but it creates a new name to the existing type.
The main advantage of typedef is that we can create meaningful data type names for
increasing the readability of the program.
{ printf(“\n minutes=%d \t
Enumeration:
Synta
x: enum identifier {value1, value2, …….,valuen} ;
Identifier: it is a user defined enumerated data type which can be used to declare variables
that can have one of the values enclosed within the braces (enumeration constants).
The enumerated variables v1, v2, v3,…….,vn can only have one of the values value1,
value2, …….,valuen .
v4 = value2;
Ex: enum day {Monday, Tuesday, Wednesday, …. Sunday}; (definition of identifier „day‟)
week_st = Monday;
week_end= Friday;
Note:
2. The compiler automatically assigns integer digits beginning with 0 to all the
enumeration constants .i.e. 0 is assigned to value1, 1 is assigned to value2, 2 is assigned
to value3, and soon. User can also assign values explicitly to the enumeration constants.
Ex: enum day {Monday=1, Tuesday, Wednesday, …. Sunday};
Tutorial Questions
1. include <stdio.h>
struct student
{
char *name;
};
void main()
{
struct student s, m;
s.name = "st";
m = s;
printf("%s%s", s.name, m.name);
} Ans______________________
#include <stdio.h>
int main(void) {
int i,t[3];
for(i = 2; i >=0 ; i--)
t[i] = i - 1;
printf("%d",t[1] - t[t[0] + t[2]]);
return 0;
}
Ans________________________
7. include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "Hello", str2[20] = " World";
printf("%s\n", strcpy(str2, strcat(str1, str2)));
return 0;
} Ans___________________________
8. #include<stdio.h>
#include<string.h>
int main()
char sentence[80];
int i;
printf("Enter a line of text\n");
gets(sentence);
for(i=strlen(sentence)-1; i >=0; i--)
putchar(sentence[i]);return o;}
Ans___________________
Assignment Questions
SET 1:
1. Implement a c program to transpose the given matrix.
2. Implement a C program to add elements of array by passing it as an argument.
SET 2:
SET 3:
1. Implement a c program to find the largest from given strings.
2. Discuss call by value and call by reference.
SET 4
1. Implement a c program to show the difference between gets() and scanf().
2. Explain the importance of reaaloc() and free().
SET 5:
1. Implement a C program to read and print an employee's detail using structure
SET-6
Important Questions
4. The elements or the members of the Array are accessed by _______________ names.
(same/different).
_______________.
Dimensional.
8. main() { int i=1; while (i<=5) { printf("%d",i); if (i>2) goto here; i++; } } fun() { here:
printf("PP");
int main()
int arr[5];
// is 32 bit
arr++;
printf("%u", arr);
return 0;