0% found this document useful (0 votes)
21 views98 pages

Unit 2 PPT-1

Uploaded by

yashasarda27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views98 pages

Unit 2 PPT-1

Uploaded by

yashasarda27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 98

Unit-2

Arrays
Introduction
• We have used fundamental data types namely char, int, float which
are very useful.
• But the variable of these types stores only one value at a given
time.
• In various applications, we need to handle large amount of data in
terms of reading, processing and printing.
• To process such data we require a data type that would facilitate
efficient storing, accessing and manipulation of data items.
• C supports a derived data type known as array.
• An array is a fixed-size sequenced collection of elements of the
same data type.
• An array can also be defined as follows...
• An array is a collection of similar data items stored in continuous
memory locations with single name.
• Examples:
– List of numbers: Test scores of a class of students.
– List of names: list of employees in a company.
• Array provides a convenient structure for representing data, so it is
classified as data structures in C.
• For example, we can use array name salary to represent a set of salaries of
a group of employees in an organization.
• To refer to the individual salaries by writing a number called index or
subscript in brackets after the array name.

elements salary

18000 25000 30000 32000 ... ...

0 1 2 3 ... ...

• salary[2] represents the salary of 3rd employee


• This enables us to develop concise and efficient programs.
Types of arrays
• Arrays not only represent lists of values but also tables of data in 2,
3 or more dimensions.
• Types of arrays:
– One dimensional arrays
– Two dimensional arrays
– Three dimensional arrays
One dimensional array
• It is a list of items can be given one variable name using only one
subscript.
• Ex: array of five numbers (15,8,84,14,29) represented with a variable
name number:
int number[5];
Array elements
Five storage locations are assigned

number[0] = 15;
number[0]
number[1] = 8;
number[1]
number[2] number[2] = 84;
number[3] number[3] =14;
number[4] number[4] =29;
Declaration of 1-D array
• Array declaration
type variable_name[ size ];

Type of elements
that will be in array Maximum number of elements
stored inside the array
float height[50];
int group[4*5];

• The size should be a numeric constant or constant expression.


• C language treats character strings as arrays of characters.

• The size in the string represents the maximum number of


characters that the string can hold. ‘w’ name[0]

char name[10]=“well done”; ‘e’ name[1]


‘l’ name[2]
• If name holds the string ‘well done’ then each character of
‘l’ name[3]
string is treated as element.
‘‘ name[4]
• Character string terminate with null character ‘\0’. Thus ‘d’ name[5]
name[9] holds null character. ‘o’ name[6]
‘n’ name[7]
• So extra space for null character should be allowed.
‘e’ name[8]
‘\0’ name[9]
Memory allocation of an array
#include<stdio.h>
void main()
{
int a[]={25,23,21,42};
int i;
for(i=0;i<4;i++)
{
printf("a[%d]=%d\n",i,a[i]);
printf("adress=%u\n",&a[i]);
}
}
Initialization
• After array is declared its variables are to initialized.
• An array can be initialized at either of the following stages:
– At compile time
– At run time

Compile time initialization


type array_name[size] = {list of values};
int number[3] = {54,99,12};
• Remaining elements initialized to zero or NULL.

int num[10] = {1,5,8};


float total[5] = {0.5,15.8,-10};
char[8] = {‘n’, ‘i’, ‘k’};
• Enough space for initialized variable

int counter[] = {1,1,1};

char name[] = {‘M’, ‘i’, ‘c’, ‘k’, ‘y’, ‘\0’};

char name[] = “Micky”;


• Compile time initialization may be partial. That is number of elements may
be less than declared size.
• In such cases remaining elements are initialized to zero, if the array type is
number and NULL if the type is char.

int number [2] = {10,20,30};


• If the initializers are more than the declared size, the compiler will
produce error.
#include<stdio.h>
void main()
{
int i,number[10]={1,5,8};
float num[5]={0.5,15.8,-10};
char name[8]={'n','i','k'};
for(i=0;i<10;i++)
{
printf("number[%d] = %d\n",i,number[i]);
}
for(i=0;i<5;i++)
{
printf("num[%d] = %f\n",i,num[i]);
}
for(i=0;i<8;i++)
{
printf("name[%d] = %c\n",i,name[i]);
}
}
Run time initialization
• scanf is used to initialize an array.

int marks[2];
scanf(“%d %d %d”, &marks[0], &marks[1]);
• It initializes the array elements with values entered through the
keyboard.
Read and display array elements
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5], i;
printf(“enter array elements:”);
for(i = 0; i < 5; i++)
{
scanf("%d", &arr[i]);
}
printf("\nPrinting elements of the array: \n\n");
for(i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
getch();
}
Program to find average marks obtained by 10 students in a test
#include<stdio.h>
void main()
{
int sum=0, avg, i, marks[10];
for(i=0;i<10;i++)
{
printf("Enter marks:");
scanf("%d",&marks[i]); or scanf("%d",(marks+i));
}
for(i=0;i<10;i++)
{
sum=sum+ marks[i]); or sum=sum+ *(marks+i);
}
avg=sum/10;
printf("\nAverage marks= %d\n", avg); or printf("\nAverage marks= %d\n", sum/10);
}
Notations for retrieving array elements

