0% found this document useful (0 votes)
3 views

UNIT 3

The document provides a comprehensive overview of arrays and strings in C programming, detailing their definitions, classifications, declarations, initializations, and examples of usage. It explains single-dimensional and multi-dimensional arrays, along with their advantages and disadvantages, and introduces string manipulation, including declaration, initialization, and common library functions. Additionally, it includes examples of functions for string operations and basic array manipulations.

Uploaded by

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

UNIT 3

The document provides a comprehensive overview of arrays and strings in C programming, detailing their definitions, classifications, declarations, initializations, and examples of usage. It explains single-dimensional and multi-dimensional arrays, along with their advantages and disadvantages, and introduces string manipulation, including declaration, initialization, and common library functions. Additionally, it includes examples of functions for string operations and basic array manipulations.

Uploaded by

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

ARRAYS

Definition :
An Array is a collection of similar data items that are stored under a common name. A
value in array is identified by index or subscript enclosed in square brackets with array
name.
The individual data items can be integers, floating point, characters and so on, but
they must be the same type and same storage class. Each element is referred by specifying
the array name with subscript, each subscript enclosed in square brackets andit must be a
non-negative integer.
If ‘n’ elements in the array ‘a’ then the elements are
a[0],a[1],a[2],a[3],…..a[n-1].
Arrays can be classified into
 Single Dimensional arrays
 Multi – Dimensional arrays
Single dimensional array:
A single dimensional or one-dimensional array consists of a fixed number of elements of
the same data type organized as a simple linear sequence.
The elements of a single dimensional array can be accessed by using a single subscript.
Eg: X[1],X[2]….X[n]
The subscript can begin with number Zero.
Declarations of arrays:
The general form of array declaration is

data_type array name[size or subscript of the array];

data_type - Type of the data.


Size or subscript - The maximum no of elements that the array can hold.
Eg: int a[5];
float height[50]
Array ‘a’ can hold maximum of 5 elements.
a

Initialization of arrays:
We can initialize the elements of arrays in the same way as the ordinary variable when
they are declared.
The general form:
data-type array-name[size] = {list of values};

Eg: int number[3] ={0,0,0};


Page 75

Will declare the variable number as an array of size 3 and will assign Zero to each
element.
Eg: int number[5] = {3,4,5};
will initialize the first three elements and the remaining two elements to ZERO.
The size may be omitted. In such cases the compiler allocates enough space for all
initialized elements

Eg: float counter [ ] ={0.0,15.75,-10};


will declare the counter array to contain the three elements.

Example:1 To find the sum of array elements


#include<stdio.h>
main()
{
int a[10],n,i,sum=0;
printf("\nEnter the total no of elements in the array:");
scanf("%d",&n);
printf("\nEnter the elements one by one");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
sum=sum+a[i];
printf("Sum =%d\t",sum);
}
Output:
Enter the total no of elements in the array: 5
Enter the elements one by one 4 5 23 10 50
Sum =92

Example:2 Program to arrange an array of elements in ascending order.


# include <stdio.h>
main()
{
int i,j,n,temp,a[20];
printf("Enter the number n:");
scanf("%d", &n);
printf("Enter the numbers:");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
for(i=0;i<n;i++)
Page 76

printf("%d\t", a[i]);
}
Output:
Enter the number n: 5
Enter the numbers: 3 2 8 1 4
1 2 3 4 8

Two dimensional array:


Declarations:
Two dimensional arrays is also called table. Each dimension of the array is indexed from
Zero to its max.Size-1. The first index selects the row and the second selects the column
within that row.
data-type array-name [rowsize][columnsize];

Eg:
int a[3][4];
3-rowsize; 4-column size;

Initialization of two dimensional arrays:


Like one dimensional, two dimensional arrays can be initialized by following their
declaration with a list of initial values enclosed with braces
Eg:
int table[2][3]={0,0,0,1,1,1};

initializes the elements of the first row to ZERO and second row to ONE.
The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}};

If the values are missing in an initializer they are automatically set to ZERO.

Example: Matrix Multiplication

#include <stdio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
printf("\n\t Enter First Matrix : ");
for(i=0;i<3;i++)
{
Page 77

for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n\t Enter Second Matrix : ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{ c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("\n\t Matrix Multiplication is : \n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",c[i][j]);
}
printf("\n");
}
}
Output:
Enter First Matrix :
1 2 1
3 2 1
1 2 1

