PPS Unit 2
PPS Unit 2
in
ACE
Engineering College
Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
NAAC Accridated with ‘A’ Grade
Department of
Computer Science and Engineering
Prepared by :
Ms. Shubhangi Mahule
Assistant Professor (M.Tech)
ACE is the leading institute for coaching in ESE, GATE & PSUs
H O: Sree Sindhi Guru Sangat Sabha Association, # 4-1-1236/1/A, King Koti, Abids, Hyderabad-500001.
Ph: 040-23234418 / 19 / 20 / 21, 040 - 24750437
2 Strings,
3 Structures and union
4 Enumeration data type
5 Pointers:
Array:
• An array is collection of items or elements stored at continuous memory locations.
(or) An array is a group of related data items that share a common name.
• The idea is to declare multiple items of same type together, accessed using a
common name
Memory Adddress
Elements of an array are accessed by specifying the index ( offset ) of the desired
element within square [ ] brackets after the array name.
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
3 Computer Science Engg
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
4 Computer Science Engg
return 0;
}
Output:
Ex2: Reading the element into an array and print all the element of array
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 10; /* set element at location i to i + 100 */
}
/* output each array element’s value */
for (j = 0; j < 10; j++ )
{
printf(“Element[%d] = %d\n”, j, n[j] );
}
return 0;
}
Output:
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
5 Computer Science Engg
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
6 Computer Science Engg
Output:
3 Multi-Dimensional Array:
• C allows arrays of three or more dimensions. The exact limit is determined
by Compiler.
Syntax:
Storageclass datatype array-name[s1][s2][s3] - - - - - [sn];
where s1,s2,...sn is size of dimension.
Ex:- int Survey[3][5][2];
Limitations of Array:
• the dimension of an array is determined the moment the array is created, and
cannot be changed later on;
• the array occupies an amount of memory that is proportional to its size,
independently of the number of elements that are actually of interest;
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
7 Computer Science Engg
• if we want to keep the elements of the collection ordered, and insert a new For Micro Notes by the
Student
value in its correct position, or remove it, then, for each such operation we
may need to move many elements (on the average, half of the elements of the
array); this is very inefficient.
String:
• Strings are declared in a similar manner as arrays. Only difference is that,
strings are of char type.
• Strings are actually one-dimensional array of characters terminated by a null
character (‘\0’).
The given string is initialized and stored in the form of arrays as below
Note: Actually, you do not place the null character at the end of a string constant. The
C compiler automatically places the ‘\0’ at the end of the string when it initializes
the array.
Example:
#include <stdio.h>
int main () {
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
8 Computer Science Engg
char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}; For Micro Notes by the
Student
printf(“Greeting message: %s\n”, greeting );
return 0;
}
Output:
Greeting message: Hello
Ex. Write a program to read and print the string using all input output function. (
getchar(), gets(), scanf() with different format specifiers).
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
9 Computer Science Engg
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
10 Computer Science Engg
The following example uses some of the above-mentioned functions – For Micro Notes by the
Student
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = “Hello”;
char str2[12] = “World”;
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf(“strcpy( str3, str1) : %s\n”, str3 );
return 0;
}
When the above code is compiled and executed, it produces the following
Output −
strcpy( str3, str1) : Hello
strcat( str1, str2) : HelloWorld
strlen(str1) : 10
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
11 Computer Science Engg
Array of String:
Syntax:
Datatype arrayname[row-size][col-size];
Example: char President[4][8];
• A string is a 1-D array of characters, so an array of strings is a 2-D array of
characters or array of arrays of character.
• A NULL character(‘\0’) must terminate each character string in the array.
• We can think of an array of strings as a table of strings, where each row of the
table is a string
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
12 Computer Science Engg
Structure:
• structure is user defined data type available in C that allows combining data
items of different kinds ie int, float, char, array and pointers.
• Structures are used to represent a record. Suppose you want to keep track
of your books in a library. You might want to track the following attributes
about each book −
□ Title
□ Author
□ Subject
□ Book ID
□ Publishing date
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member. The format of the struct statement is as
follows −
Syntax:
struct tag
{
member 1;
member 2;
...
member m;
} variable1, variable2....... , variable n;
• The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition.
• At the end of the structure’s definition, before the final semicolon, you can
specify one or more structure variables but it is optional.
• Structure members can’t be initialized within structure and there is no
memory allocated for the members of the structure.
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
13 Computer Science Engg
• Memory for all the member will allocate after creating the variable of For Micro Notes by the
struct type. Student
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
14 Computer Science Engg
/* book 2 specification */
strcpy( Book2.title, “Telecom Billing”);
strcpy( Book2.author, “Zara Ali”);
strcpy( Book2.subject, “Telecom Billing Tutorial”);
Book2.book_id = 6495700;
/* print Book1 info */
printf( “Book 1 title : %s\n”, Book1.title);
printf( “Book 1 author : %s\n”, Book1.author);
printf( “Book 1 subject : %s\n”, Book1.subject);
printf( “Book 1 book_id : %d\n”, Book1.book_id);
/* print Book2 info */
printf( “Book 2 title : %s\n”, Book2.title);
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
15 Computer Science Engg
Array of structures:
Syntax:
structtype variablename[size];
Ex: struct point arr[10];
In above example arr is variable which store maximum 10 values of struct point type
unlike normal variable;
int main()
{
// Create an array of structures
struct arr[10];
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
16 Computer Science Engg
typedef statement:
The typedef allows us to create an alias or new name for an existing type or user
defined type. The syntax of typedef is as follows:
Syntax:
typedef data_type new_name;
typedef: It is a keyword.
data_type: It is the name of any existing type or user defined type created using
structure/union.
new_name: alias or new name you want to give to any existing type or user defined
type.
Ex: typedef int myint;
Myint a=20; //valid statement
#include <stdio.h>
#include <string.h>
int main( ) {
Book book;
strcpy( book.title, “C Programming”);
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
17 Computer Science Engg
Union in C:
Like Structures, union is a user defined data type. In union, all members share the
same memory location.
For example in the following C program, both x and y share the same location. If we
change x, we can see the changes being reflected in y.
Example
#include <stdio.h>
int main()
{
// A union variable t
union test t;
t.x = 2; // t.y also gets value 2
printf (“After making x = 2:\n x = %d, y = %d\n\n”,
t.x, t.y);
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
18 Computer Science Engg
t.x, t.y);
return 0;
}
Output:
After making x = 2:
x = 2, y = 2
#include <stdio.h>
union test1
{
int x;
int y;
};
union test2{
int x;
char y;
};
union test3
{
int arr[10];
char y;
};
int main()
{
printf (“sizeof(test1) = %d, sizeof(test2) = %d,”
“sizeof(test3) = %d”, sizeof(test1),
sizeof(test2), sizeof(test3));
return 0;
}
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
19 Computer Science Engg
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names
to integral constants, the names make a program easy to read and maintain.
enum State {Working = 1, Failed = 0};
The keyword ‘enum’ is used to declare new enumeration types in C .
enum declaration.
enum flag{constant1, constant2, constant3, ....... };
The name of enumeration is “flag” and the constant are the values of the flag. By default,
the values
of the constants are as follows: constant1 = 0, constant2 = 1, constant3 = 2 and so on.
Variables of type enum can also be defined. They can be defined in two ways:
enum week{Mon, Tue, Wed};
enum week day;
Or
enum week{Mon, Tue, Wed}day;
An example program to demonstrate working of enum in C
#include<stdio.h>
int main()
{
enum week day;
day = Wed;
printf(“%d”,day);
return 0;
}
Output: 2
In the above example, we declared “day” as the variable and the value of “Wed” is
allocated to day, which is 2. So as a result, 2 is printed.
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
20 Computer Science Engg
• Two enum names can have same value. For example, in the following C For Micro Notes by the
Student
program both ‘Failed’ and ‘Freezed’ have same value 0.
enum State {Working = 1, Failed = 0, Freezed = 0};
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
21 Computer Science Engg
• Two pointers can be subtracted to know how many elements are available For Micro Notes by the
Student
between these two pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler).
Advantages:
• Pointers are more efficient in handling arrays and data tables.
• Pointers can be used to return multiple values from a function via function
arguments.
• Pointers allow passing a function as argument to other functions.
• The use of pointer arrays to character strings results in saving of data storage
space in memory.
• Pointers allow C to support dynamic memory management.
• Pointers provide an efficient way for manipulating dynamic data structures
such as structures, linked lists, queues, stacks and trees.
• Pointers increase the execution speed and thus reduce the program execution
time.
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q’s value using ptr variable */
printf(“%d %d “,q, *ptr);
return 0;
}
Output: 50 50
Explanation:
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
22 Computer Science Engg
Pointer to Array:
Syntax:
data_type (*var_name)[size_of_array];
int (*ptr)[10];
• Here ptr is pointer that can point to an array of 10 integers. Since subscript([])
have higher precedence than indirection(*), it is necessary to enclose the
indirection operator(*) and pointer name inside parentheses.
• Here the type of ptr is ‘pointer to an array of 10 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points
to the whole array are totally different. The following program shows this:
#include<stdio.h>
int main()
{
// Pointer to an integer
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
23 Computer Science Engg
return 0;
}
Output:
p: is pointer to 0th element of the array arr, while ptr: is a pointer that points to the
whole array arr.
The base type of p is int while base type of ptr is ‘an array of 5 integers’.
We know that the pointer arithmetic is performed relative to the base size, so
if we write ptr++, then the pointer ptr will be shifted forward by 20 bytes.
The following figure shows the pointer p and ptr. Darker arrow denotes pointer to an
array.
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
24 Computer Science Engg
On dereferencing a pointer expression we get a value pointed to by that pointer For Micro Notes by the
Student
expression. Pointer to an array points to an array, so on dereferencing it, we should get
the array, and the name of array denotes the base address. So whenever a pointer to an
array is dereferenced, we get the base address of the array to which it points.
// C program to illustrate sizes of pointer of array
#include<stdio.h>
int main()
{
int arr[] = { 3, 5, 6, 7, 9 };
int *p = arr;
int (*ptr)[5] = &arr;
Pointer to Structure:
can be created and accessed using pointers. A pointer variable of a structure can be
created as below:
struct name
{
member1;
member2;
.
.
};
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
25 Computer Science Engg
#include <stdio.h>
typedef struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of person1
printf(“Displaying: “);
printf(“%d%f”,(*personPtr).age,(*personPtr).weight);
return 0;
}
In this example, the pointer variable of type struct person is referenced to the address
of person1. Then, only the structure member through pointer can can accessed.
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
26 Computer Science Engg
In other words, structures pointing to the same type of structures are self-referential in
nature.
Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
Self Referential Structure with Single Link:
These structures can have only one self-pointer as their member. The following
example will show us how to connect the objects of a self-referential structure with
the single link and access the corresponding data members. The connection formed is
shown in the following figure.
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
27 Computer Science Engg
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Intialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
Output:
30
40
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)
28 Computer Science Engg
ACE Engineering College : Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG)