Scs1102 Unit III
Scs1102 Unit III
Scs1102 Unit III
Contents
Single and Multidimensional Arrays: Array Declaration and Initialization of arrays – Arrays as
function arguments. Strings: Initialization and String handling functions. Structure and Union:
Definition and Declaration - Nested Structures, Array of Structures, Structure as function
arguments, Function that return structure – Union.
ARRAYS
Introduction:
So far we have used only single variable name for storing one data item. If we need to store
multiple copies of the same data then it is very difficult for the user. To overcome the difficulty a
new data structure is used called arrays.
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of elements are stored
contiguously in the memory under one variable name.
An array can be declared of any standard or custom data type.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100
variables named as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C
programming arrays is introduced in C which gives the capability to store the 100 roll numbers
in the contiguous memory which has 100 blocks and which can be accessed by single variable
name.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays
Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non-
contiguous allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address
from base register and then it will refer relative address of memory location with respect to
base address.
How to allocate contiguous memory?
1. Using static array declaration.
2. Using alloc ( ) / malloc ( ) function to allocate big chunk of memory dynamically.
Array Terminologies:
Size: Number of elements or capacity to store elements in an array. It is always mentioned in
square brackets [ ].
Type: Refers to data type. It decides which type of element is stored in the array. It is also
instructing the compiler to reserve memory according to the data type.
Base: The address of the first element is a base address. The array name itself stores address
of the first element.
Index: The array name is used to refer to the array element. For example num[x], num is array
and x is index. The value of x begins from 0.The index value is always an integer value.
Range: Value of index of an array varies from lower bound to upper bound. For example in
num[100] the range of index is 0 to 99.
Word: It indicates the space required for an element. In each memory location, computer can
store a data piece. The space occupation varies from machine to machine. If the size of element
is more than word (one byte) then it occupies two successive memory locations. The variables
of data type int, float, long need more than one byte in memory.
Characteristics of an array:
1. The declaration int a [5] is nothing but creation of five variables of integer types in
memory instead of declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from one
another with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the
other elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or
array variable of its type.
6. Array elements are stored in contiguous memory locations.
Array Declaration:
Array has to be declared before using it in C Program. Array is nothing but the collection of
elements of similar data types.
Syntax: <data type> array name [size1][size2].....[sizen];
Types of Array
1. Single Dimensional Array / One Dimensional Array
2. Multi Dimensional Array
Here we are learning the different ways of compile time initialization of an array.
Ways of Array Initializing 1-D Array:
1. Size is Specified Directly
2. Size is Specified Indirectly
Method 1: Array Size Specified Directly
In this method, we try to specify the Array Size directly.
int num [5] = {2,8,7,6,0};
In the above example we have specified the size of array as 5 directly in the initialization
statement. Compiler will assign the set of values to particular element of the array.
num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;
As at the time of compilation all the elements are at specified position So This initialization
scheme is Called as “Compile Time Initialization“.
Graphical Representation:
Accessing Array
1. We all know that array elements are randomly accessed using the subscript variable.
2. Array can be accessed using array-name and subscript variable written inside pair of
square brackets [ ].
Consider the below example of an array
So whenever we tried accessing array using arr[i] then it returns an element at the location*(arr
+ i)
Accessing array a[i] means retrieving element from address (a + i).
Example Program2: Accessing array
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]);
}
getch();
}
Output:
51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
5 5 5 5
26 26 26 26
Operations with One Dimensional Array
1. Deletion – Involves deleting specified elements form an array.
2. Insertion – Used to insert an element at a specified position in an array.
3. Searching – An array element can be searched. The process of seeking specific
elements in an array is called searching.
4. Merging – The elements of two arrays are merged into a single one.
5. Sorting – Arranging elements in a specific order either in ascending or in descending
order.
Example Programs:
1. C Program for deletion of an element from the specified location
from an Array
#include<stdio.h>
int main() {
int arr[30], num, i, loc;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Read elements in an array
printf("\nEnter %d elements :", num);
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
//Read the location
printf("\nLocation of the element to be deleted :");
scanf("%d", &loc);
/* loop for the deletion */
while (loc < num) {
arr[loc - 1] = arr[loc];
loc++; }
num--; // No of elements reduced by 1
//Print Array
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5
Enter 5 elements: 3 4 1 7 8
Location of the element to be deleted: 3
3 4 7 8
2. C Program to delete duplicate elements from an array
int main() {
int arr[20], i, j, k, size;
printf("\nEnter array size: ");
scanf("%d", &size);
printf("\nAccept Numbers: ");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("\nArray with Unique list: ");
for (i = 0; i < size; i++) {
for (j = i + 1; j < size;) {
if (arr[j] == arr[i]) {
for (k = j; k < size; k++) {
arr[k] = arr[k + 1]; }
size--; }
else
j++; }
}
for (i = 0; i < size; i++) {
printf("%d ", arr[i]); }
return (0);
}
Output:
Enter array size: 5
Accept Numbers: 1 3 4 5 3
Array with Unique list: 1 3 4 5
3. C Program to insert an element in an array
#include<stdio.h>
int main() {
int arr[30], element, num, i, location;
printf("\nEnter no of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
printf("\nEnter the element to be inserted:");
scanf("%d", &element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified location
for (i = num; i >= location; i--) {
arr[i] = arr[i - 1]; }
num++;
arr[location - 1] = element;
//Print out the result of insertion
for (i = 0; i < num; i++)
printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5
1 2 3 4 5
Enter the element to be inserted: 6
Enter the location: 2
1 6 2 3 4 5
4. C Program to search an element in an array
#include<stdio.h>
int main() {
int a[30], ele, num, i;
printf("\nEnter no of elements:");
scanf("%d", &num);
printf("\nEnter the values :");
for (i = 0; i < num; i++) {
scanf("%d", &a[i]); }
//Read the element to be searched
printf("\nEnter the elements to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;
while (i < num && ele != a[i]) {
i++; }
//If i < num then Match found
if (i < num) {
printf("Number found at the location = %d", i + 1);
}
else {
printf("Number not found"); }
return (0);
}
Output:
Enter no of elements: 5
11 22 33 44 55
Enter the elements to be searched: 44
Number found at the location = 4
5. C Program to copy all elements of an array into another array
#include<stdio.h>
int main() {
int arr1[30], arr2[30], i, num;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Accepting values into Array
printf("\nEnter the values:");
for (i = 0; i < num; i++) {
scanf("%d", &arr1[i]); }
/* Copying data from array 'a' to array 'b */
for (i = 0; i < num; i++) {
arr2[i] = arr1[i]; }
//Printing of all elements of array
printf("The copied array is:");
for (i = 0; i < num; i++)
printf("\narr2[%d] = %d", i, arr2[i]);
return (0);
}
Output:
Enter no of elements: 5
Enter the values: 11 22 33 44 55
The copied array is: 11 22 33 44 55
6. C program to merge two arrays in C Programming
#include<stdio.h>
int main() {
int arr1[30], arr2[30], res[60];
int i, j, k, n1, n2;
printf("\nEnter no of elements in 1st array:");
scanf("%d", &n1);
for (i = 0; i < n1; i++) {
scanf("%d", &arr1[i]); }
printf("\nEnter no of elements in 2nd array:");
scanf("%d", &n2);
for (i = 0; i < n2; i++) {
scanf("%d", &arr2[i]); }
i = 0;
j = 0;
k = 0;
// Merging starts
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
res[k] = arr1[i];
i++;
k++; }
else {
res[k] = arr2[j];
k++;
j++; }
}
/*Some elements in array 'arr1' are still remaining where as the array
'arr2' is exhausted*/
while (i < n1) {
res[k] = arr1[i];
i++;
k++; }
/*Some elements in array 'arr2' are still remaining where as the array
'arr1' is exhausted */
while (j < n2) {
res[k] = arr2[j];
k++;
j++; }
//Displaying elements of array 'res'
printf("\nMerged array is:");
for (i = 0; i < n1 + n2; i++)
printf("%d ", res[i]);
return (0);
}
Enter no of elements in 1st array: 4
11 22 33 44
Enter no of elements in 2nd array: 3
10 40 80
Merged array is: 10 11 22 33 40 44 80
1 integer roll 1 10
Declaration a[3][4]
No of Rows 3
No of Columns 4
No of Cells 12
Memory Representation:
1. 2-D arrays are stored in contiguous memory location row wise.
2. 3 X 3 Array is shown below in the first Diagram.
3. Consider 3×3 Array is stored in Contiguous memory location which starts from 4000.
4. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next
memory location i.e. Elements stored row-wise
5. After Elements of First Row are stored in appropriate memory locations, elements of
next row get their corresponding memory locations.
6. This is integer array so each element requires 2 bytes of memory.
Basic Memory Address Calculation:
a[0][1] = a[0][0] + Size of Data Type
a[0][0] 4000
a[0][1] 4002
a[0][2] 4004
a[1][0] 4006
a[1][1] 4008
a[1][2] 4010
a[2][0] 4012
a[2][1] 4014
a[2][2] 4016
Initializing 2D Array
Limitations of Arrays:
Array is very useful which stores multiple data under single name with same data type.
Following are some listed limitations of Array in C Programming.
A. Static Data
1. Array is Static data Structure
2. Memory Allocated during Compile time.
3. Once Memory is allocated at Compile Time it cannot be changed during Run-time
Applications of Arrays:
Array is used for different verities of applications. Array is used to store the data or values of
same data type. Below are the some of the applications of array –
A. Stores Elements of Same Data Type
Array is used to store the number of elements belonging to same data type.
int arr[30];
Above array is used to store the integer numbers in an array.
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Similarly if we declare the character array then it can hold only character. So in short character
array can store character variables while floating array stores only floating numbers.
B. Array Used for maintaining multiple variable names using single name
Suppose we need to store 5 roll numbers of students then without declaration of array we need
to declare following –
int roll1, roll2, roll3, roll4, roll5;
1. Now in order to get roll number of first student we need to access roll1.
2. Guess if we need to store roll numbers of 100 students then what will be the procedure.
3. Maintaining all the variables and remembering all these things is very difficult.
Consider the Array int roll[5]; Here we are using array which can store multiple values and we
have to remember just single variable name.
C. Array can be used for Sorting Elements
We can store elements to be sorted in an array and then by using different sorting technique we
can sort the elements.
Different Sorting Techniques are:
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Bucket Sort
D. Array can perform Matrix Operation
Matrix operations can be performed using the array. We can use 2-D array to store the matrix.
Matrix can be multi dimensional.
E. Array can be used in CPU Scheduling
CPU Scheduling is generally managed by Queue. Queue can be managed and implemented
using the array. Array may be allocated dynamically i.e at run time. [Animation will Explain more
about Round Robin Scheduling Algorithm | Video Animation]
F. Array can be used in Recursive Function
When the function calls another function or the same function again then the current values are
stores onto the stack and those values will be retrieving when control comes back. This is
similar operation like stack.
STRINGS
A string is a sequence of character enclosed with in double quotes (“ ”) but ends with
\0. The compiler puts \0 at the end of string to specify the end of the string.
To get a value of string variable we can use the two different types of formats.
Using scanf() function as: scanf(“%s”, string variable);
C library supports a large number of string handling functions. Those functions are stored under
the header file string.h in the program.
Syntax
strcat (StringVariable1, StringVariable 2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
printf(‚ Concatenation String is:%s‛, strcat(str1,str2));
getch();
}
Output:
Enter First String
Good
Enter Second String
Morning
Concatenation String is: GoodMorning
(iii) strcmp() function
strcmp() function is used to compare two strings. strcmp() function does a case
sensitive comparison between two strings. The two strings are compared character by
character until there is a mismatch or end of one of the strings is reached (whichever occurs
first). If the two strings are identical, strcmp( ) returns a value zero. If they‟re not, it returns the
numeric difference between the ASCII values of the first non-matching pairs of characters.
Syntax
strcmp(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmp(str1,str2);
printf(‚ Compare String Result is:%d‛,res);
getch();
}
Output:
Enter First String
Good
Enter Second String
Good
Compare String Result is: 0
strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.
Syntax
strcmpi(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmpi(str1,str2);
printf(‚ Compare String Result is:%d‛,res);
getch();
}
Output:
Enter First String
WELCOME
Enter Second String
welcome
Compare String Result is: 0
(v) strcpy() function:
strcpy() function is used to copy one string to another. strcpy() function copy the contents of
second string to first string.
Syntax
strcpy(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
strcpy(str1,str2)
printf(‚ First String is:%s‛,str1);
printf(‚ Second String is:%s‛,str2);
getch();
}
Output:
Enter First String
Hello
Enter Second String
welcome
First String is: welcome
Second String is: welcome
(vi) strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.
Syntax
strlwr(StringVariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Lowercase String : %s‛, strlwr(str));
getch();
}
Output:
Enter String
WELCOME
Lowercase String : welcome
(vii) strrev() function:
strrev() function is used to reverse characters in a given string.
Syntax
strrev(StringVariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Reverse String : %s‛, strrev(str));
getch();
}
Output:
Enter String
WELCOME
Reverse String : emoclew
(viii) strupr() function:
strupr() function is used to convert all characters in a given string from lower case to
uppercase letter.
Syntax
strupr(Stringvariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Uppercase String : %s‛, strupr(str));
getch();
}
Output:
Enter String
welcome
Uppercase String : WELCOME
STRUCTURES
Arrays are used for storing a group of SIMILAR data items. In order to store a group of
data items, we need structures. Structure is a constructed data type for packing different types
of data that are logically related. The structure is analogous to the “record” of a database.
Structures are used for organizing complex data in a simple and meaningful way.
Structure Definition
Structures are defined first and then it is used for declaring structure variables. Let us
see how to define a structure using simple example given below:
struct book
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};
The keyword “struct” is used for declaring a structure. In this example, book is the name of the
structure or the structure tag that is defined by the struct keyword. The book structure has six
fields and they are known as structure elements or structure members. Remember each
structure member may be of a different data type. The structure tag name or the structure
name can be used to declare variables of the structure data type.
struct tagname
Data_type member1;
Data_type member2;
…………….
……………
};
Note:
1. To mark the completion of the template, semicolon is used at the end of the
template.
2. Each structure member is declared in a separate line.
First, the structure format is defined. Then the variables can be declared of that structure type.
A structure can be declared in the same way as the variables are declared. There are two
ways for declaring a structure variable.
1) Declaration of structure variable at the time of defining the structure (i.e structure
definition and structure variable declaration are combined)
struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
} b1,b2,b3;
The b1, b2, and b3 are structure variables of type struct book.
NOTE:
Structure tag name is optional.
E.g.
struct
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
}b1, b2, b3;
Declaration of structure variable at a later time is not possible with this type of
declaration. It is a drawback in this method. So the second method can be preferred.
Structure members are not variables. They don‟t occupy memory until they
are associated with a structure variable.
Syntax
STRUCTURE_Variable.STRUCTURE_Members
The different ways for storing values into structure variable is given below:
b1.pages = 786;
b1.price = 786.50;
strcpy(b1.author, ‚John‛);
Example
#include<stdio.h>
#include<conio.h>
struct book
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};
Example
main()
{
struct
{
int rollno;
int attendance;
}
s1={786, 98};
}
The above example assigns 786 to the rollno and 98 to the attendance.
Example
main()
{
struct student
{
int rollno;
int attendance;
};
struct student s1={786, 98};
struct student s2={123, 97};
}
Note:
Structures can also be nested. i.e A structure can be defined inside another structure.
Example
struct employee
{
int empid;
char empname[20];
int basicpay;
int da;
int hra;
int cca;
} e1;
In the above structure, salary details can be grouped together and defined as a
separate structure.
Example
struct employee
{
int empid;
char empname[20];
struct
{
int basicpay;
int da;
int hra;
int cca;
} salary;
} e1;
The structure employee contains a member named salary which itself is another
structure that contains four structure members. The members inside salary structure
can be referred as below:
e1.salary.basicpay
e1.salary.da;
e1.salary.hra;
e1.salary.cca;
However, the inner structure member cannot be accessed without the inner structure
variable.
Example
e1.basicpay
e1.da
e1.hra
e1.cca
are invalid statements
Moreover, when the inner structure variable is used, it must refer to its inner structure
member. If it doesn‟t refer to the inner structure member then it will be considered as
an error.
Example
e1.salary (salary is not referring to any inner structure member. Hence it is wrong)
Array of Structures
A Structure variable can hold information of one particular record. For example,
single record of student or employee. Suppose, if multiple records are to be
maintained, it is impractical to create multiple structure variables. It is like the
relationship between a variable and an array. Why do we go for an array? Because we
don‟t want to declare multiple variables and it is practically impossible. Assume that you
want to store 1000 values. Do you declare 1000 variables like a1, a2, a3…. Upto
a1000? Is it easy to maintain such code ? Is it a good coding? No. It is not.
Therefore, we go for Arrays. With a single name, with a single variable, we can store
1000 values. Similarly, to store 1000 records, we cannot declare 1000 structure
variables. But we need “Array of Structures”.
The above code creates 1000 elements of structure type student. Each element
will be structure data type called student. The values can be stored into the array of
structures as follows:
s1[0].student_age = 19;
Example
#include<stdio.h>
#include<conio.h>
struct book
{
int bookid;
char bookname[20];
char author[20];
};
Struct b1[5];
main()
{
int i;
clrscr();
for (i=0;i<5;i++)
{
printf("Enter the Book Id: ");
scanf("%d", &b1[i].bookid);
printf("Enter the Book Name: ");
scanf("%s", b1[i].bookname);
printf("Enter the Author Name: ");
scanf("%s", b1[i].author);
}
for (i=0;i<5;i++)
{
printf("%d \t %s \t %s \n", b1[i].bookid, b1[i].bookname,
b1[i].author);
}
getch();
}
Output:
Example
struct sample
{
int no;
float avg;
} a;
void main( )
{
a.no=75;
a.avg=90.25;
fun(a);
}
Output
Method 1 :- Individual member of the structure is passed as an actual argument of the function
call. The actual arguments are treated independently. This method is not suitable if a structure
is very large structure.
Method 2:- Entire structure is passed to the called function. Since the structure declared as
the argument of the function, it is local to the function only. The members are valid for the
function only. Hence if any modification done on any member of the structure , it is not reflected
in the original structure.
Method 3 :- Pointers can be used for passing the structure to a user defined function. When
the pointers are used , the address of the structure is copied to the function. Hence if any
modification done on any member of the structure , it is reflected in the original structure.
{
Local Variable declaration;
Statement 1;
Statement 2;
--------------
-------------
Statement n;
}
Example :
#include <stdio.h>
struct st
{
char name[20];
int no;
int marks;
};
int main( )
{
struct st x ,y;
int res;
printf(‚\n Enter the First Record‛);
scanf(‚%s%d%d‛,x.name,&x.no,&x.marks);
printf(‚\n Enter the Second Record‛);
scanf(‚%s%d%d‛,y.name,&y.no,&y.marks);
res = compare ( x , y );
if (res == 1)
printf(‚\n First student has got the Highest Marks‛);
else
printf(‚\n Second student has got the Highest Marks‛);
}
compare ( struct st st1 , struct st st2)
{
if (st1.marks > st2. marks )
return ( 1 );
else
return ( 0 );
}
In the above example , x and y are the structures sent from the main ( ) function as the
actual parameter to the formal parameters st1 and st2 of the function compare ( ).
#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example *sptr)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr->num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr->num2);
}
//-------------------------------------
void print(struct Example *sptr)
{
printf("\nNum1 : %d",sptr->num1);
printf("\nNum2 : %d",sptr->num2);
}
//-------------------------------------
void main()
{
int i;
clrscr();
for(i=0;i<3;i++)
accept(&s[i]);
for(i=0;i<3;i++)
print(&s[i]);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
struct student
{
int id;
char name[20];
float percentage;
};
void main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
getch();
}
Write a C program to create a structure student, containing name and roll. Ask user the
name and roll of a student in main function. Pass this structure to a function and display
the information in that function.
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration
otherwise compiler shows error */
int main()
{
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument
return 0;
}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Output
Enter student's name: Kevin Amla
Enter roll number: 149
Output
struct student
{
int id;
char name[20];
float percentage;
};
void main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
getch();
}
Explanation
In this program, structure variables dist1 and dist2 are passed by value (because value of dist1
and dist2 does not need to be displayed in main function) and dist3 is passed by reference ,i.e,
address of dist3 (&dist3) is passed as an argument. Thus, the structure pointer variable d3
points to the address of dist3. If any change is made in d3 variable, effect of it is seed in dist3
variable in main function.
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}
void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Array of Structure can be passed to function as a Parameter.function can also return Structure
as return type.Structure can be passed as follow
Example :
#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr[i].num2);
}
}
//-------------------------------------
void print(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
}
}
//-------------------------------------
void main()
{
int i;
clrscr();
accept(s,3);
print(s,3);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
Explanation :
Inside main structure and size of structure array is passed. When reference (i.e ampersand) is
not specified in main , so this passing is simple pass by value. Elements can be accessed by
using dot [.] operator
Union
The concept of Union is borrowed from structures and the formats are also same. The
distinction between them is in terms of storage. In structures , each member is stored in its own
location but in Union , all the members are sharing the same location. Though Union consists of
more than one members , only one member can be used at a particular time. The size of the
cell allocated for an Union variable depends upon the size of any member within Union
occupying more no:- of bytes. The syntax is the same as structures but we use the keyword
union instead of struct.
where employee is the union variable which consists of the member name,no
and salary. The compiler allocates only one cell for the union variable as
20 Bytes Length
20 bytes cell can be shared by all the members because the member name is occupying the
highest no:- of bytes. At a particular time we can handle only one member.To access the
members of an union , we have to use the same format of structures.
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
Output:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
Explanation for above C union program:
There are 2 union variables declared in this program to understand the difference in
accessing values of union members.
Record1 union variable:
If we want to access all member values using union, we have to access the member
before assigning values to other members as shown in record2 union variable in this
program.
Each union members are accessed in record2 example immediately after assigning
values to them.
If we don‟t access them before assigning values to other member, member name and
value will be over written by other member as all members are using same memory.
We can‟t access all members in union at same time but structure can do that.
int main()
{
strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;
Assignment Question
1. Create a structure to store the employee number, name, department and basic salary.
Create a array of structure to accept and display the values of 10 employees.
PRACTICE QUESTIONS
main( )
{
char c[2] = "A" ;
printf ( "\n%c", c[0] ) ;
printf ( "\n%s", c ) ;
}
main( )
{
char str1[ ] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ } ;
char str2[ ] = "Hello" ;
printf ( "\n%s", str1 ) ;
printf ( "\n%s", str2 ) ;
}
a) main( )
(a) main( )
{
char *str1 = "United" ;
char *str2 = "Front" ;
char *str3 ;
str3 = strcat ( str1, str2 ) ;
printf ( "\n%s", str3 ) ;
}
7) Which is more appropriate for reading in a multi-word string?
as ______.
c. The array char name [10] can consist of a maximum of ______ characters.