CP New
CP New
Control Structures: Decision making Statements - Simple if, if_else, nested if_else,
else_if ladder, Switch Case, goto, break & continue statements; Looping Statements -
Entry controlled and exit controlled statements, while, do-while, for loops, Nested
loops.
Strings: Declaring & Initializing string variables; String handling functions - strlen,
strcmp, strcpy and strcat; Character handling functions - toascii, toupper, tolower,
isalpha, isnumeric etc.
User Defined Functions: Need for user defined functions; Format of C user defined
functions; Components of user defined functions - return type, name, parameter
list, function body, return statement and function call; Categories of user defined
functions - With and without parameters and return type.
Unions.
1
Arrays:
✓ Array is a set of elements of same type. Elements of array are stored in contiguous/adjacent
memory location and addressed by a common name with subscript. Array index/subscript
always starts from zero.
✓ Array might be of any data types.
✓ Array size must be an integer value.
Syntax: data type array_name[size];
Example: int a[10];
1. 1-Dimensional array: 1-Dimensional array is a type of array which contains only one
subscript/index.
Syntax: Data type array name[size];
Example: int s[5];
Memory representation:
0 1 2 3 4
2
s[0]➔ This will access the 1st location of array in the above memory representation.
3
printf(“%d\n”,s[i]);
}
getch();
}
#include<stdio.h>
4
#include<conio.h>
void main()
{
int a[100],n,i,sum=0;
clrscr();
printf(“enter the number of elements you want to insert:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“enter the element %d:”,i+1);
scanf(“%d”,&a[i]);
sum=sum+a[i];
}
printf(“\n the sum of an array is:%d”,sum);
printf(“\n the average of an array is:%0.2f”,(float) sum\n);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],small,size,i,location=1;
clrscr();
printf(“enter the elements in an array\n”);
scanf(“%d”,&size);
printf(“enter %d integers\n”,size);
for(i=0;i<size;i++)
{
scanf(“%d”,&a[i]);
small=a[0];
}
for(i=0;i<size;i++)
{
if(a[i]<small)
{
small=a[i];
location=i+1;
}
}
printf(“smallest element is present at %d location and its value is
%d\n”,location,small);
getch();
}
5
Program to Find The Largest Elements of An Array:
#include<stdio.h>
#include<conio.h.
void main()
{
int a[100],i,n,large;
clrscr();
printf(“enter the size of an array”);
scanf(“%d”,&n);
printf(“enter %d elements\n”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
large=a[0];
for(i=0;i<n;i++)
{
if(a[i]>large)
{
large=a[i];
}
printf(“largest=%d”,large);
getch();
}
2. 2-Dimensional Array:
An array containing two subscripts is known as 2-dimensional array. The 2-dimensional
array in C-programming language is also known as matrix. A matrix can be represented in
the form of rows and columns. 2-dimensional array is represented in tabular form where
the first subscript represent row size and the second subscript represent the column size.
Syntax: Data type array name[row size][columnsize];
Example: int a[3][4];
Memory representation:
0 1 2 3
0 0,0 0,1 0,2 0,3
Here the number of rows represents the first subscript and the number of columns
represents the second subscript. This two dimensional memory matrix is given for
6
representation purpose only. However, in memory elements will be storedin the contiguous
memory locations.
• Initializing using array within array syntax: For initializing 2-dimensional array we can
assign the values to each element as array within array.
{1,4},
{5,2},
{6,5}
};
• Initialize using 1-dimensional array syntax: The values are assigned sequentially using
curly brackets.
Syntax: data type array name[row][column]={ele1,ele2,……,ele row*column};
Example: int a[3][4]={10,20,30,40,50,60,70,80,90,100,110,120};
#include<stdio.h>
#include<conio.h>
void main()
int a[100][100],m,n,i,j;
clrscr();
printf(“enter the number of rows and columns”);
scanf(“%d%d”,&m,&n);
printf(“enter %d elements\n”,m*n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“contents of 2D array are\n”);
for(i=0;i<m;i++)
{
7
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100][100],b[100][100],c[100][100],m,n,i,j;
clrscr();
printf(“enter the size of an array”);
scanf(“%d”,&m,&n);
printf(“enter the %d elements of a matrix\n”,m*n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter the %d elements of b matrix\n”,m*n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
8
}
printf(“sum of two matrix is\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
getch();
}
Program To Compute The Sum Of Upper and Lower Diagonal Elements Of A Matrix:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100][100],n,i,j,sumlower,sumupper;
clrscr();
printf(“enter the size of an array”);
scanf(“%d”,&n);
printf(“enter %d elements of the matrix”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i<j)
{
sumupper=sumupper+a[i][j];
}
if(i>j)
{
sumlower=sumlower+a[i][j];
}
}
printf(“sum of lower diagonal elements=%d”,sumlower);
printf(“sum of upper diagonal elements=%d”,sumupper);
getch();
}
9
Program to insert an element into a specific position in array:
#include<stdio.h>
void main()
{
int a[100], i, pos, ele,n;
printf(“ enter the size of array”);
scanf(“%d”, &n);
printf(“ Enter %d elements”, n);
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);
printf(“Enter the element and position number”);
scanf(“%d%d”,&ele,&pos);
for(i=n-1; i>=pos-1;i--)
{
a[i+1]=a[i];//move element one step down
}
a[pos-1]=ele;
printf(“ the elements of array are”);
for(i=0;i<n;i++)
printf(“%d\t”, a[i]);
}
10
printf(“ the elements of array are”);
for(i=0;i<n;i++)
printf(“%d\t”, a[i]);
}
11
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);
for(i=0; i<n-1;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
If(a[pos]>a[j])
{ pos=j;
}
If (pos!=i)
{
t= a[i];
a[i]=a[pos];
a[pos]=t;
}
}
}
printf(“ the sorted elements of array are”);
for(i=0;i<n;i++)
printf(“%d\t”, a[i]);
}
Strings:
Strings are the set of characters enclosed within the double quotes. It is terminated at the
end by a null character that is \0.
Example: “success”
Declaration of a string:
Declaring a string is as simple as declaring a 1-dimensional array. It is declared using char
data type and stored in the form of characters.
Syntax: char string name[size];
Example: char str[10];
In the above example str is a name given to the string variable and size is used to define
the length of the string that is the number of characters string will accommodate.
12
String Input/Output:
C-programming language provides many built-in functions to read any given input and to
display the data on screen when there is a need to output the result. All these built-in
functions are present in the C header file string.h.
1. printf and scanf functions: The standard input/output header file named stdio.h contains
the definitions of the functions printf() and scanf(), which are used to display output on the
screen and to take the input from the programmer respectively.
scanf() accepts char upto the white space character.
scanf() appends ‘\0’ at the end of the string.
printf() is used to display the string upto the white space.
Syntax: printf(“%s”,string name);
scanf(“%s”,string name);
NOTE: & operator is not required in scanf() for accepting string variable since string name
itself is used to store in that particular location.
printf() function returns the number of characters printed by it, and scanf() function returns
the number of characters read by it.
The main disadvantage of scanf() functions that it stops reading characters when it
encounters a space. For example if we enter a string as good morning using scanf() function
it will read only good and leave rest of the part after the space.
Program To Accept And Display The String Using Printf() And Scanf() Functions:
#include<stdio.h>
#include<conio.h>
void main()
{
char name[100];
clrscr();
printf(“enter the string”);
scanf(“%s”,name);
printf(“entered name=%s\n”,name);
getch();
}
Program To Accept And Display The String Using getchar() And putchar() Functions:
#include<stdio.h>
#include<conio.h>
void main()
13
{
char address[200],c;
int i=0;
printf(“enter the address\n”);
do
{
c=getchar();
address[i]=c;
i++;
}while(c!=’\n’)
c[i]=’\0’;
printf(“entered address is\n”);
for(i=0;address[i]!=’\0’;i++)
{
putchar(address[i]);
}
getch();
}
Program To Accept And Display A String Using Gets() And Puts() Functions:
#include<stdio.h>
#include<conio.h>
void main()
{
char address[200];
printf(“enter your address”);
gets(address);
printf(“entered address is\n”);
puts(address);
getch();
}
14
Syntax: sscanf(buffer string,format specifier,arguments);
Here the contents of buffer string will be stored in arguments.
Example: char name[20];
int age;
sscanf(“ram 23”,”%s%d”,name,age);
As we can create a 2-dimensional array of int, float, etc. In the same way we can also create
a 2-dimensional array of strings. It is also called as table of strings.
Syntax: char string name[rows][cloumns];
Example: char names[50][20];
Memory representation:
0 1 2 3 4 5 6
0
M O H A N \0
1 D A S \0
2
K A R A M \O
3
R A V I \0
4 R A G H U \0
It requires only row index for accessing a 2-dimensional char array elements.
Syntax: array name[index];
Example: puts(names[2]);
15
Program To Accept 5 Names And Display The Same:
#include<stdio.h>
#include<conio.h>
void main()
{
char name[5][20];
int i;
clrscr();
printf(“enter 5 names”);
for(i=0;i<5;i++)
{
scanf(“%s”,name[i]);
}
printf(“the entered names are\n”);
for(i=0;i<5;i++)
{
printf(“%s”,name[i]);
}
getch();
}
16
It returns -1 if first string is lesser than second string.
It is used for sorting of the strings.
Syntax: strcmp(str1,str2);
5. strstr function: It is used to find the substring in a string.
It returns pointer of the starting letter of the substring if present.
It return null pointer instead.
Syntax: char_ptr_Var= strstr(string;substring);
E.g.,
const char name[20] = "Dennis Ritchie";
const char find[10] = "Ritchie";
char *ret;
Program To Find The Length Of The String Without Using Built-In Functions:
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
int i,len=0;
printf(“enter a string\n”);
gets(name);
for(i=0;name[i]!=’\0’;i++)
{
len++;
}
printf(“length of the string=%d”,len);
getch();
}
Program To Copy The Contents Of One String To Another String Without Using Built-
In functions:
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
int i;
printf(“enter the string\n”);
gets(s1);
17
for(i=0;s1[i]!=’\0’;i++)
{
s2[i]=s1[i];
}
s2[i]=’\0’;
puts(s1);
puts(s2);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
int i,len=0;
printf(“enter the two strings s1 and s2\n”);
gets(s1);
gets(s2);
for(i=0;s1[i]!=’\0’;i++)
{
len++;
}
for(i=0;s2[i]!=’\0’;i++)
{
s1[len]=s2[i];
len++;
}
s1[len]=’\0’;
puts(s1);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
int i;
printf(“enter the string s1 and s2\n”);
gets(s1);
gets(s2);
18
while(s1[i]!=’\0’&&s2[i]!=’\0’&&s1[i]==s2[i])
{
i++;
}
if(s1[i]==’\0’&&s2[i]==’\0’)
{
printf(“both strings are equal”);
}
else
{
printf(“strings are different”);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
int i;
clrscr();
printf(“enter a string”);
gets(s1);
for(i=0;s1[i]!=’\0’;i++)
{
19
s2[i]=s1[i]+5;
}
s2[i]=’\0’;
puts(s2);
getch();
}
Character functions in C
Character functions need ctype.h header file to be included in the pgoram. Different character
functions provided by C Language are:
1. isalpha():
This function checks whether the character variable/constant contains alphabet or not.
2. isdigit()
This function checks whether the character variable/ constant contains digit or not.
3. isupper()
This function checks whether the character variable/constant contains an capital letter alphabet or
not.
4. islower()
This function checks whether the character variable/constant contains a lowercase alphabet or not.
5. toupper()
This function converts lowercase alphabet into uppercase alphabet.
6. tolower()
This function converts an uppercase alphabet into lowercase alphabet.
20
UNIT 3
Pointers
Pointers in C language is a variable that stores the address of another variable. A pointer in
C is used to allocate memory dynamically that is at run time. The pointer variable might
be belonging to any of the data type such as int, float, doublr, char etc.
p=&x;
*p=5;
The location pointed by P is initialized with 5 which is the location named as ‘x’
Advantages of pointers in C:
✓ Pointers provide direct access to memory.
✓ Pointers provide a way to return more than one function to the function.
✓ Reduces the complexity and storage space of the program.
✓ Provide an alternate way to access the array elements.
✓ Pointers can be used to pass information back and forth between the calling function and
called functions.
✓ Pointers allows us to perform dynamic memory allocation and deallocation.
✓ Pointers allows us to resize the dynamically allocated memory block.
✓ Addresses of objects can be extracted by using pointers.
21
Disadvantages of pointers:
✓ If pointers are updated with incorrect values, it might lead to memory corruption.
✓ Care to be taken while working with pointers.
Pointer to pointer:
A pointer to a pointer is a form of multiple indirection or chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value:
Example:
int v=300, *ptr,*pptr;
ptr=&v;
pptr=&ptr;
now *ptr will be accessing the value at v ie 300, similarly,**pptr will also be accessing the
value *ptr ie 300.
Pointer to Pointer in C
A variable that is a pointer to a pointer must be declared as such. This is done by placing
an additional asterisk in front of its name. For example, the following declaration declares
a pointer to a pointer of type int −
int **var;
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
22
/* take the address of ptr using address of operator & */
pptr = &ptr;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Pointer Arithmetic:
A pointer in c is an address, which is a numeric value. Therefore, you can perform
arithmetic operations on a pointer just as you can on a numeric value. There are four
arithmetic operators that can be used on pointers: ++, --, +, and -. However, as we know
that pointer contains the address, the result of an arithmetic operation performed on the
pointer will also be a pointer
Increment (++):
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points
to the address 1000 (Assuming 32-bit integers).
Example:
ptr++;
After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without
impacting the actual value at the memory location.
The following program increments the variable pointer to access each succeeding element
of the array:
#include <stdio.h>
int main () {
23
ptr = var;
return 0;
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
Decrement (--): Similar to increment. In this case it will decrease the value by number of
bytes.
Addition (+): We can add a value to the pointer variable. The formula of adding value to
pointer is given below: Adding any number to a pointer will give an address. new_address=
current_address + (number * size_of(data type))
For 64-bit int variable, it will add 4 * number.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output:
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
Subtraction (-): Similar to addition.
24
Illegal arithmetic with pointers:
There are various operations which cannot be performed on pointers. Since, pointer stores
address hence we must ignore the operations which may lead to an illegal address, for
example, addition, and multiplication. A list of such operations is given below.
• Address + Address = illegal
• Address * Address = illegal
• Address % Address = illegal
• Address / Address = illegal
• Address & Address = illegal
• Address ^ Address = illegal
• Address | Address = illegal
• ~Address = illegal
Variable arr will give the base address, which is a constant pointer pointing to arr[0].
Hence arr contains the address of arr[0] i.e 1000.
Pointer to Array
Use a pointer to an array, and then use that pointer to access the array elements. For
example,
#include<stdio.h>
void main()
{
int a[3] = {1, 2, 3};
int *p = a;
for (int i = 0; i < 3; i++)
{
25
printf("%d", *p);
p++;
}
return 0;
}
123
Syntax:
a[i]
Syntax:
*(*(a + i) + j)
26
Functions:
A function is a set of statements that perform a particular task. Every C-program contains
at least one function, which is main().
Types of functions:
1. Built-in functions.
2. User-defined functions.
1. Built-in functions: These are pre-shipped functions which comes along with the C-
compiler or any associated header files. Built-in functions can be accessed only by
mentioning the header files in the inclusion section.
2. User-defined functions: These are the functions that are created by the developers for
solving a particular task.
Example: sorting(), display() etc
Functions are also called as methods, sub-programs, sub-routine, procedure, sub-
procedure.
Advantages of functions:
✓ Functions avoid repetition of codes that is; functions written once can be used again and
again.
✓ It increases problem readability.
✓ Through structured programming approach or modular programming approach or top
down design we can break down a complex problem into smaller functions.
✓ Modifying of a program becomes easier by using functions.
✓ Saves lines of codes and program will be simple and clean.
Note: Arguments/parameters are values which are supplied to the function. Return value is
the value returned by the function.
27
num=square(4);
printf(“%d”, num);
}
int square(int n1)
{
int x=n1*n1;
return(x);
}
Working:
✓ Firstly compiler will call main function.
✓ When control comes inside the main function, execution of main starts(that is execution of
C-program starts)
✓ Here in the above example we have called a function square(4).
✓ We have passed “4” as parameter to function. Now control goes to the square function and
executes the statements and returns the value.
✓ Function will return value 16 to the calling function(main). It will start executing from the
same place it was called.
✓ Returned value will be assigned to variable “num”.
✓ num value (16) will be displayed using printf.
✓ Main function ends.
✓ C-program terminates.
Example:
int largest(intx, inty)
{
if(x>y)
return x;
else
28
return y;
}
As per the syntax we can return one value, but to return more than one variable we can use
arrays.
Syntax for calling the function:
function name(arguments);
Example: largest(x,y);
Types of functions: Functions are classified into different types based on arguments and
return type.
1. Functions with arguments and return type:
It is type of function that contains both arguments and return type.
Syntax: return datatype function name(arguments)
{
body of the function
return value;
}
#include<stdio.h>
#include<conio.h>
int largest(int, int)
void main()
{
int n1,n2,res;
clrscr();
printf(“enter two numbers”);
scanf(“%d%d”,&n1,&n2);
res=largest(n1,n2);
printf(“largest=%d”,res);
}
int largest(int n1, int n2)
{
if(n1>n2)
{
return n1;
29
}
else
{
return n2;
}
}
2. Function with argument and without return value:
It is a type of function that contains argument but does not return value.
Syntax: void function name(argument)
{
body of the function
}
Program To Compute Largest Of Two Functions:
#include<stdio.h>
#include<conio.h>
void largest(int, int);
void main();
{
int n1,n2;
printf(“enter two numbers”);
scanf(“%d%d”,&n1,&n2);
largest(n1, n2);
}
void largest(int n1,int n2)
{
if(n1>n2)
printf(“n1 is largest”);
else
printf(“n2 is largest”);
}
30
printf(“largest=%d”,res);
}
int largest()
{
int n1, n2;
printf(“enter 2 numbers\n”);
scanf(“%d%d”,&n1,&n2);
if(n1>n2)
{
return n1;
}
else
{
return n2;
}
}
#include<stdio.h>
#include<conio.h>
void largest();
void main()
{
largest();
}
void largest()
{
int n1,n2;
printf(“enter two numbers”);
scanf(“%d%d”,&n1,&n2);
if(n1>n2)
{
printf(“n1 is largest”);
}
else
{
printf(“n2 is largest”);
}
31
}
Nesting Of Functions:
One function calls another functions or chain of function calls is called as nesting.
Recursion:
When a function calls itself from its body it is called as recursion.
Syntax: datatype function_name(argument)
{
function_name(argument);
}
32
Program To Compute Factorial Of A Number Using Recursion:
#include<stdio.h>
#include<conio.h>
void main()
{
intn,f=0;
clrscr();
printf(“enter the number\n”);
scanf(“%d”,&n);
f=fact(n);
printf(“factorial of %d is %d\n”,n,f);
getch();
}
int fact(int n)
{
if(n==0)
{
return 1;
}
else
{
return(n*fact(n-1));
}
}
Advantages of recursion:
✓ Reduces complexity of the problem.
✓ Through recursion one can solve problems in an easy way.
Disadvantages of recursion:
✓ Recursive solution is always logical and it is very difficult to trace.
✓ Recursion consumes a lot of stack spaces(memory).
✓ Recursion uses more processor time.
33
Program For Swapping Two Numbers Using Call By Value:
#include<stdio.h>
#include<conio.h>
void main()
{
int x=10, y=20;
printf(“Before Swap: x=%d, y=%d”,x,y);
swap(x,y);
}
void swap(int m, int n)
{
int temp;
temp=m;
m=n;
n=temp;
printf(“After Swap: m=%d, n=%d”,m,n);
}
• Call by reference: In this method the address of the actual parameters is passed to the
function, so actual and formal arguments shares the same address space. In call by
reference, original value is modified because since we pass reference (address). Hence
value changed inside the function, is reflected inside as well as outside the function.
34
Passing Arrays To The Functions:
1. Passing 1-dimensional array to the function:
1- Dimensional array can be passed by passing the array name and array size. Therefore,
two arguments are required.
Arguments required are:
1. Array name.
2. Size of array.
Example:
#include<stdio.h>
int minarray(int arr[],int size)
{
int min=arr[0];
int i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}//end of for
return min;
}//end of function
int main()
{
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array
Example:
#include <stdio.h>
35
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", arr[i][j]);
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;
print(m, n, arr);
return 0;
}
Example:
#include <stdio.h>
int main(void) {
// variables
char message[] = "Hello World";
// print the string message
displayString(message);
return 0;
}
2. 2-dimensional array of string: To pass a two dimensional string to a function we just write
the name of the string array variable as the function argument and row size.
Arguments required are:
1. string name.
2. Row size.
Example:
#include <stdio.h>
36
void displayCities(char [][50], int rows);
int main(void) {
// variables
char cities[][50] = { "Bangalore", "Chennai", "Kolkata", "Mumbai", "New
Delhi" };
int rows = 5;
return 0;
}
printf("Cities:\n");
for (r = 0; r < rows; r++) {
i = 0;
while(str[r][i] != '\0') {
printf("%c", str[r][i]);
i++;
}
printf("\n");
}
}
37
{
struct student s;
display(s.name);
}
void display(char s[20])
{
puts(s);
}
2. Passing entire structure: To pass an entire structure to a function we just write the name
of structure variable.
Example:
struct student
{
char name[20];
int reg no;
}
main(0
{
struct student s;
display(s);
}
void display(struct student s)
{
puts(s.name);
printf(“Age=%d”,s.age);
}
38
struct student a;
display(&a);
}
void display(struct student *s)
{
puts(s➔names);
}
Structures:
Structures are the user defined data type. It is a collection of different data types under one
name. It is a collection of related data items.
Syntax:
struct structure name
{
data type variable name;
data type variable name;
};
Example:
struct student
{
char name[20],course[5];
int regno,m[5];
};
All the different data types inside the structure are called as members of the structure.
Typedef is used to create alias name for the existing data types just to maintain simplicity.
Example: typedef struct student stud;
Now we can create variables using the alias name stud.
stud s1,s2;
39
structure variable name.members name
Example:
s1.name
printf(“regno=%d”,s1.regno);
Example:
struct student
{
char name[20],course[5];
int regno,m[5];
};
Operation In Structures:
1. Assigning one structure to another.
By assigning a structure variable to another a copy of one structure to another is done.
However, both structure variables must be of similar type. If the structures are of different
types we cannot assign the value of one structure to another.
Example:
struct student s1,s2;
s2=s1;
2. Comparing two structure:
s1==s2;
It returns 0 if the structures are different
It returns 1 if the structure are same.
40
void main()
{
struct student s;
int i, total=0;
printf(“enter the name\n”);
gets(s.name);
printf(“enter the course\n”);
gets(s.course);
printf(“enter the reg no\n”);
scanf(“%d”,&s.regno);
printf(“enter marks of 5 subjects\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&s.m[i]);
}
//compute total marks
for(i=0;i<5;i++)
{
total=total+s.m[i];
}
printf(“name= “);
puts(s.name);
printf(“course= \n“);
puts(s.course);
printf(“regno=%d\n”,s.regno);
printf(“5 subjects marks\n”);
for(i=0;i<5;i++)
{
printf(“%d\n”,s.m[i]);
}
printf(“total marks=%d”,total);
getch();
}
Array of Structures:
Collection of structures of same type.
Syntax:
struct structure name variable name[no.variables];
Example: struct student s[5];
41
Memory representation:
Program To Accept 5 Students’ Information And Display The Same Using Array Of
Structures:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20],course[5];
int regno;
};
void main()
{
struct student s[5];
int i;
printf(“enter the name, course, regno of 5 students\n”);
for(i=0;i<5;i++)
{
scanf(“%s%s%d”,s[i].name,s[i].course,&s[i].regno);
printf(“details of 5 students\n”);
}
for(i=0;i<5;i++)
{
printf(“name=%s,course=%s,regno=%d\n”,s[i].name,s[i].course,s[i].regno );
}
getch();
}
Unions:
A union is a special data type available in C that allows storing different data types in the
same memory location. It is a collection of different data types under one name. It is user
defined data type and is similar to structures.
Syntax:
42
union union name
{
data type variable name;
};
Example:
union student
{
char name[20],course[5];
int regno,m[5];
};
Declaration of unions:
Memory allocation:
It allocates memory only for the largest sized member. At any point of time, the memory
will be allocated for only one member of the union. So only one member value will be
stored and accessed at a time. Therefore, the total Size of the union is the size of the largest
member in union.
Example:
union student
{
char name[20],course[5];
int regno,m[5];
};
reg no 2 bytes
course 5 bytes
name 20 bytes
Size of Union student = 20 bytes
43
Difference between structures and unions:
STRUCTURES UNIONS
The keyword struct is used to define The keyword union is used to define
a structure. a union.
The size of structure is greater than or The size of the union is equal to the
equal to the sum of size of all its size of the largest member.
members.
Each member within a structure is Memory allocated will be shared by
assigned unique storage area of individual members of the union.
location.
Altering the value of the member will Altering the value of any of the
not affect other members of the members will alter the value of other
structure. members.
Individual member can be accessed at Only one member can be accessed at
a time. a time.
Several members of a structure can Only the first member of the union
initialize at once. can be initialized.
****
44