Enter Second Martix :


3 3 3
1 2 1
1 1 1
Matrix Multiplication is :
6 8 6
12 14 12
6 8 6
Page 78
Multi dimensional array:

Arrays can have more than one dimension, these arrays-of-arrays are called
multidimensional arrays
The general form:

type array-name[s1][s2]…[sn];
Eg:
int a[3][5][12];
float b[5][4][5][3];

a is a 3-dim array declared to contain 180 integer elements


b is 4-dim elements array containing 300 elements of floating point type.

Advantages and Disadvantages of Array in C Programming


Advantages

 It allocates memory in contiguous memory locations for its elements. It


does not allocate any extra space/ memory for its elements. Hence there is
no memory overflow or shortage of memory in arrays.
 Iterating the arrays using their index is faster compared to any other
methods like linked list etc.
 It allows to store the elements in any dimensional array – supports
multidimensional array.
Disadvantages

 It allows us to enter only fixed number of elements into it. We cannot alter
the size of the array once array is declared.

 Inserting and deleting the records from the array would be costly since we
add / delete the elements from the array, we need to manage memory
space too.

STRINGS
Strings
A string is sequence of characters enclosed within double quotes.
Eg: “Make hay while the sun shines”
Important points about string literal constants are as follows:
 Every string literal constant is automatically terminated by null
character ie ‘\0’.
 String literals are enclosed within double quotes(“A”) whereas
character literals are enclosed within single quotes(‘A’).
 The length of a string is defined as the number of characters
present in it.
 In C language string type is not separately available and character
Page 79

pointers are used to represent strings.


Declaration of Strings
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic
syntax for declaring a string.
char str_name[size];
Example : char s[5];

In the above syntax str_name is any name given to the string variable and size is used
to define the length of the string, i.e the number of characters strings will store.
Note: There is an extra terminating character which is the Null character (‘\0’) used to
indicate the termination of a string that differs strings from normal character arrays.

Initializing a String
A string can be initialized in different ways.
2 Ways to Initialize a String in C
1. Assigning a string literal : String literals can be assigned without size. Here, the
name of the string str acts as a pointer because it is an array.
char str[] = "hello";
or
char str[6] = "hello";
2. Assigning character by character : We can also assign a string character by
character. But we should remember to set the end character as ‘\0’ which is a null
character.
char str[] = { 'h','e','l','l','o','\0'};
or
char str[6] = { 'h','e','l','l','o','\0'};

Reading strings from terminal:


1. Using scanf()
The scanf() function is used with %s format specification to read a string of characters.
Eg:
char add[15];
scanf(“%s”, add);

The problem with scanf() is that it terminates its input on the first white space it finds.
Therefore, if the input is typed as,
Page 80

“NEW YORK”
then only the string “NEW” will be stored in array add.
2. Reading a line of text using gets():
It is possible to read a line of text with the help of gets() function.

Example :
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name,); // read string
printf("Name: ");
puts(name); // display string
return 0;
}

Writing strings on screen:


The printf() function with %s format is used to print strings on screen. It is used to
display an array of characters terminated by null character.
Eg: printf(“%s”, name);

String Library Functions


The C string library provides a large number of functions that can be used for string
manipulations. The string functions are required to include string.h header file in the
program.
S.No Function name Role
1 strlen() Calculates the length of string
2 strcpy() Copies a string to another string
3 strncpy() Copies at most n characters of the src to the string
dest
4 strcat() Concatenates(joins) two strings
5 strncat() Appends at the most n characters of the string src
to the string dest
6 strcmp() Compares two string
7 strncmp() Compares at the most n characters of two strings s1
and s2
8 strncmpi() Compares at the most n characters of two strings s1
and s2 without case sensitivity.
9 strlwr() Converts string to lowercase
10 strupr() Converts string to uppercase
11 strrev() Reverse the content of a string s
12 strchr() Scans a string for the first occurrence of a given
character
13 strstr() Finds the first occurrence of a substring (s2) in
Page 81

another string (s1).


14 atoi() Converts string to integer
1. strcat() function
Definition:
strcat( ) function in C language concatenates two given strings. It concatenates source
string at the end of destination string.

Syntax
char * strcat ( char * destination, const char * source );
Eg:
void main()
{
char src[]="c", dest[]="programming";
strcat(src,dest);
printf("concatenated string is %s",src);
}
Output:
concatenated string is c programming