#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={25,23,21,42};
int i;
clrscr();
for(i=0;i<4;i++)
{
printf("address=%u, ",&a[i]);
printf("a[%d]=%d %d %d %d \n",i,a[i], *(a+i), *(i+a), i[a]);
}
getch();
}
2-Dimensional array
• Two dimensional array is called a matrix.
• Declaration: columns

type array_name [rows][cols];

rows

Ex: int student_marks[4][2];


– int  specifies type of element in each slot
– student_marks  specifies name of the array
– [4]  specifies number of rows
– [2]  specifies number of columns
Initialization of 2-D array
• Initialization at the time of declaration.

int stud[4][2] = { {101,56}, {102,80},{103,33},{104,78}};


int stud[4][2] = { 101,56, 102,80,103,33,104,78};

Number of rows Number of columns

• Column dimension is necessary and row dimension is optional.


• In the declaration of two dimensional array the column size should be
specified, to that it can arrange the elements in the form of rows and
columns.
• int stud[4][2] = { {101,56}, {102,80},{103,33},{104,78}};
Col 0 Col 1

Row 0 101 56

Row 1 102 80

Row 2 103 33

Row 3 104 78

• 2-d array is collection of a number of 1-d arrays placed one below


the other conceptually.
• A 1-d or a 2-d array elements are stored in one continuous chain.

stud[0][0] stud[0][1] stud[1][0] stud[1][1] stud[2][0] stud[2][1] stud[3][0] stud[3][1]


