SlideShare a Scribd company logo
1 of 80
UNIT-2
Derived data types
Content:
1 Array
2 Strings
3 Structures and union
4 Enumeration data
type
5 Pointers
Data types:
What is derived data type?
• Derived data types are those that are defines in
terms of other data types(called base types).
• New types may be derived from primitive types.
• Why we are using arrays?
• Primitive datatypes can hold only one value at a
time.
• To overcome the disadvantage of primitive data
type we use Arrays concept. Array can hold n
number of elements at a time.
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 address
Elements of an array are accessed by specifying the index ( offset ) of the
desired element within square [ ] brackets after the array name
The types of Arrays
1 One dimensional array
2 Two dimensional array
3 Multi dimensional array
One dimensional Array
declaration:
Syntax:
Storageclass dataType arrayname[size];
In C, we can declare an array by specifying its
type and size or by initializing it or by both.
Storage class is optional.
Declaration and Initialization :
• Storageclass dataType arrayname[size] = {List of Value};
1. int arr[10]; // declaration for one dimensional array
index
2. int arr[6] = {10, 20, 30, 40,50,60}
G.V G.V G.V G.V G.V G.V G.V G.V G.V G.V
10 20 30 40 50 60
0 1 2 3 4 5 6 7 8 9
3. int arr[6]={12,13,14};
4. int arr[]={5,6,7,8};
5. Int arr{5};
arr[0]=12;
arr[1]=23;
arr[2]=40;
arr[3]=50;
arr[4]=55;
12 13 14 0 0 0
5 6 7 8
12 23 40 50 55
0 1 2 3 4
Accessing Array Elements:
Array elements are accessed by using an integer index. Array index starts
with 0 and goes till size of array minus 1.
Ex1: program for how to assign the array element
#include<stdio.h>
int main()
{
int arr[5];
arr[0] = 5;
arr[1] = 2;
arr[2] = -10;
arr[3] = arr[0];
printf("the elements in the array are");
printf(“n %d %d %d %d”, arr[0], arr[1], arr[2], arr[3]);
return 0;
}
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,num;
printf("Enter how many elements
want to insert in to the array");
scanf("%d",&num);
for ( i = 0; i < num; i++ )
{
scanf("%d",&n[i]);
}
for (j = 0; j < num; j++ )
{
printf("Element[%d] =
%dn", j, n[j] );
}
return 0;
}
Two – Dimensional Array:
• To store tables we need two dimensional arrays. Each table
consists of rows and columns.
• The two-dimensional array can be defined as an array of
arrays. The 2D array is organized as matrices which can be
represented as the collection of rows and columns.
• Two dimensional arrays are declare as…
Syntax:
Storageclass datatype arrayname [row-size][col-size];
Initializing Two Dimensional Arrays:
• They can be initialized by following their declaration
with a list of initial values enclosed in braces.
Ex:- int table[2][3] = {0,0,0,1,1,1};
• Initializes the elements of first row to zero and second
row to one. The initialization is done by row by row.
The above statement can be written as
int table[2][3] = {{0,0,0},{1,1,1}};
• When all elements are to be initialized to zero,
following short-cut method may be used.
int m[3][5] = {{0},{0},{0}};
• Valid declaration
int abc[2][2] = {1, 2, 3 ,4 }
• Valid declaration
int abc[][2] = {1, 2, 3 ,4 }
• Invalid declaration – you must specify
second dimension
int abc[][] = {1, 2, 3 ,4 }
• Invalid because of the same reason
mentioned above
int abc[2][] = {1, 2, 3 ,4 }
How to display the elements from 2d array
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
How to read and display the elements from 2d array
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("n printing the elements ....n");
for(i=0;i<3;i++)
{
printf("n");
for (j=0;j<3;j++)
{
printf("%dt",arr[i][j]);
}
}
}
Addition of two matrices:
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100):
");
scanf("%d", &c);
printf("nEnter elements of 1st matrix:n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
printf("Enter elements of 2nd matrix:n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("nSum of two matrices: n");
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%d ", sum[i][j]);
}
printf("n");
}
return 0;
}
Multiplication
• In order to multiply two matrices,
no.of columns of first matrix = no.of rows in
second matric
formula:
• mul[i][j]= mul[i][j]+a[i][k]*b[k][j];
3.Multi-Dimensional Array:
• C allows arrays of three or more
dimensions. The exact limit is determined
by the Compiler.
• Syntax:
• Storage class datatype array-name[s1][s2][s3][sn];
where s1,s2,… sn is the size of the dimension.
Ex:- int Survey[3][5][2];
Advantages of Arrays
• Arrays represent multiple data items of the
same type using a single name.
• In arrays, the elements can be accessed
randomly by using the index number.
• Arrays allocate memory in contiguous memory
locations for all its elements. Hence there is no
chance of extra memory being allocated in
case of arrays. This avoids memory overflow or
shortage of memory in arrays.
Applications of Arrays
1. Array stores data elements of the same data type.
2. Maintains multiple variable names using a single name.
Arrays help to maintain large data under a single variable
name. This avoid the confusion of using multiple variables.
3. Arrays can be used for sorting data elements. Different
sorting techniques like Bubble sort, Insertion sort,
Selection sort etc use arrays to store and sort elements
easily.
4. Arrays can be used for performing matrix
operations. Many databases, small and large, consist of
one-dimensional and two-dimensional arrays whose
elements are records.
5. Arrays can be used for CPU scheduling.
6. Lastly, arrays are also used to implement other data
structures like Stacks, Queues, Heaps, Hash tables etc.
Strings:
• 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’).
Declaration and initialization:
• char c[] =“abcd”;
• char c[50] =“ABCD”;
• char c[]={‘a’,’b’,’c’,’d’,’0’};
• char c[5]={‘a’,’b’,’c’,’d’,’0’};
• char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’};
(or)
• char greeting[] = “Hello”;
a B C D 0
A B C D 0
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.
The given string is initialized and stored in the form of
arrays as below
Example1:
#include <stdio.h>
int main ()
{
char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’};
printf(“Greeting message: %sn”, greeting );
return 0;
}
Output:
Greeting message: Hello
Example2:
#include <stdio.h>
int main ()
{
char name[6] ;
printf(“enter your name”);
gets(name);
Printf(“%s”,name);
return 0;
}
Output:
Greeting message: Hello
String handling functions:
1. String length
2. String concatenation
3. String copy
4. String comparison
5. String occurrence
String Library or Manipulation Function:
s.no Function Work of function
1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of
string s1.
3 strlen(s1); Returns the length of string s1.
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same;
less than 0 if s1<s2;
6 strstr(s1, s2); Returns a pointer to the first occurrence
of string s2 in string s1.
• strcmp() compares the corresponding characters
from both strings based on their ASCII values.
• Therefore, if the ASCII value of the first character
in the first string is less than the ASCII value of the
corresponding character in the second string,
strcmp() returns a negative number.
• If the ASCII value of the first differing character in
the first string is greater than the ASCII value of
the corresponding character in the second string,
strcmp() returns a positive number.
The following example uses some of the above-mentioned functions
#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) : %sn”, str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf(“strcat( str1, str2): %sn”, str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf(“strlen(str1) : %dn”, len );
return 0;
}
The strstr() function returns pointer to the first
occurrence of the matched string in the given
string. It is used to return substring from first match
till the last character.
#include <stdio.h>
#include<string.h>
int main(){
char str[100]="this is c programming lab";
char *sub;
sub=strstr(str,“lab");
printf("nSubstring location is: %d",sub-str);
return 0;
}
Array of Strings:
Syntax:
Datatype arrayname[row-size][col-size];
Example: initialization
char cities[4][10]={“pune”,”Mumbai”,”delhi”,”Nagpur”};
• 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.
Memory representation:
#include <stdio.h>
int main()
{ //declaration
char strings[10][100];
int i,n;
printf("Enter total number of strings: ");
scanf("%d",&n);
printf("Enter strings...n");
for(i=0; i<n; i++)
{
printf("enter String [%d] : ",i+1);
scanf("%s",strings[i]);
}
printf("nStrings are...n");
for(i=0; i<n; i++)
{
printf("[%d]: %sn",i+1,strings[i]);
}
return 0;
}
Structures:
• 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 structure name
{
member 1;
member 2;
...
member m;
} variable1, variable2,…., variable n;
Here is the way you would declare the Books structure :
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Structure variable may be defined as a member of
another structure. In that case, the declaration of the
embedded structure must appear before the declaration
of the outer structure.
struct date
{
int month;
int day;
int year;
} ;
struct Books
{
char title[50]; char
author[50];
char subject[100];
int book_id;
struct date publishing_date;
} book;
The second structure (Books) contains another
structure(date)as one of the members.
Initialization of structure variables:
#include<stdio.h>
int main()
{
struct car
{
char name[100];
float price;
};
struct car car1 ={"xyz", 987432.50};
printf("Name of car1 =%sn,car1.name);
printf("Price of car1 = %fn",car1.price);
return 0;
}
Accessing Structure Members:
• To access any member of a structure, we use the
member access operator (.) ie dot operator.
• The member access operator is coded as a period
between the structure variable name and the structure
member (book.title, book.subject,) that we wish to
• access. You would use the keyword struct to
define variables of structure type.
Array of structures
• An array of structres in C can be defined as the
collection of multiple structures variables where each
variable contains information about different entities.
The array of structures in C are used to store
information about multiple entities of different data
types.
• The array of structures is also known as the collection
of structures.
Nested structures:
• C provides us the feature of nesting one
structure within another structure by using
which, complex data types are created.
• For example, we may need to store the address of an
entity employee in a structure. The attribute address
may also have the subparts as street number, city,
state, and pin code. Hence, to store the address of
the employee, we need to store the address of the
employee into a separate structure and nest the
structure address into the structure employee.
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....n");
printf("name: %snCity: %snPincode: %dnPhone: %s",emp.name,emp.add.city,em
p.add.pin,emp.add.phone);
}
Unions:
• Like Structures, union is a user defined data
type.
• In union, all members share the same
memory location.
• Syntax:
union Identity
{
Data members;
…..
…..
};
Example
#include <stdio.h>
union test // Declaration of union is same as structures union test
{
int x, y;
};
int main()
{
test t; // A union
variable t union
t.x = 2; // t.y also gets value 2
printf (“After making x = 2:n x =
%d, y = %dnn”, t.x, t.y);
t.y = 10; // t.x is also updated to 10
printf (“After making Y = ‘A’:n x = %d, y = %dnn”, t.x, t.y);
return 0;
}
How is the size of union decided by compiler?
Size of a union is taken according the size of
largest member in union.
#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;
}
Pointers
• Pointers in C language is a variable that
stores/points the address of another variable.
Syntax:
Datatype *var_name;
Example : int *p;
char *p;
Where, * is used to denote that “p” is pointer variable
and not a normal variable.
Assigning address of a variable to a
pointer:
• Example
Int num=10;
Int *ptr;
ptr=&num;
Points to remember:
1. Normal variable stores the value whereas pointer
variable stores the address of the variable.
2. The content of the C pointer always be a whole number i.e. address.
3. Always C pointer is initialized to null, i.e. int *p = null.
4. & symbol is used to get the address of the variable.
5. * symbol is used to get the value of the variable that the pointer is
pointing to.
6. If a pointer in C is assigned to NULL, it means it is pointing to
nothing.
7. Two pointers can be subtracted to know how many elements are
available between these two pointers.
8. But, Pointer addition, multiplication, division are not allowed.
9. The size of any pointer is 2 byte (for 32 bit compiler).
Example
#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);
printf("n %u ",ptr);
return 0;
}
Pointer to an array:
datatype array[size];
datatype *pointer = array;
Example:
int arr[5] = {1, 2, 3,4,5};
int *p = arr;
p
1000
1 2 3 4 5
Example:
#include<stdio.h>
void main()
{
int arr[5] = {1, 2, 3,4,5};
int *p = arr;
for (int i = 0; i < 3; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
#include <stdio.h>
int main () {
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; /* an array with 5
elements */
double *p;
int i;
p = balance;
printf( "Array values using pointern"); /* output each array element's
value */
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %fn", i, *(p + i) );
}
printf( "Array values using balance as addressn");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %fn", i, *(balance + i) );
}
return 0;
}
Array of pointer:
Like an array of variables, we can also use array of pointers in c.
Syntax:
datatype *variablename[size];
Example:
Int *ptr[10];
Float *ptr[5];
Char *ptr[6];
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>
const int SIZE = 3;
void main()
{
int arr[] = { 1, 2, 3 };
int i, *ptr[SIZE]; // we can make an integer pointer array to
storing the address of array elements
for (i = 0; i < SIZE; i++)
{
ptr[i] = &arr[i]; // assigning the address of integer.
}
// printing values using pointer
for (i = 0; i < SIZE; i++)
{
printf("Value of arr[%d] = %dn", i, *ptr[i]);
}
}
Pointer to Structure:
Structure can be created and accessed using
pointers. A pointer variable of a structure can be created
as below:
struct name
{
member1;
member2;
….
….
};
int main()
{
struct name *ptr;
}
#include<stdio.h>
struct student{
int sno;
char sname[30];
float marks;
};
main ( ){
struct student s;
struct student *st;
printf("enter sno, sname, marks:");
scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
st = &s;
printf ("details of the student are");
printf ("Number = %dn", st ->sno);
printf ("name = %sn", st->sname);
printf ("marks =%fn", st ->marks);
}
Self Referential Structures:
• Self Referential structures are those structures that have
one or more pointers that point to the same type of
structure, as their member. (or)
• When structure member points to itself then this type of
the structure is called Self Referential Structures.
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.
Types of pointers:
There are various types of pointer in C,
we have 4 different types of pointers in C. They are as
follows
1) Void pointer
2) Null pointer
3) Wild pointer
4) Dangling pointer
• 1) Void pointer
• A pointer is said to be void when a pointer has no
associated data type with it. In other words, it can
point to any data type and also, it can be typecasted to
any type.It is also referred to as a generic pointer
sometimes.
• Example:
int main()
{
int num = 5;
void *ptr = &num;
printf(“%d”, *ptr);
return 0;
}
Boolean data type:
• In C, Boolean is a data type that contains two types of
values, i.e., 0 and 1.
• Basically, the bool type value represents two types of
behavior, either true or false.
• Here, '0' represents false value, while '1' represents
true value.
• In C Boolean, '0' is stored as 0, and another integer is
stored as 1.
• Syntax:
• bool variable_name;
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool x=false; // variable initialization.
if(x==true) // conditional statements
{
printf("The value of x is true");
}
else
printf("The value of x is FALSE");
return 0;
}
Enumeration data type:
• 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.
• Syntax:
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.
Example:
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday};
int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}
Output:
Day 4
C (PPS)Programming for problem solving.pptx