2. strcpy() function

Definition:
strcpy( ) function copies contents of one string into another string.

Syntax
char * strcpy ( char * destination, const char * source );

Eg:
void main()
{
char src[]="spark",dest[15];
strcpy(dest,src);
printf("%s is copied to dest string\t",dest);
}
Output:
spark is copied to dest string.

3. strlen() function
Definition
strlen( ) function in C gives the length of the given string.
Syntax
int strlen ( const char * str );

Eg:
void main()
{
char string[]="spark";
Page 82

int len;
len=strlen(string);
printf("length of %s is %d\t",string,len);
}
Output: length of spark is 5.

4. strcmp() function

Definition
This function compares two strings passed as parameters and returns either
+ve number,0,-ve number.
+ve value indicates string1 > string2.
0 indicates string1 and string2 are equal.
-ve value indicates string1 < string2.
Syntax

int strcmp ( const char * str1, const char * str2 );

Eg:
#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="spark",string2[]="programming";
int cmp;
cmp=strcmp(string1,string2);
if(cmp>0)
printf("%s > %s",string1,string2);
else
{
if(cmp<0)
printf("%s < %s",string1,string2);
else
printf("%s = %s",string1,string2);
}
}
Output:
spark > programming.
This is because alphabetically p comes first then s.so the string compare function returns
difference between ascii of s and p which would be +ve.

5. strrev() function
Definition
This function accepts single string as parameter and reverses that string.
Syntax
char * strrev(char *s)

Eg:
Page 83

#include <stdio.h>
#include <string.h>
void main(void)
{
char string[]="spark";
strrev(string);
printf("reverse string is %s",string);
}
Output
reverse string is kraps.

6. strlwr() function
Definition
 strlwr( ) function converts a given string into lowercase.
Syntax
char *strlwr(char *string);

Eg:
#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="SPArk";
strlwr(string1);
printf("%s is in lower case",string1);

}
Output
spark is in lower case.

7. strupr() function
Definition
 strupr( ) function converts a given string into uppercase.
Syntax

char *strupr(char string);


Eg:
#include<stdio.h>
#include<string.h>
voidmain(void)
{
char string1[]="SPArk";
strupr(string1);
printf("%s is in upper case",string1);

}
Output
SPARK is in upper case.
Page 84
8. atoi()
converts the string argument to an integer .
#include <stdio.h>
#include <string.h>
void main () {
int val;
char str[20]=”989”;
val = atoi(str);
printf("String value = %s, Int value = %d\n", str, val);

}
Example :1 Program to reverse a given string
#include <stdio.h>
main()
{
char s[80], c;
int i=0,k;
c = getchar();
while( c != ‘\n’)
{
s[i] = c;
i++;
c= getchar();
}
s[i] = ‘\0’;
printf(“Length = %d\n”, i);
printf(“%s”, s);
for(k=i-1; k >=0; k--)
printf(“%c”, s[k]);
}
Output:
Input: shar
Output: rahs
Example :2 : Program to Check a Given String is Palindrome or not
#include <stdio.h>
#include <string.h>
void main()
{
char s1[25],s2[25];
printf("Enter the string: ");
gets(s1);
strcpy(s2,s1);
strrev(s2);
if(!strcmp(s1,s2))
printf("string is palindrome");
else
Page 85

printf("string is not palindrome");


}
FUNCTIONS

Definition of Function:
A Function is a self contained block or a sub-program of one or more statements that
performs a special task when it is called.

Need for functions:


1. Functions are very much useful when a block of statements has to be
written/executed again and again.
2. Functions are useful when the program size is too large or complex. Functions are
called to perform each task sequentially from the main program. It is like a top-
down modular programming technique to solve a problem.
3. Using functions, large programs can be reduced to smaller ones. It is easy to debug
and find out the errors in it.

Types of Functions:
1. Library or Built-in Functions
Built in Functions are pre defined functions.
e.g., scanf( ),printf( ),getch(),exit(),etc.
2. User defined Functions

User-Defined Functions
Functions defined by the users according to their requirements are called user-defined
functions. These functions are used to break down a large program into small functions.

Advantage of User defined function:


1. Reduce the source code
2. Easy to maintain and modify
3. It can be called from any where in the program.