101 56 102 80 103 33 104 78
65508 65510 65512 65514 65516 65518 65520 65522
Basic program to initialize array, print the array
elements and its respective address
#include<conio.h>
void main()
{
int students[4][2]={101,88,102,97,103,65,104,85};
int i,j;
clrscr();
for(i=0;i<4;i++)
for(j=0;j<2;j++)
{
printf("students[%d][%d] = %d”, i,j,students[i][j]);
printf(“ address = %u\n", &students[i][j]);
}
getch();
}
Read and display 2-D array
#include<stdio.h> for(i=0; i<row; i++)
#include<conio.h> {
void main() for(j=0; j<col; j++)
{ {
int arr[10][10], row, col, i, j; printf("%d ",arr[i][j]);
clrscr(); }
printf("Enter number of row for Array (max 10) : printf("\n");
"); }
scanf("%d",&row); getch();
printf("Enter number of column for Array (max }
10) : ");
scanf("%d",&col);
printf("Now Enter %d*%d Array Elements :
",row, col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("The Array is :\n");
Output
• Each row of 2-d array can be though of as a 1-d array. (important
fact)
• Ex: int s[4][2];
• Four 1-d arrays with 2 elements each
• We refer 1-d array using a single subscript
• If we imagine s as 1-d array then we can refer elements as s[0],
s[1],.. So on.
• s[0] gives address of zeroth 1-d array, s[1] gives address of first 1-d
array and so on.

s[0][0] s[0][1] s[1][0] s[1][1] s[2][0] s[2][1] s[3][0] s[3][1]


101 56 102 80 103 33 104 78
65508 65510 65512 65514 65516 65518 65520 65522

• Now we are able to reach each 1-d array.


Program to show how 2-D array is stored
#include<conio.h>
void main()
{
int s[4][2]={101,88,102,76,103,54,104,46};
clrscr();
printf("Base Address = %u\n",s);
printf("zeroth 1-d address = %u\n",s[0]);
printf("first 1-d address = %u\n",s[1]);
printf("second 1-d address = %u\n",s[2]);
printf("third 1-d address = %u\n",s[3]);
getch();
}
s[0][0] s[0][1] s[1][0] s[1][1] s[2][0] s[2][1] s[3][0] s[3][1]
101 88 102 76 103 54 104 46
65510 65510 65512 65514 65516 65518 65520 65522
Addition of two matrices
#include<conio.h> printf("\nMatrix 2:\n");
void main() for(i=0; i<3; i++)
{ {
int mat1[3][3], mat2[3][3], mat3[3][3], i, j, k; for(j=0; j<3; j++)
clrscr(); {
printf("Enter first matrix element (3*3) : "); printf("%2d ",mat2[i][j]);
for(i=0; i<3; i++) }
for(j=0; j<3; j++) printf("\n");
scanf("%d",&mat1[i][j]); }
printf("Enter second matrix element (3*3) : "); //Addition of 2 matrices
for(i=0; i<3; i++) printf("\nsum matrix:\n");
for(j=0; j<3; j++) for(i=0; i<3; i++)
scanf("%d",&mat2[i][j]); for(j=0; j<3; j++)
printf("\nMatrix 1:\n"); mat3[i][j]=mat1[i][j]+mat2[i]
for(i=0; i<3; i++) [j];
{ //print sum matrix
for(j=0; j<3; j++) for(i=0; i<3; i++)
{ {
printf("%2d ",*(*(mat1+i) for(j=0; j<3; j++)
+j)); {
} printf("%2d ",mat3[i][j]);
printf("\n"); }
} printf("\n");
}
getch();
}
Output
Multiplication of 2 matrices
#include<conio.h> printf("Enter second matrix (%d*%d) : ",p,q);
void main() for(i=0; i<p; i++)
{ for(j=0; j<q; j++)
int mat1[5][5], mat2[5][5], mat3[5][5], i, j, k, m, scanf("%d",&mat2[i]
n, p, q; [j]);
clrscr(); printf("\nMatrix 1:\n");
printf("Enter first matrix dimensions: "); for(i=0; i<m; i++)
scanf("%d %d",&m, &n); {
printf("Enter second matrix dimensions: "); for(j=0; j<n; j++)
scanf("%d %d", &p, &q); printf("%2d ",mat1[i]
if(n!=p) [j]);
{ printf("\n");
printf("Enter valid dimensions\n"); }
exit(); printf("\nMatrix 2:\n");
} for(i=0; i<p; i++)
printf("Enter first matrix (%d*%d) : ",m,n); {
for(i=0; i<m; i++) for(j=0; j<q; j++)
for(j=0; j<n; j++) printf("%2d ",mat2[i]
scanf("%d",&mat1[i] [j]);
[j]); printf("\n");
}
//Multiplication of 2 matrices
printf("\nMultiplication matrix:\n");
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
mat3[i][j]=0;
for(k=0; k<n; k++)
mat3[i][j] = mat3[i][j]+mat1[i][k] *mat2[k][j];
}
}
//print Multiplied matrix
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
printf("%2d ",mat3[i][j]);
}
printf("\n");
}
getch();
}
Transpose of a matrix
#include<conio.h> for(i=0; i<3; i++)
void main() {
{ for(j=0; j<3; j++)
int mat1[3][3], mat2[3][3], i, j; {
clrscr(); mat2[i][j]=mat1[j][i];
printf("Enter first matrix element (3*3) : "); }
for(i=0; i<3; i++) }
{ //print transpose matrix
for(j=0; j<3; j++) printf(“\nTranspose Matrix:\n”);
{ for(i=0; i<3; i++)
scanf("%d",&mat1[i][j]); {
} for(j=0; j<3; j++)
} {
printf("\nMatrix 1:\n"); printf("%2d ",mat2[i][j]);
for(i=0; i<3; i++) }
{ printf("\n");
for(j=0; j<3; j++) }
{ getch();
printf("%2d ",mat1[i][j]); }
}
printf("\n");
}
//Transpose of matrix 1
Output
#include<conio.h> for(i=0; i<2; i++)
void main() {
{ for(j=0; j<3; j++)
int mat1[3][2], mat2[2][3], i, j; {
clrscr(); mat2[i][j]=mat1[j][i];
printf("Enter first matrix element (3*2) : "); }
for(i=0; i<3; i++) }
{ //print transpose matrix
for(j=0; j<2; j++) printf("\nTranspose Matrix:\n");
{ for(i=0; i<2; i++)
scanf("%d",&mat1[i][j]); {
} for(j=0; j<3; j++)
} {
printf("\nMatrix 1:\n"); printf("%2d ",mat2[i][j]);
for(i=0; i<3; i++) }
{ printf("\n");
for(j=0; j<2; j++) }
{ getch();
printf("%2d ",mat1[i][j]); }
}
printf("\n");
}
//Transpose of matrix 1
Output
Program to find trace of a matrix
#include<conio.h> printf("%2d ",mat1[i][j]);
void main() }
{ printf("\n");
int mat1[3][3], i, j, sum; }
clrscr(); //Trace of matrix 1
sum=0; for(i=0; i<3; i++)
printf("Enter first matrix element (3*3) : "); {
for(i=0; i<3; i++) sum=sum+mat1[i][i];
{ }
for(j=0; j<3; j++) //print trace matrix
{ printf(“\nTrace of Matrix1 = %d\n”, sum);
scanf("%d",&mat1[i][j]); getch();
} }
}
printf("\nMatrix 1:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
Output
Program to find normal of a matrix
#include <stdio.h> }
#include <math.h> printf("\nMatrix :\n");
void main () for(i=0; i<m; i++)
{ {
int array[10][10]; for(j=0; j<n; j++)
int i, j, m, n, sum , normal; {
clrscr(); printf("%2d ",array[i][j]);
sum=0; sum=sum+ array[i][j] * array[i][j];
printf("Enter the order of the matrix\n"); }
scanf("%d %d", &m, &n); printf("\n");
printf("Enter the elements of the matrix \ }
n"); normal = sqrt(sum);
for (i = 0; i < m; ++i) printf("The normal of the matrix is =
{ %d\n", normal);
for (j = 0; j < n; ++j) getch();
{
scanf("%d", &array[i][j]); }
}
Output
Applications of arrays
• Arrays are used to Store List of values
– In c programming language, single dimensional arrays are used
to store list of values of same datatype. In other words, single
dimensional arrays are used to store a row of values. In single
dimensional array data is stored in linear form.
• Arrays are used to Perform Matrix Operations
– We use two dimensional arrays to create matrix. We can
perform various operations on matrices using two dimensional
arrays.
• Arrays are used to implement Search Algorithms
– We use single dimensional arrays to implement search
algorihtms like ...
• Linear Search
• Binary Search
• Arrays are used to implement Sorting Algorithms
– We use single dimensional arrays to implement sorting
algorihtms like ...
• Insertion Sort
• Bubble Sort
• Selection Sort
• Quick Sort
• Merge Sort, etc.,
• Arrays are used to implement Data structures
– We use single dimensional arrays to implement datastructures
like...
• Stack Using Arrays
• Queue Using Arrays
• Arrays are also used to implement CPU Scheduling Algorithms
Strings
• Similar to integer array, a group of characters can be stored in a
character array.
• Strings are used to manipulate text such as words and sentences.
• A string constant is a 1-d array of characters terminated by a null
character ‘\0’.
char name[] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};
• The elements of character array are stored in contiguous memory
locations.

H E L L O \0
65520 65521 65522 65523 65524 65525
Memory allocation of character array
#include<conio.h>
void main()
{
char name[]= { 'H', 'E', 'L', 'L', 'O', '\0'};
int i=0;
clrscr();
while(i<5)
{
printf("'%c' = %u\n", name[i], &name[i]);
i++;
}
getch();
}
• while loop condition i<5 can be replaced by name[i]!=‘\0’ as each
character array always ends with a ‘\0’.
• C provides a shortcut to declare a string
• Ex: char name[] = “HELLO”;
• ‘\0’ is not required, C inserts the null character automatically.
• The %s used in printf() is a format specification for printing out a
string.
• The same specification can be used to receive a string from
keyboard using scanf().
String accessing
#include<conio.h>
void main()
{
char name[]= "HELLO", name2[10]; \\ sets aside 10 bytes under the array name2
int i=0;
clrscr();
printf("\n");
while(name[i]!='\0')
{
printf("%c", name[i]);
i++;
}
printf("\nEnter your name: ");
scanf("%s", name2); \\ fills in the characters until enter key is hit then places ‘\0’ in the array
printf("Your name is %s.\n",name2);
getch();
}
• While entering the string using scanf()
– Length of the string should not exceed the dimension of he
character array. Since compiler doesn’t perform bound checking.
– scanf() is not capable of receiving multi-word strings. Therefore,
names such as ‘Michel Jackson’ would be unacceptable.
• String I/O functions in C
– gets() is used to receive multi-word strings from keyboard.
– puts() is used to print multi-word strings.
A program to show how gets() and puts() functions are used

#include<conio.h>
void main()
{
char name[20];
clrscr();
printf("Enter your name: ");
gets(name);
puts("Hello!");
puts(name);
getch();
}
String Functions
• C provides a wide range of string functions for
performing different string tasks
• Examples
strlen(str) - calculate string length
strcpy(dst,src) - copy string at src to dst
strcmp(str1,str2) - compare str1 to str2
• Functions come from the utility library string.h
– #include <string.h> to use
String Length
Syntax: int strlen(char *str)
returns the length (integer) of the string argument
counts the number of characters until an \0 encountered
does not count \0 char
Example:
char str1 = “hello”;
X=strlen(str1) //x is 5
Copying a String
Syntax:
char *strcpy(char *dst, char *src)
copies the characters (including the \0) from the source string (src)
to the destination string (dst)
dst should have enough space to receive entire string (if not, other
data may get written over)
if the two strings overlap (e.g., copying a string onto itself) the
results are unpredictable
return value is the destination string (dst)
char *strncpy(char *dst, char *src, int n)
similar to strcpy, but the copy stops after n characters
if n non-null (not \0) characters are copied, then no \0 is copied
String Comparison
Syntax:
int strcmp(char *str1, char *str2)
compares str1 to str2, returns a value based on the first character
they differ at:
less than 0
if ASCII value of the character they differ at is smaller for str1
or if str1 starts the same as str2 (and str2 is longer)
greater than 0
if ASCII value of the character they differ at is larger for str1
or if str2 starts the same as str1 (and str1 is longer)
0 if the two strings do not differ
String Comparison (cont)
strcmp examples:
strcmp(“hello”,”hello”) -- returns 0
strcmp(“yello”,”hello”) -- returns value > 0
strcmp(“Hello”,”hello”) -- returns value < 0
strcmp(“hello”,”hello there”) -- returns value < 0
strcmp(“some diff”,”some dift”) -- returns value < 0
expression for determining if two strings s1,s2 hold the
same string value:
!strcmp(s1,s2)
String Comparison (cont)
Sometimes we only want to compare first n chars:
int strncmp(char *s1, char *s2, int n)
Works the same as strcmp except that it stops at the
nth character
looks at less than n characters if either string is shorter than
n
strcmp(“some diff”,”some DIFF”) -- returns value > 0
strncmp(“some diff”,”some DIFF”,4) -- returns 0
String Comparison (ignoring case)
Syntax:
int strcasecmp(char *str1, char *str2)
similar to strcmp except that upper and lower case characters (e.g.,
‘a’ and ‘A’) are considered to be equal
int strncasecmp(char *str1, char *str2, int n)
version of strncmp that ignores case
String Concatenation
Syntax:
char *strcat(char *dstS, char *addS)
appends the string at addS to the string dstS (after dstS’s delimiter)
returns the string dstS
can cause problems if the resulting string is too long to fit in dstS
char *strncat(char *dstS, char *addS, int n)
appends the first n characters of addS to dstS
if less than n characters in addS only the characters in addS
appended
always appends a \0 character
Searching for a Character/String
Syntax:
char *strchr(char *str, int ch)
returns a pointer (a char *) to the first occurrence of ch in str
returns NULL if ch does not occur in str
can subtract original pointer from result pointer to determine which
character in array
char *strstr(char *str, char *searchstr)
similar to strchr, but looks for the first occurrence of the string
searchstr in str
char *strrchr(char *str, int ch)
similar to strchr except that the search starts from the end of string
str and works backward
String Spans (Searching)
• Syntax: int strspn(char *str, char *cset)
– specify a set of characters as a string cset
– strspn searches for the first character in str that is not part of
cset
– returns the number of characters in set found before first non-
set character found
• Syntax: int strcspn(char *str, char *cset)
– similar to strspn except that it stops when a character that is
part of the set is found
• Examples:
– strspn(“a vowel”,”bvcwl”) returns 2
– strcspn(“a vowel”,”@,*e”) returns 5
String functions
• strlen()
– Counts the number of characters in the string.
– Ex:
char array[] = “Dhoni”;
int len1, len2;
len1 = strlen(array);
len2 = strlen(“Pawan Kalyan”);
• strcpy()
– Copies the contents of one string into another.
– The base addresses of the source and target strings should be supplied
to this function.
– Ex:
char source[]= “Monalisa”;
char target[20];
strcpy (target , source);
A program to illustrate strlen() and strcpy()
#include<conio.h>
#include<string.h>
void main()
{
char arr1[] = "Hello";
char source[] = "Monalisa", target[20];
int l1, l2;
clrscr();
l1=strlen(arr1);
l2=strlen("Pawan Kalyan");
printf("\nLength of '%s' = %d", arr1, l1);
printf("\nLength of 'Pawan kalyan' = %d", l2);
strcpy(target, source);
printf("\nSource =");
puts(source);
printf("\nTarget = ");
puts(target);
getch();
}
• strcat()
– Concatenates the source string at the end of the target string.
– Ex: “Gabbar” and “Singh” on concatenation becomes
“GabbarSingh”.
• strcmp()
– This function compares 2 strings to find out whether they are
same or different.
– 2 strings are compared char by char until there is a mismatch or
end of the one the strings is reached (whichever occurs first).
– If 2 strings are identical then this function returns zero.
– Else it returns the numeric difference between the ASCII values
of he first non-matching pair of char.
A program to illustrate strcat() and strcmp()
#include<stdio.h>
#include<string.h>
void main()
{
char source[] = "Hello";
char target[] = "Monalisa";
char str1[]="Jerry";
char str2[]="Ferry";
int i, j ,k;
printf("Source = %s \n", source);
strcat(target, source);
printf("Target = %s \n", target);
i=strcmp(str1, "Jerry");
j=strcmp(str1,str2);
k=strcmp(str1,"Jerry boy");
printf("\n %d %d %d\n", i, j, k);
}
String/Data Conversion

#include<stdio.h>
void main()
{
//atoi: alphabet to integer
char str[]="2019";
Output:
//str=str+3;
Year: 2022
int yr = atoi(str); 101000001
yr = yr+3; 1
printf("Year: %d\n",yr);
//itoa: integer to alphabet
int num = 321;
char snum[20];
itoa(num, snum, 2);
printf("%s\n", snum);
printf("%c ",snum[2]);
}
C - scanf() and sprintf() function

Formatted functions Description

The sscanf() function reads the values from a


char[] array and store each value into
sscanf()
variables of matching data type by specifying
the matching format specifier.

The sprintf() function reads the one or


multiple values specified with their
sprintf()
matching format specifiers and store these
values in a char[] array.
Example program
#include<stdio.h>
void main()
{
char a[20] = "31 10 2019", b[20];
int day,month,year;
printf("%s\n",a);
sscanf(a,"%d %d %d",&day, &month, &year);
printf("Today's date: %d %d %d\n", day, month,year);
int d=24,m=1,y=2022;
Output:
sprintf(b, "%d|%d|%d",d,m,y);
31 10 2019
printf("Today's date: %s\n",b); Today's date: 31 10 2019
} Today's date: 24|1|2022
Structures and Unions
Introduction
• A variable stores a value, array stores a collection of elements of
same datatype.
• But we often deal with entities that are collection of dissimilar data
types.
• Example: A book data
Name (string)
Price (float)
Number of pages (int)
– Storing 3 books data in arrays:
• Storing names in string of arrays
• Storing prices in a float array
• Storing number of pages in an int array
Name Anci C Outline of Programming Let us C
with C
0 1 2

Price 520.00 1050.00 450.00


0 1 2

Number of pages 1000 520 656


0 1 2

• If we handle this example with array it is difficult to handle the


number of arrays for a single book data.
• We have a special data type called structure
What is a structure?
• In structure, a number of data • Example:
types grouped together. struct book
• These data types may or may not {
be of same type. char name[25];
• Declaring a structure: float price;
struct struct_name int pages;
{ };
datatype element1; struct book b1,b2,b3;
datatype element2; or
…. struct book
…. {
};
char name[25];
struct struct_name s1,s2,s3;
float price;
int pages;
} b1, b2, b3;
• Initialization of a structure:
struct book
{
char name[10]; b1.name b1.price b1.pages
float price; basic 150.50 520
65510 65520 65524
int pages;
};
struct book b1 = {“basic”, 150.50, 520};
struct b3 = {0};

• Closing brace in structure type declaration must be followed by semicolon.


• Structure type declaration does not reserve any space in memory. It
defines the ‘form’ of the structure.
• If a structure variable is initiated to a value {0}
– all its int and float elements are set to value 0
– And char elements are set to ‘\0’.
Program to illustrate accessing of structure elements and memory map
of structure elements
#include<conio.h> printf("Pages= %d : %u\n", b1.pages,
void main() &b1.pages);
{
struct book printf("\nBook 2 details\n");
{ printf("Name= %s\n", b2.name);
char name[10]; printf("Price= %f\n", b2.price);
float price; printf("Pages= %d\n", b2.pages);
int pages; getch();
}; }
struct book b1 = { "BasicC", 150.50,
520};
struct book b2 = {0};
clrscr();
printf("Size of the structure = %d\n",
sizeof(b1));
printf("\nBook 1 details\n");
printf("Name= %s : %u\n", b1.name,
&b1.name);
printf("Price= %f : %u\n", b1.price,
&b1.price);
Program to illustrate nested structure
#include<conio.h> strcpy(emp.dept, "Accounts");
struct Employee emp.age=48;
{ emp.allowance.basic=5000;
int eid; emp.allowance.da=1000;
char ename[15]; emp.allowance.hra=1500;
char dept[10]; printf(" ID:%d\n Name:%s\n Dept:%s\n Age:
int age; %d\n", emp.eid, emp.ename, emp.dept,
struct salary emp.age);
{ printf(" Basic Salary:%d\n DA:%d\n HRA:%d\
n", emp.allowance.basic, emp.allowance.da,
int basic;
emp.allowance.hra);
int da;
getch();
int hra;
}
}allowance;
};
void main()
{
struct Employee emp;
clrscr();
emp.eid=121;
strcpy(emp.ename, "Raghu");
Program to illustrate array of structure
#include<conio.h> {
struct Student sptr++;
{ if(sptr->age > maxage)
char name[10]; {
int rno; maxage=sptr->age;
int age; sptr1 = sptr;
}; }
void main() }
{ printf("\n%s is the elder student with age= %d\n",
struct Student class[5]; sptr1->name, maxage);
struct Student *sptr, *sptr1; getch();
int i, maxage=0; }
clrscr();
for(i=0; i<5; i++)
{
printf("Enter name of student: ");
scanf("%s", class[i].name);
printf("Enter Roll no.: ");
scanf("%d", &class[i].rno);
printf("Enter age: ");
scanf("%d", &class[i].age);
}
sptr=class;
maxage = sptr->age;
for(i=1; i<5 ; i++)
union
• Like structure, union in c language is a user-defined
data type that is used to store the different type of
elements.
• At once, only one member of the union can occupy
the memory.
• The size of the union in any instance is equal to the
size of its largest element.
Defining union
• The union keyword is used to define the union.
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
• Example to define union for an employee:
union employee
{ int id;
char name[50];
float salary;
};
Program creates a union to employee details and accessing
those details
#include <stdio.h>
#include <string.h>
union employee
{
int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, “sachin tendulkar");
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Union and structure
Advantage of union over structure
• It occupies less memory because it occupies the size of the largest
member only.
Disadvantage of union over structure
• Only the last entered data can be stored in the union. It overwrites
the data previously stored in the union.
Structure vs. Union
typedef
• The typedef is a keyword used in C programming to provide some
meaningful names to the already existing variable in the C program.
• It behaves similarly as we define the alias for the commands.
• typedef is used to redefine the name of an already existing variable.
• Syntax:
typedef <existing_name> <alias_name>;
• Example:
typedef unsigned int unit;
Example program
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
Output:
Value of i is :10
Value of j is :20
Pointers
What is a pointer?
• When we declare a variable, the compiler allocates required
memory with specified name.
• Pointer is a special type of variable used to store the memory
location address of a variable.
• Every pointer stores the address of variable with same datatype
only.
• For declaring a pointer variable
datatype *pointer_name;
• Example:
int *ptr;
• Reference (address of) operator ‘&’ is used to access address of a
variable.
• Initialising a pointer
pointer_name = &varaible_name;
• Example:
int a, *ptr;
a = 10;
ptr = &a;
• Pointer can be used to access value at the address with the use of
‘*’ in front of pointer variable name.
• Memory allocation of pointer variable:
– In computer, memory address of any memory location is
an unsigned integer value, which requires 2 bytes of memory in
C.
– So, irrespective of pointer datatype every pointer variable is
allocated with 2 bytes of memory.
• Can a pointer variable store a constant value?
Program to initialize and access pointers
#include<conio.h>
#define max 10
void main()
{
int a=10;
int *ptr1, *ptr2;
clrscr();
printf("a=%d\n",a);
ptr1=&a;
ptr2=25;
printf("ptr1=%u\n",ptr1);
printf("ptr2=%u\n",ptr2);
printf("value at ptr1=%d\n",*ptr1);
printf("value at ptr2=%d\n",*ptr2);
getch();
}
Pointer to a pointer

• C programming language also provides pointer variable to store the


address of another pointer variable.
• This type of pointer variable is called as pointer to pointer variable.
Sometimes we also call it as double pointer.
datatype **pointer_name;

• To store the address of normal variable we use single pointer


variable
• To store the address of single pointer variable we use double
pointer variable
• To store the address of double pointer variable we use triple pointer
variable
• Similarly the same for remaining pointer variables also.
Program to illustrate pointer to a pointer
#include<conio.h>
#define max 10
void main()
{
int a=10;
int *ptr1, **ptr2;
clrscr();
printf("a=%d\n",a);
ptr1=&a;
printf("accessing ptr1\n");
printf("address of a = %u\n",ptr1);
printf("value of a =%d\n",*ptr1);
printf("address of pointer ptr1=%u\n",&ptr1);
ptr2 = &ptr1;
printf("Accessing ptr 2\n");
printf("address of ptr1 = %u\n",ptr2);
printf("address of a = %u\n",*ptr2);
printf("value of a = %d \n", **ptr2);
getch();
}
Pointer operations
• In c programming language, we can perform the
following arithmetic operations on pointers:
– Addition of a constant
– Subtraction of a constant
– Increment
– Decrement
Program to illustrate pointer operations
#include<stdio.h> ptr++;
#include<conio.h> printf("After incrementation = %u\n",
void main() ptr);
{ ptr--;
int i=5, *ptr; printf("After decrementation = %u\
clrscr(); n", ptr);
printf("value of i = %d\n", i); getch();
ptr=&i; getch();
printf("address of i = %u\n", ptr); }
ptr=ptr+2;
printf("After addition of 2 = %u\n",
ptr);
ptr=ptr-4;
printf("After substraction of 4 = %u\
n", ptr);
Array of pointers
• “Array of pointers” is an array of the pointer variables. It is
also known as pointer arrays.
• Syntax:
int *var_name[array_size];
• Declaration of an array of pointers:
int *ptr[3];
• We can make separate pointer variables which can point to
the different values or we can make one integer array of
pointers that can point to all the values.
C program to demonstrate example of array of pointers

#include <stdio.h>
const int SIZE = 3;
void main()
{
// creating an array
int arr[] = { 1, 2, 3 };
// we can make an integer pointer array to store the address of array elements
int i, *ptr[SIZE];
for (i = 0; i < SIZE; i++) {
// assigning the address of integer.
ptr[i] = &arr[i];
}
// printing values using pointer Output:
for (i = 0; i < SIZE; i++) { Value of arr[0] = 1
Value of arr[1] = 2
printf("Value of arr[%d] = %d\n", i, *ptr[i]); Value of arr[2] = 3
}
}
void pointer
• Pointer to void is the concept of defining a pointer variable
that is independent of datatype.
• void pointer is a pointer variable used to store the address of
variable of any datatype.
• "void“ keyword is used to create void pointer.
• Declaration:
void *pointer_name ;
Program to illustrate void pointer
#include<conio.h>
int main()
{
int a=10 ;
float b ;
char c ;
void *ptr ;
clrscr() ;
ptr = &a ;
printf("Address of integer variable a = %u\n", ptr) ;
ptr = &b ;
printf("Address of float variable b = %u\n", ptr) ;
ptr = &c ;
printf("Address of character variable c = %u\n", ptr) ;
getch();
return 0;
}
Pointers to arrays
#include<conio.h>
void main()
{
int arr[]={5,10,15,20,25,30};
int i, *ptr;
clrscr();
ptr = &arr[0];
for(i=0;i<6;i++)
{
printf("arr[%d] = %d ",i,*ptr);
printf("address = %u\n",ptr);
ptr++;
}
getch();
}
Program to illustrate accessing 1D array elements using
value at address operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
int i;
clrscr();
printf("Enter 5 integer elements\n");
for(i=0;i<5;i++)
{
scanf("%d", a+i);
}
for(i=0;i<5;i++)
{
printf("address=%u, ",&a[i]);
printf("a[%d]=%d %d %d %d \n", i, a[i], *(a+i), *(i+a), i[a]);
}
getch();
}
Accessing 2-Dimensional arrays using pointers

s[0][0] s[0][1] s[1][0] s[1][1] s[2][0] s[2][1] s[3][0] s[3][1]


101 56 102 80 103 33 104 78
65508 65510 65512 65514 65516 65518 65520 65522

• To refer to individual elements of 2-d array:


– Consider s[2][1]
– third 1-d array address is obtained by s[2] that is
65516
– So 65516+1 or s[2]+1 gives the address 65518.
– The value at this address is *(s[2]+1) or *(*(s+2)+1))
Read and display 2-D array
#include<conio.h>
void main()
{
int mat1[3][3], i, j;
clrscr();
printf("Enter first matrix element (3*3) : ");
for(i=0; i<3; i++)
for(j=0; j<3; j++)
scanf("%d",&mat[i][j]);
printf("\nMatrix 1:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf("%2d ",*(*(mat1+i)+j));
printf("\n");
}
}
Program to illustrate strings with pointers
#include<conio.h>
void main()
{
char str[] = "Hello";
char str1[10];
char *str2 = "Monalisa", *str3, *str4;
clrscr();
printf("Str = %s\n",str);
//str1=str; //error
//str1="hai"; //error
str3="hai";
printf("Str3 = %s\n",str3);
str4=str2;
printf("Str4 = %s\n",str4);
getch();
}
Program to illustrate structure with pointers
#include<stdio.h> strcpy(S.name,"Mounica");
#include<string.h> S.age=20;
struct Student //printf("Address of student
{ Structure: %u\n",&S.name);
char name[10]; printf("student 1 details using
int rno; pointer:\n");
int age; printf("Name= %s \nRoll no.= %d\
nage= %d\n", sptr->name, sptr-
};
>rno, sptr->age);
void main()
{
//printf("\nAddress of student
struct Student S; structure = %u",sptr);
struct Student *sptr; }
sptr = &S;
sptr->rno=125;
Self Referential Structure
• Structure that have one or more pointers which points to
the same type of structure, as their member is known as
self referential structure.
• Syntax:
struct struct_name
{
datatype var_name;
struct struct_name *pointer_name;
}
Single linked list
//Self referential structure (single linked list)
#include<stdio.h>
struct node
{
int data;
struct node *link;
};
void main()
{
struct node obj1;
//object 1 creation
obj1.data=20;
obj1.link=NULL;
printf("Object 1: %d %d\n",obj1.data,obj1.link);//20 0
//Object 2 creation
struct node obj2;
obj2.data=30;
obj2.link=NULL;
obj1.link=&obj2; //linking object 1 and object 2
printf("Object 1 (after creating object 2): %d %d\n",obj1.data,obj1.link);//20 address
printf("Object 2: %d %d\n",obj1.link->data,obj1.link->link);//30 0
}
Double linked list
//Self referential structure (doubly linked list) struct node obj3;
#include<stdio.h> obj3.data=40;
struct node obj3.prevlink=NULL;
{ obj3.nextlink=NULL;
struct node *prevlink;
int data; //Linking nodes
struct node *nextlink; obj1.nextlink=&obj2;
}; obj2.nextlink=&obj3;
void main()
{ obj2.prevlink=&obj1;
//object 1 creation obj3.prevlink=&obj2;
struct node obj1;
obj1.data=20; printf("3 Object data using object 1:\n");
obj1.prevlink=NULL; printf("%d %d %d\n",obj1.data,obj1.nextlink->data,
obj1.nextlink=NULL; obj1.nextlink->nextlink->data);

//Object 2 creation printf("3 Object data using object 2:\n");


struct node obj2; printf("%d %d %d\n",obj2.prevlink->data,obj2.data,
obj2.data=30; obj2.nextlink->data);
obj2.prevlink=NULL;
obj2.nextlink=NULL; printf("3 Object data using object 3:\n");
printf("%d %d %d\n",obj3.prevlink->prevlink-
>data,obj3.prevlink->data, obj3.data);
//Object 3 creation
}
Thank You

You might also like