More Related Content

Similar to C (PPS)Programming for problem solving.pptx (20)

Array.pptx
Array.pptxArray.pptx
Array.pptx
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Session 4
Session 4Session 4
Session 4
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Arrays In General
Arrays In GeneralArrays In General
Arrays In General
 
02 arrays
02 arrays02 arrays
02 arrays
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
Session 7 En
Session 7 EnSession 7 En
Session 7 En
 
Session 7 En
Session 7 EnSession 7 En
Session 7 En
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 

Recently uploaded

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 

Recently uploaded (20)

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 

C (PPS)Programming for problem solving.pptx

  • 1. UNIT-2 Derived data types Content: 1 Array 2 Strings 3 Structures and union 4 Enumeration data type 5 Pointers
  • 3. What is derived data type? • Derived data types are those that are defines in terms of other data types(called base types). • New types may be derived from primitive types. • Why we are using arrays? • Primitive datatypes can hold only one value at a time. • To overcome the disadvantage of primitive data type we use Arrays concept. Array can hold n number of elements at a time.
  • 4. 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 address Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name
  • 5. The types of Arrays 1 One dimensional array 2 Two dimensional array 3 Multi dimensional array
  • 6. One dimensional Array declaration: Syntax: Storageclass dataType arrayname[size]; In C, we can declare an array by specifying its type and size or by initializing it or by both. Storage class is optional.
  • 7. Declaration and Initialization : • Storageclass dataType arrayname[size] = {List of Value}; 1. int arr[10]; // declaration for one dimensional array index 2. int arr[6] = {10, 20, 30, 40,50,60} G.V G.V G.V G.V G.V G.V G.V G.V G.V G.V 10 20 30 40 50 60 0 1 2 3 4 5 6 7 8 9
  • 8. 3. int arr[6]={12,13,14}; 4. int arr[]={5,6,7,8}; 5. Int arr{5}; arr[0]=12; arr[1]=23; arr[2]=40; arr[3]=50; arr[4]=55; 12 13 14 0 0 0 5 6 7 8 12 23 40 50 55 0 1 2 3 4
  • 9. Accessing Array Elements: Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1. Ex1: program for how to assign the array element #include<stdio.h> int main() { int arr[5]; arr[0] = 5; arr[1] = 2; arr[2] = -10; arr[3] = arr[0]; printf("the elements in the array are"); printf(“n %d %d %d %d”, arr[0], arr[1], arr[2], arr[3]); return 0; }
  • 10. 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,num; printf("Enter how many elements want to insert in to the array"); scanf("%d",&num); for ( i = 0; i < num; i++ ) { scanf("%d",&n[i]); } for (j = 0; j < num; j++ ) { printf("Element[%d] = %dn", j, n[j] ); } return 0; }
  • 11. Two – Dimensional Array: • To store tables we need two dimensional arrays. Each table consists of rows and columns. • The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. • Two dimensional arrays are declare as… Syntax: Storageclass datatype arrayname [row-size][col-size];
  • 12. Initializing Two Dimensional Arrays: • They can be initialized by following their declaration with a list of initial values enclosed in braces. Ex:- int table[2][3] = {0,0,0,1,1,1}; • Initializes the elements of first row to zero and second row to one. The initialization is done by row by row. The above statement can be written as int table[2][3] = {{0,0,0},{1,1,1}}; • When all elements are to be initialized to zero, following short-cut method may be used. int m[3][5] = {{0},{0},{0}};
  • 13. • Valid declaration int abc[2][2] = {1, 2, 3 ,4 } • Valid declaration int abc[][2] = {1, 2, 3 ,4 } • Invalid declaration – you must specify second dimension int abc[][] = {1, 2, 3 ,4 } • Invalid because of the same reason mentioned above int abc[2][] = {1, 2, 3 ,4 }
  • 14.
  • 15. How to display the elements from 2d array #include<stdio.h> int main(){ int i=0,j=0; int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; //traversing 2D array for(i=0;i<4;i++) { for(j=0;j<3;j++) { printf("arr[%d] [%d] = %d n",i,j,arr[i][j]); }//end of j }//end of i return 0;
  • 16. How to read and display the elements from 2d array #include <stdio.h> void main () { int arr[3][3],i,j; for (i=0;i<3;i++) { for (j=0;j<3;j++) { printf("Enter a[%d][%d]: ",i,j); scanf("%d",&arr[i][j]); } } printf("n printing the elements ....n"); for(i=0;i<3;i++) { printf("n"); for (j=0;j<3;j++) { printf("%dt",arr[i][j]); } } }
  • 17. Addition of two matrices: #include <stdio.h> int main() { int r, c, a[100][100], b[100][100], sum[100][100], i, j; printf("Enter the number of rows (between 1 and 100): "); scanf("%d", &r); printf("Enter the number of columns (between 1 and 100): "); scanf("%d", &c); printf("nEnter elements of 1st matrix:n"); for (i = 0; i < r; i++) for (j = 0; j < c; j++) { printf("Enter element a%d%d: ", i + 1, j + 1); scanf("%d", &a[i][j]);
  • 18. printf("Enter elements of 2nd matrix:n"); for (i = 0; i < r; i++) for (j = 0; j < c; j++) { printf("Enter element b%d%d: ", i + 1, j + 1); scanf("%d", &b[i][j]); } // adding two matrices for (i = 0; i < r; i++) for (j = 0; j < c; j++) { sum[i][j] = a[i][j] + b[i][j]; }
  • 19. // printing the result printf("nSum of two matrices: n"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { printf("%d ", sum[i][j]); } printf("n"); } return 0; }
  • 20. Multiplication • In order to multiply two matrices, no.of columns of first matrix = no.of rows in second matric formula: • mul[i][j]= mul[i][j]+a[i][k]*b[k][j];
  • 21. 3.Multi-Dimensional Array: • C allows arrays of three or more dimensions. The exact limit is determined by the Compiler. • Syntax: • Storage class datatype array-name[s1][s2][s3][sn]; where s1,s2,… sn is the size of the dimension. Ex:- int Survey[3][5][2];
  • 22.
  • 23. Advantages of Arrays • Arrays represent multiple data items of the same type using a single name. • In arrays, the elements can be accessed randomly by using the index number. • Arrays allocate memory in contiguous memory locations for all its elements. Hence there is no chance of extra memory being allocated in case of arrays. This avoids memory overflow or shortage of memory in arrays.
  • 24. Applications of Arrays 1. Array stores data elements of the same data type. 2. Maintains multiple variable names using a single name. Arrays help to maintain large data under a single variable name. This avoid the confusion of using multiple variables. 3. Arrays can be used for sorting data elements. Different sorting techniques like Bubble sort, Insertion sort, Selection sort etc use arrays to store and sort elements easily. 4. Arrays can be used for performing matrix operations. Many databases, small and large, consist of one-dimensional and two-dimensional arrays whose elements are records. 5. Arrays can be used for CPU scheduling. 6. Lastly, arrays are also used to implement other data structures like Stacks, Queues, Heaps, Hash tables etc.
  • 25.
  • 26. Strings: • 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’).
  • 27. Declaration and initialization: • char c[] =“abcd”; • char c[50] =“ABCD”; • char c[]={‘a’,’b’,’c’,’d’,’0’}; • char c[5]={‘a’,’b’,’c’,’d’,’0’}; • char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’}; (or) • char greeting[] = “Hello”; a B C D 0 A B C D 0
  • 28. 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. The given string is initialized and stored in the form of arrays as below
  • 29. Example1: #include <stdio.h> int main () { char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’}; printf(“Greeting message: %sn”, greeting ); return 0; } Output: Greeting message: Hello
  • 30. Example2: #include <stdio.h> int main () { char name[6] ; printf(“enter your name”); gets(name); Printf(“%s”,name); return 0; } Output: Greeting message: Hello
  • 31. String handling functions: 1. String length 2. String concatenation 3. String copy 4. String comparison 5. String occurrence
  • 32. String Library or Manipulation Function: s.no Function Work of function 1 strcpy(s1, s2); Copies string s2 into string s1. 2 strcat(s1, s2); Concatenates string s2 onto the end of string s1. 3 strlen(s1); Returns the length of string s1. 4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; 6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
  • 33. • strcmp() compares the corresponding characters from both strings based on their ASCII values. • Therefore, if the ASCII value of the first character in the first string is less than the ASCII value of the corresponding character in the second string, strcmp() returns a negative number. • If the ASCII value of the first differing character in the first string is greater than the ASCII value of the corresponding character in the second string, strcmp() returns a positive number.
  • 34. The following example uses some of the above-mentioned functions #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) : %sn”, str3 ); /* concatenates str1 and str2 */ strcat( str1, str2); printf(“strcat( str1, str2): %sn”, str1 ); /* total lenghth of str1 after concatenation */ len = strlen(str1); printf(“strlen(str1) : %dn”, len ); return 0; }
  • 35. The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is used to return substring from first match till the last character. #include <stdio.h> #include<string.h> int main(){ char str[100]="this is c programming lab"; char *sub; sub=strstr(str,“lab"); printf("nSubstring location is: %d",sub-str); return 0; }
  • 36. Array of Strings: Syntax: Datatype arrayname[row-size][col-size]; Example: initialization char cities[4][10]={“pune”,”Mumbai”,”delhi”,”Nagpur”}; • 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.
  • 38. #include <stdio.h> int main() { //declaration char strings[10][100]; int i,n; printf("Enter total number of strings: "); scanf("%d",&n); printf("Enter strings...n"); for(i=0; i<n; i++) { printf("enter String [%d] : ",i+1); scanf("%s",strings[i]); } printf("nStrings are...n"); for(i=0; i<n; i++) { printf("[%d]: %sn",i+1,strings[i]); } return 0; }
  • 39.
  • 40. Structures: • 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
  • 41. 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 structure name { member 1; member 2; ... member m; } variable1, variable2,…., variable n;
  • 42. Here is the way you would declare the Books structure : struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book;
  • 43. Structure variable may be defined as a member of another structure. In that case, the declaration of the embedded structure must appear before the declaration of the outer structure. struct date { int month; int day; int year; } ;
  • 44. struct Books { char title[50]; char author[50]; char subject[100]; int book_id; struct date publishing_date; } book; The second structure (Books) contains another structure(date)as one of the members.
  • 45. Initialization of structure variables: #include<stdio.h> int main() { struct car { char name[100]; float price; }; struct car car1 ={"xyz", 987432.50}; printf("Name of car1 =%sn,car1.name); printf("Price of car1 = %fn",car1.price); return 0; }
  • 46. Accessing Structure Members: • To access any member of a structure, we use the member access operator (.) ie dot operator. • The member access operator is coded as a period between the structure variable name and the structure member (book.title, book.subject,) that we wish to • access. You would use the keyword struct to define variables of structure type.
  • 47. Array of structures • An array of structres in C can be defined as the collection of multiple structures variables where each variable contains information about different entities. The array of structures in C are used to store information about multiple entities of different data types. • The array of structures is also known as the collection of structures.
  • 48.
  • 49. Nested structures: • C provides us the feature of nesting one structure within another structure by using which, complex data types are created. • For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the subparts as street number, city, state, and pin code. Hence, to store the address of the employee, we need to store the address of the employee into a separate structure and nest the structure address into the structure employee.
  • 50. #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; struct employee { char name[20]; struct address add; }; void main () { struct employee emp; printf("Enter employee information?n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone); printf("Printing the employee information....n"); printf("name: %snCity: %snPincode: %dnPhone: %s",emp.name,emp.add.city,em p.add.pin,emp.add.phone); }
  • 51. Unions: • Like Structures, union is a user defined data type. • In union, all members share the same memory location. • Syntax: union Identity { Data members; ….. ….. };
  • 52. Example #include <stdio.h> union test // Declaration of union is same as structures union test { int x, y; }; int main() { test t; // A union variable t union t.x = 2; // t.y also gets value 2 printf (“After making x = 2:n x = %d, y = %dnn”, t.x, t.y); t.y = 10; // t.x is also updated to 10 printf (“After making Y = ‘A’:n x = %d, y = %dnn”, t.x, t.y); return 0; }
  • 53. How is the size of union decided by compiler? Size of a union is taken according the size of largest member in union. #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; }
  • 54.
  • 55. Pointers • Pointers in C language is a variable that stores/points the address of another variable. Syntax: Datatype *var_name; Example : int *p; char *p; Where, * is used to denote that “p” is pointer variable and not a normal variable.
  • 56. Assigning address of a variable to a pointer: • Example Int num=10; Int *ptr; ptr=&num;
  • 57.
  • 58. Points to remember: 1. Normal variable stores the value whereas pointer variable stores the address of the variable. 2. The content of the C pointer always be a whole number i.e. address. 3. Always C pointer is initialized to null, i.e. int *p = null. 4. & symbol is used to get the address of the variable. 5. * symbol is used to get the value of the variable that the pointer is pointing to. 6. If a pointer in C is assigned to NULL, it means it is pointing to nothing. 7. Two pointers can be subtracted to know how many elements are available between these two pointers. 8. But, Pointer addition, multiplication, division are not allowed. 9. The size of any pointer is 2 byte (for 32 bit compiler).
  • 59. Example #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); printf("n %u ",ptr); return 0; }
  • 60. Pointer to an array: datatype array[size]; datatype *pointer = array; Example: int arr[5] = {1, 2, 3,4,5}; int *p = arr;
  • 62. Example: #include<stdio.h> void main() { int arr[5] = {1, 2, 3,4,5}; int *p = arr; for (int i = 0; i < 3; i++) { printf("%d", *p); p++; } return 0; }
  • 63. #include <stdio.h> int main () { double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; /* an array with 5 elements */ double *p; int i; p = balance; printf( "Array values using pointern"); /* output each array element's value */ for ( i = 0; i < 5; i++ ) { printf("*(p + %d) : %fn", i, *(p + i) ); } printf( "Array values using balance as addressn"); for ( i = 0; i < 5; i++ ) { printf("*(balance + %d) : %fn", i, *(balance + i) ); } return 0; }
  • 64. Array of pointer: Like an array of variables, we can also use array of pointers in c. Syntax: datatype *variablename[size]; Example: Int *ptr[10]; Float *ptr[5]; Char *ptr[6];
  • 65. 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:
  • 66. #include<stdio.h> const int SIZE = 3; void main() { int arr[] = { 1, 2, 3 }; int i, *ptr[SIZE]; // we can make an integer pointer array to storing the address of array elements for (i = 0; i < SIZE; i++) { ptr[i] = &arr[i]; // assigning the address of integer. } // printing values using pointer for (i = 0; i < SIZE; i++) { printf("Value of arr[%d] = %dn", i, *ptr[i]); } }
  • 67. Pointer to Structure: Structure can be created and accessed using pointers. A pointer variable of a structure can be created as below: struct name { member1; member2; …. …. }; int main() { struct name *ptr; }
  • 68.
  • 69. #include<stdio.h> struct student{ int sno; char sname[30]; float marks; }; main ( ){ struct student s; struct student *st; printf("enter sno, sname, marks:"); scanf ("%d%s%f", & s.sno, s.sname, &s. marks); st = &s; printf ("details of the student are"); printf ("Number = %dn", st ->sno); printf ("name = %sn", st->sname); printf ("marks =%fn", st ->marks); }
  • 70. Self Referential Structures: • Self Referential structures are those structures that have one or more pointers that point to the same type of structure, as their member. (or) • When structure member points to itself then this type of the structure is called Self Referential Structures.
  • 71. 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.
  • 72. Types of pointers: There are various types of pointer in C, we have 4 different types of pointers in C. They are as follows 1) Void pointer 2) Null pointer 3) Wild pointer 4) Dangling pointer
  • 73. • 1) Void pointer • A pointer is said to be void when a pointer has no associated data type with it. In other words, it can point to any data type and also, it can be typecasted to any type.It is also referred to as a generic pointer sometimes. • Example: int main() { int num = 5; void *ptr = &num; printf(“%d”, *ptr); return 0; }
  • 74.
  • 75. Boolean data type: • In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. • Basically, the bool type value represents two types of behavior, either true or false. • Here, '0' represents false value, while '1' represents true value. • In C Boolean, '0' is stored as 0, and another integer is stored as 1. • Syntax: • bool variable_name;
  • 76. #include <stdio.h> #include<stdbool.h> int main() { bool x=false; // variable initialization. if(x==true) // conditional statements { printf("The value of x is true"); } else printf("The value of x is FALSE"); return 0; }
  • 77. Enumeration data type: • 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. • Syntax: enum flag { constant1, constant2, constant3, };
  • 78. • 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.
  • 79. Example: #include <stdio.h> enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; int main() { // creating today variable of enum week type enum week today; today = Wednesday; printf("Day %d",today+1); return 0; } Output: Day 4