Defining a Function:
Two principal components exists in defining a function
(i) First line (includes the name of the function and argument declaration)
(ii) Second line (body of the function)
First line contains the type specification of the value returned by the function followed
by function name and set of arguments separated by commas. Each argument is preceded
by its associated type declaration.

Format:
Page 86
data type function name (type1 arg1, type2 arg 2,………, typeN arg n)
{
<Local declaration>
………………………
< statement block >
………………………
………………………
return(variable or expression);
}

Note:
data type is the value return by the function and arguments expected.
arg 1,arg 2,….,arg n are the arguments which are variable that will receive the values from
the calling program. name is the name of the function by which the function is called by
the calling program.

Local declaration: Referred to as local variables and are used only inside the function.
Statement block: Consists of a set of statements and built-in functions which are
executed as the function is called.
Return: The result is returned to the calling program through a return statement that
normally appears at the end of a function block. Note that the function block starts and
ends with braces { }

Eg: int fact( int k)


{
int i, p=1;
for(i=1;i<=k;i++)
p=p*i;
return(p);
}

Accessing a function: (Function calling)


A function can be accessed by specifying its name, followed by a list of
arguments enclosed in parenthesis and separated by commas.
General Form:
function_name (list of arguments);

The arguments appearing in the function call are referred to as actual arguments
main()
{
………..
add(a,b); // function calling. a and b are Actual arguments.
………..
}
Page 87

add function_name
a,b actual arguments
Function Prototype:
Function prototypes are usually written at the beginning of the main ( )
program.
The general form of function prototype:

data type function_name (data_type1 arg1, data_type2 arg2,…., data_typeN argN);


Data type represents the data type of the item that is returned by the function.
data_type1 arg1, data_type2 arg2,…., data_typeN argN represents the data type of the
arguments arg1, arg2,……arg n.
Eg: int big (int a, int b);
int fact(int k);
** Function prototypes are not mandatory in C.
They facilitates error checking between the calls to a function and corresponding
function definition

S.no C function aspects syntax


1 function definition return_type function_name ( arguments list )
{
Body of function;
}
2 function call function_name ( arguments list );
3 function declaration return_type function_name ( argument list);

Formal parameters:
Passing the parameters from the called functions [user defined function] to the
calling functions [main function]. The arguments in the function declaration and definition
are called formal parameters.
Actual arguments:
These are the parameters transferred from the calling function [main
function] to the called function [user defined function]. The arguments in function calling
in main ( ) is called Actual arguments.
Note:
o Actual Argument – This is the argument which is used in function call.
o Formal parameter – This is the parameter which is used in function
definition.

Categories of Functions:
1. Function with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and with return values.
4. Function with no arguments and with return values.
Category 1: Functions with no arguments and no return values:
When a function has no arguments, it does not receive any data from the calling
Page 88

function. In effect there is no data transfer between the calling function and the called
function.
Calling Function Analysis Called Function
main() fun1()
{ {
-------- ----
--------- No arguments passed ----
fun1(); ----
----- }
----- No values Sent back
}
Eg:
#include<stdio.h>
main()
{
void add(void);
add( ); // Calling function without passing any argument
}
void add ( )
{
int a,b,c;
printf(“Enter two numbers “);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“ Sum is …%d”,c);
}
Output:
Enter two numbers
10
20
Sum is … 30
Category 2: Functions with arguments and no return values:
Calling Function Analysis Called Function
main() fun1(x,y)
{ {
-------- ----
--------- arguments passed ----
fun1(a,b); ----
----- }
----- No values Sent bank
}
When a single value is passed to a function via an actual argument the value of actual
argument is copied into the function. Therefore the value of the corresponding formal
parameter can to alter within the function but the value of the actual argument within the
calling routine will not change. This procedure for passing the value of an argument to a
function to is known as passing by value.
Example Program:
#include<stdio.h>
Page 89

main()
{
void add (int,int );
int a,b;
printf ("Enter two values:”);
scanf(“%d%d”,&a,&b);
add (a,b);
}
void add (int x, int y)
{
int z;
z=x+y;
printf ("Sum is ….%d”,z);
}
Output:
Enter two values :
10
20
Sum is …. 30

Category 3: Functions with arguments and with return values:


Return statement:
Information is returned from the function to the calling position of the program via return
statement
Syntax :-
return expression ;
If the function returns a value the function access is often written as assignment statement
Eg : y =polynomial(x);
If the function does not return anything the function access appears by itself
Eg : display ( a, b , c );

Calling Function Analysis Called Function


main() fun1(x,y)
{ {
-------- ----
--------- arguments passed ----
c=fun1(a,b); ----
----- values Sent bank return(y);
----- }
}
Note :
The number of actual arguments must be the same as the number of formal
parameters and each actual argument must be of same data type as its corresponding
formal parameter
Eg:
# include <stdio.h>
Page 90

main ( )
{
int add(int,int );
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“ Sum is …%d”,c);
}
int add( int x,int y)
{
int z;
z=x+y;
return(z);
}
Output:
Enter two values : 10 20
Sum is … 30
Category 4: Functions without arguments and with return values:

Calling Function Analysis Called Function


main() Data_type fun1()
{ {
int z; int y=5;
-------- No arguments passed ----
--------- ----
z=fun1(); values Sent bank return(y);
----- }
-----
}
 Here no arguments are passed through the main() function, but the called function
returns the values.
 The called function is independent. It reads values from the keyboard or generates
from initialization and returns the values.
 Here both calling and called functions are partly communicated with each other.

Eg:
#include<stdio.h>
main()
{
int sum();
c=add();
printf(“sum is …%d”,c);
}
int add ( )
{
int a,b,c;
printf(“Enter two numbers”);
Page 91

scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
Output:
Enter two numbers
10
20
Sum is …30

Argument passing method in C


The argument passing method in C language are classified as :
1. Pass by value/Call by value
2. Pass by address/Call by reference

1. CALL BY VALUE/ PASS BY VALUE:-


 The method of passing argument by value is also known as call by value.
 In this method, the values of actual arguments are copied to the formal parameters
of the function.
 When the control return back to main(),changes made in formal parameters will
not affect the actual arguments in main()
Eg: Swapping two variables
#include <stdio.h>
swap(int ,int );
void main()
{
int a,b;
printf("Enter the values of a and b" );
scanf("%d%d",&a,&b);
swap(a,b);
printf("\nIn main() a=%d\tb=%d",a,b);
}
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("\nIn swap function a=%d b=%d",a,b);
}
Output:
Enter the values of a and b
100
200
In swap function a=200 b=100
In main() a=100 b=200

In call by value method the formal parameters are sent as a photocopy of the actual
Page 92

argument. Hence, changes made in the called function will not be reflected in the calling
function.
2. CALL BY REFERENCE:-
 The method of passing arguments by address or reference is also known as Call by
address or Call by reference.
 In this method, the address of the actual arguments is passed to the formal
parameters of the function.
 If the arguments are passed by reference, the changes made in the values pointed
to by the formal parameters in the called function are reflected back to the calling
function.
Eg: Swapping two variables using pointers
#include <stdio.h>
//swap(int ,int );
void main()
{
int a,b;
printf("Enter the values of a and b" );
scanf("%d%d",&a,&b);
swap(&a,&b);
printf("\n In main() After Swapping a=%d\tb=%d\n",a,b);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
Enter the values of a and b
100
200
In main() After Swapping a=200 b=100
In call by reference address of the actual arguments are passed to the called
function and stored in formal parameters. Therefore any changes made using the formal
parameters will be reflected in the calling function.

Comparison between Call by Value and Call by Reference


Call by Value Call by Reference
1. In this method, the value of the variable is 1. In this method, the address of the
passed as an argument. variable is passed as an argument.
2. Memory location occupied by formal and 2. Memory location occupied by formal
actual arguments is different. and actual arguments is same and there is
a saving of memory location.
3. Since a new location is created, this 3. Since the existing memory is used
method is slow. through its address, this method is fast.
4. Any alteration in the value of the 4. Any alteration in the value of the
Page 93

argument passed is local to the function and argument passed is accepted in the calling
is not accepted in the calling program. program.
5. Here is no possibility of wrong data 5. There is a possibility of wrong data
manipulation since the arguments are manipulation since the addresses are used
directly used in an application. in an expression. A good skill of
programming is required here.
RECURSION
A function that calls itself is known as a recursive function. And, this technique
is known as recursion.

Example 1: Factorial of n numbers using recursion


#include<stdio.h>
int fact(int n);
main()
{
int n ,r;
printf ("Enter the value for n:");
scanf("%d",&n);
r=fact(n);
printf("n!=%d\n",r);
}
int fact(int x)
{
int f=1;
if(x>1)
f=x*fact(x-1);
return(f);
}
Output
Enter the value for n: 5
n! =120
Working of above recursive example can be illustrated using following diagrams:
Page 94
Example 2 : Fibonacci Series (Binary recursion)
#include<stdio.h>
int fib(int);
int main()
{
int n, term;
printf(“Enter term no:”);
scanf("%d",&n);
term=fib(n);
printf("Fibonacci series is %d”,term);
}
int fib(int n)
{
if(n==1)return 0;
if(n==2)return 1;
return fib(n-1)+fib(n-2);
}
Output:
Enter term no: 4
Fibonacci term is 2

Applications of Recursion :-
 Towers of Hanoi (Binary recursion)
 Printing Backwards
 Finding Factorial

Advantages of Recursion in C
 Makes the program elegant.
Page 95

 It adds clarity to the program code and also reduces the time to write the
code.
 It is best for solving problems based on tree structures.
Disadvantages of Recursion in C
 It is slower than non recursive programs due to the overhead of maintaining
the stack.
 It requires more memory for the stack.
 For better performance, use loops instead of recursion. Because recursion is
slower.

STRUCTURES

Definition:
A structure is a collection of variables under a single name. These variables can be of
different types. A structure is a convenient way of grouping several pieces of related
information together.
A structure type is defined by,
Syntax 1:
struct tag-name/structure_name
{
datatype member1;
datatype member2;
...
datatype membern;
};
Eg:
struct student
{
char name[20];
int ID;
};
Declare a structure variable
Method 1 :
We can declare structure variables using the tag name anywhere in the program.
Eg:
struct student s1,s2,s3;
declares s1,s2,s3 as variables of type struct student. Each one of these variables has 2
members as specified by the template.
Method 2 :
Struct student
{
char name[64];
char course[30];
int age;
int year;
} s1,s2;
In this case ,the variables are declared immediately.
Page 96

Structure initialization:
Like any other data type, a structure variable can be initialized. For ex,
struct {
char name[64];
char course[30];
int age;
int year;
} student = { “arthi”, “B.SC”, 23, 2008};
C does not permit the initialization of individual structure members within the
template. The initialization must be done only outside the structure using variables.

Accessing members of structure:

1. Using Member Access Operator(.) or Dot Operator


Each member in a structure is accessed using the member operator “.”, which is also
known as dot or period operator.
The syntax is,
variable.member

Eg:
s1.name
s1.id
We would assign the values to the members as,
strcpy(s1.name, “ram”);
s1.id = 1;
We can also get values from users using scanf( );
Eg:
scanf(“%s”, s1.name);
scanf(“%d”, &s1.id);

2. Using Member Structure Pointer Operator or Arrow Operator(->)


Structure pointer operator or Arrow operator is used to access members of structure using
pointer variable.
Syntax:
structure_pointer->member_name;

Arrays of structures
Eg:
struct marks
{
int sub1;
int sub2;
int sub3;
};
struct marks stud[3];
Page 97

The above creates an array of 3 structures. The members can be accessed as follows,
stud[0].sub1 = 45;
stud[0].sub2 = 68;
stud[0].sub3 = 71;

stud[2].sub1 = 60;
stud[2].sub2 = 75;
stud[2].sub3 = 71;

Example 1 : Program for Mark Sheet using array of structure


#include<stdio.h>
struct student
{
int regno;
char name[30];
int mark1;
int mark2;
int mark3;
};
Void main()

struct stud s[3];


int total = 0;
printf(“Enter students details:”);
for(i=0;i<3;i++)
{
printf(“Enter reg number:”);
scanf(“%d”, &s[i].regno);
printf(“Enter name:”);
scanf(“%s”, s[i].name);
printf(“enter mark1:”);
scanf(“%d”, & s[i].mark1);
printf(“Enter mark2:”);
scanf(“%d”, & s[i].mark2);
printf(“enter mark3:”);
scanf(“%d”, & s[i].mark3);
}
printf(“Students Mark Sheet details:”);
for(i=0;i<3;i++)
{
printf(“reg number:%d”, s[i].regno);;
printf(“Student name:%s”, s[i].name);
printf(“mark1:%d”, s[i].mark1);
printf(“mark1:%d”, s[i].mark2);
printf(“mark1:%d”, s[i].mark3);
printf(“Total = %d”, s[i].mark1 + s[i].mark2 + s[i].mark3);
}
Page 98

}
Example 2 : Program for Employee Details using structure

#include <stdio.h>
struct employee
{
char name[100];
int age;
float salary;
char department[50];
};
int main(){
struct employee emp;

printf("Enter Name, Age, Salary and Department of Employee\n");


scanf("%s %d %f %s", &emp.name, &emp.age,&emp.salary, &emp.department);

/* Printing structure members using dot operator */


printf("Employee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n",emp.name, emp.age,
emp.salary,emp.department);

return 0;
}

Output
Enter Name, Age, Salary and Department of Employee
Jack 30 1234.5 Sales
Employee Details
Name : Jack
Age : 30
Salary = 1234.500000
Dept : Sales

Employee Details
Name : Jack
Age : 30
Salary = 1234.500000
Dept : Sales

Unions
Unions follow the same syntax as structures. The major difference is in terms of storage.
In structures, each member has its own storage location, whereas all members of a union
use the same location.
Syntax:
union tag-name
Page 99

{
datatype member1;
Eg:

union student
{datatype member2;
...
datatype membern;
char name[20];int
ID;
};
The union contains 2 elements each of different data type. However, we can use only one of
them at a time. The compiler allocates space that is large enough to hold the largest variable type
in union. In the above ex, name uses 20 byes and id used 2 bytes and union takes the bigger one
as its size. So it is 20 bytes and represents the size of the union.

POINTERS:

Definition:
A pointer is a variable that represents the location (rather than the value) of a data item,
such as a variable or an array.

Key points to remember about pointers in C:

 Pointers in provide an alternative way to access information stored in arrays.


 Pointer techniques are especially valuable when you work with strings.
 C Pointer is used to allocate memory dynamically i.e. at run time.
 The variable of pointer might be any of the data type such as int, float, char,
double, etc.
 Normal variable stores the value whereas pointer variable stores the address of the
 & symbol is used to get the address of the variable.
 * symbol is used to get the value of the variable that the pointer is pointing to.

The uses of pointer:


 Pointers are more efficient in handling the data tables.
 Pointers reduce the length and complexity of a program.
 They increase the execution speed.
 The use of a pointer array to character strings results in saving of data storage
space in memory.

Pointer Declaration:

A Pointer is a numeric variable and, like all variables, must be declared before it can be
used. Pointer variable name should follow the same rules as that of ordinary variable name
Page 100

and must be unique.


Syntax : typename *ptrname;

Typename is any of C’s data types and indicates the type of the variable that the pointer
points to. The asterisk(*) is the indirection operator, and it indicates that ptrname is pointer
to type name and not a variable of type name. Pointers can be declared along with non
pointer variables.

Eg: int *p; char *p;

--Where, * is used to denote that “p” is pointer variable and not a normal variable.

Pointer –Initialization:

int x; *p;
p = &x;

Page 75
This is nothing but a pointer variable p is assigned the address of the variable x. The
address of the variables will be different every time the program is executed.
Reading/Accessing value through pointer:

int x=123, *p;


p = &x;
Here the pointer variable p is assigned the address of variable x.
printf(“%d”, *p); will display value of x 123. This is reading value through pointer
printf(“%d”, p); will display the address of the variable x.
printf(“%d”, &p); will display the address of the pointer variable p.
printf(“%d”,x); will display the value of x 123.
printf(“%d”, &x); will display the address of the variable x.

Example:
#include<stdio.h>
void main()
{
int a=10, *ptr;
ptr=&a;
printf(”\n The value of a is ”,a);
*ptr=(*ptr)/2;
printf(”The value of a is.”,(*ptr));
}
Output:
The value of a is: 10
The value of a is: 5

Pointer Expression & Pointer Arithmetic


C allows pointer to perform the following arithmetic operations:
A pointer can be incremented / decremented.
Any integer can be added to or subtracted from the pointer.
A pointer can be incremented / decremented.

int a,*p1, *p2, *p3;


p1=&a;
p2=p1++;
p3=++p1;
printf(“Address of p where it points to %u”, p1); 1000
printf(“After incrementing Address of p where it points to %u”, p1); 1002
printf(“After assigning and incrementing p %u”, p2); 1000
printf(“After incrementing and assigning p %u”, p3); 1002
void pointers
 In C General Purpose Pointer is called as void Pointer.
 It does not have any data type associated with it
 It can store address of any type of variable

Page 76
Declaration of void pointer:

void * pointer_name;

Eg:
void *ptr; // ptr is declared as void pointer
char cnum;
int inum;
float fnum;
ptr=&cnum; // ptr has address of character data
ptr=&inum; // ptr has address of integer data
ptr=&fnum; // ptr has address of float data

Null Pointer
 NULL pointer is a pointer which is pointing to nothing.
 NULL pointer points the base address of segment

The following declaration declares nptr as a null pointer:

int *nptr=0;

NULL is micro constant which has been defined in the header file stdio.h

The following declaration statement is equivalent to the declaration statement mentioned


above:
int *nptr=NULL;

Pointers and Arrays

Elements of the array are stored in contiguous memory locations. They can be efficiently
accessed by using pointers.
Pointer variable can be assigned to an array. The address of each element is
increased by one factor depending upon the type of data type. The factor depends on the
type of pointer variable defined. If it is integer the factor is increased by 2. Consider the
following example:
int x[5]={11,22,33,44,55}, *p;
p = x; //p=&x; // p = &x[0];
Page 77
Assume the address on x[0] is 1000 then the address of other elements will be as follows
x[1] = 1002
x[2] = 1004
x[3] = 1006
x[4] = 1008

Example:
#include<stdio.h>
main()
{
int i;
int a[5]={1,2,3,4,5};
int *p=a; /* same as int*p= &a[0]
for(i=0;i<5;i++)
{
printf(“%d”,*p);
p++;
}

Array of Pointers
An array of pointers is a collection of addresses. The addresses in array ofpointers
could be the addresses of isolated variables or the addresses of array elements or any other
addresses. The only constraint is that all the pointers in an array must be of the same type.

Eg:
#include<stdio.h>
main()
{
int a=10,b=20,c=30;
int *arr[3]={&a,&b,&c};
printf(“%d\t%d\t%d”,*arr[0],*arr[1],*arr[2]);
}
Output:
10 20 30

Function pointers

 A function pointer (or subroutine pointer or procedure pointer) is a type of pointer.


 A function pointer points to executable code within memory.
 When dereferenced, a function pointer can be used to invoke the function it points to
and pass it arguments just like a normal function call. Such an invocation is also known
as an "indirect" call, because the function is being invoked indirectly througha variable
instead of directly through a fixed name or address.
 Function pointers can be used to simplify code by providing a simple way to select a
Page 78

function to execute based on run-time values.


Syntax:

int ( *ptrfunc) ();


Here, ptrfunc is a pointer to a function that takes no arguments and returns an
integer. DO NOT forget to put in the parenthesis, otherwise the compiler will assume
that ptrfunc is a normal function name, which takes nothing and returns a pointer to an
integer.

Example:
#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add;
result=(*ip)(a,b);
printf("Value after addition is : %d",result);
return 0;
}
int add(int a,int b)
{
int c=a+b;
return c;
}

Array of Function Pointers

In an array of function pointers, array takes the addresses of different functions, and the
appropriate function will be called based on the index number.

Example.:

#include <stdio.h>
float add(float,int);
float sub(float,int);
int main()
{
float x; // variable declaration.
int y;
float (*fp[2]) (float,int); // function pointer declaration.
Page 79

fp[0]=add; // assigning addresses to the elements of an array of a function pointer.


fp[1]=sub;
printf("Enter the values of x and y :");
scanf("%f %d",&x,&y);
float r=(*fp[0]) (x,y); // Calling add() function.
printf("\nSum of two values is : %f",r);
r=(*fp[1]) (x,y); // Calling sub() function.
printf("\nDifference of two values is : %f",r);
return 0;
}

float add(float x,int y)


{
float a=x+y;
return a;
}
float sub(float x,int y)
{
float a=x-y;
return a;
}

Pointers and Structure


Pointer pointing to a structure is known as structure pointers.
General format for pointer structure is:

struct
{
member 1;
member 2;
}variable,*ptr;

Here the variable represents structure type variable and *ptr represents the name of the
pointer.
Example:

#include<stdio.h>
void main()
{
struct account
{
char name[20];
char place[25];
int accno;
};
static struct account m4={“aaa”, “Chennai”,23142};
struct account *ptr;
ptr=&m4;
printf(“%s%s%d”,m4.name,m4.place,m4.accno);
Page 80

printf(“%s%s%d”,ptr->name,ptr->place,ptr->accno);
}
Output:
aaa chennai 23142
aaa Chennai 23142.

You might also like