0% found this document useful (0 votes)
40 views44 pages

CP New

Dear Students, For C Programming Lab Practical Exam the following programs are excluded, Part - A 9. Program to find the roots of Quadratic equation. 12. Program to perform addition and subtraction of Matrix. PART - B 7. Program to read and display Multiply mxn Matrix using function. 12. Demonstrate the difference between the Structure and Union. Thank you.

Uploaded by

likithm678
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)
40 views44 pages

CP New

Dear Students, For C Programming Lab Practical Exam the following programs are excluded, Part - A 9. Program to find the roots of Quadratic equation. 12. Program to perform addition and subtraction of Matrix. PART - B 7. Program to read and display Multiply mxn Matrix using function. 12. Demonstrate the difference between the Structure and Union. Thank you.

Uploaded by

likithm678
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/ 44

Unit – 2 (14 Hours)

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.

Arrays: One Dimensional arrays - Declaration, Initialization and Memory


representation; Two Dimensional arrays - Declaration, Initialization and Memory
representation.

Strings: Declaring & Initializing string variables; String handling functions - strlen,
strcmp, strcpy and strcat; Character handling functions - toascii, toupper, tolower,
isalpha, isnumeric etc.

Unit – 3 (14 Hours)

Pointers in C: Understanding pointers - Declaring and initializing pointers,


accessing address and value of variables using pointers; Pointers and Arrays;
Pointer Arithmetic; Advantages and disadvantages of using pointers;

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.

User defined data types: Structures - Structure Definition, Advantages of


Structure, declaring structure variables, accessing structure members, Structure
members initialization, comparing structure variables, Array of Structures;
Unions - Union definition; difference between Structures and

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];

Types of array: Arrays are classified based on the number of subscripts/index.


1. 1-Dimensional array.
2. 2-Dimensional array.
3. Multi-Dimensional array.

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

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

Accessing array location:


Elements of an array are accessed by specifying the index of the desired element within the
square [] brackets after the array name.
Example: s[3]➔ This will access the 4th location of array in the above memory
representation.

2
s[0]➔ This will access the 1st location of array in the above memory representation.

Points to take care while working with an array:


1. s[1.5]➔ Array index must be always in integer form, decimal/fractional numbers are not
allowed.
2. Array index cannot be accessed outside the array bounds.
Example: s[5] cannot be accessed in the above memory representation.

Initialization of 1-Dimensional array:

There are two ways to initialize an array


1. Size specified directly:
Syntax: Data type array name[size]={ele1,ele2,…….,ele n};
Example: int a[5]={2,4,6,8,10};
In the above example we have specified the size of an array as 5 directly in the initialization
statement. Compiler will assign the set of values to the particular element of the array.
a[0] a[1] a[2] a[3] a[4]
2 4 6 8 10

2. Without specifying Size:


Syntax: data type array name[]={ele1,ele2….,ele n};
Example: int a[]={2,4,6,8,10};
In the above example we do not provide size to array but instead we provide the set of
values to the array. Compiler counts the number of elements inside pair of braces and
determines the size of an array.
✓ int a[3]={1,2,3,4,5,6,7}; ➔ In this case, it is a legal initialization. The compiler will
consider only first 3 elements and ignore the rest of the elements inside the braces.

Program To Accept And Display The Elements Of 1-Dimensional Array:


#include<stdio.h>
#include<conio.h>
void main()
{
int s[50],i;
clrscr();
printf(“enter the size of an array\n”);
scanf(“%d”,&n);
printf(“enter %d elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&s[i]);
}
printf(“content of an array are\n”);
for(i=0;i<n;i++)
{

3
printf(“%d\n”,s[i]);
}
getch();
}

Program To Search An Element In An Array Using Linear Search Technique:

//linear search technique


#include<stdio.h>
#include<conio.h>
void main()
{
int s[100],i,n,ele,found=0;
clrscr();
printf(“enter the size o an array\n”);
scanf(“%d”,&n);
printf(“enter %d elements\n”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&s[i]);
}
printf(“enter the search element\n”);
scanf(“%d”,&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
found=1;
break;
}
}
if(found==1)
{
printf(“search is successful”);
printf(“element is found in %d location”);
}
else
{
printf(“unsuccessful search”);
}
getch();
}

Program to Display Sum And Average Of An Array:

#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();
}

Program to Display smallest Element In An Array:

#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

1,0 1,1 1,2 1,3


1
2,0 2,1 2,2 2,3
2

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.

Initialization of 2-dimensional array:

• Initializing using array within array syntax: For initializing 2-dimensional array we can
assign the values to each element as array within array.

Syntax: Data type array name[row][column]={


{ele1,ele2,… ...... ele column},
{ele1,ele2,… ........ ele column},
.
.
.
{ele1,ele2,……ele column}
};
Example: int a[3][2]={

{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};

Program To Accept 2-Dimensional Array And Display It:

#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();
}

3. Multi-Dimensional Array: Array with more than 2 subscripts.

Syntax: type name[size1][size2]...[sizeN];

Example: int threedim[5][10][4];

Program to Add Two Square Matrix:

#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]);
}

Program to delete an element from 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=pos-1; i<=n-1;i++)
{
a[i]=a[i+1];
}

10
printf(“ the elements of array are”);
for(i=0;i<n;i++)
printf(“%d\t”, a[i]);
}

Program to sort an array using insertion sort:


#include<stdio.h>
void main()
{
int a[100], i, j, 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]);
for(i=1; i<=n-1;i++)
{
pos=i;
while(pos>0 && a[pos]<a[pos-1])
{
t= a[pos];
a[pos]=a[pos-1];
a[pos-1]=t;
pos--;
}
}
printf(“ the sorted elements of array are”);
for(i=0;i<n;i++)
printf(“%d\t”, a[i]);
}

Program to sort an array using selection sort:


#include<stdio.h>
void main()
{
int a[100], i, j, pos, ele,n;
printf(“ enter the size of array”);
scanf(“%d”, &n);
printf(“ Enter %d elements”, n);

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.

Initialization of a string: A string can be initialized in two ways.


1. Syntax: char string name[size]={‘char1’,’char2’,……’char n’,’\0’};
Example: char str[]={‘h’,’e’,’l’,’l’,’o’,’\0’};
2. Syntax: char string name[size]={“string”};
Example: char str[]={“hello”};

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();
}

2. getchar And putchar Functions:


The getchar() function reads a character from the terminal. This function reads only a single
character at a time. getchar() is iteratively used to accept a string. getchar() do not append
‘\0’ at the end of the string.
The putchar() function displays only a single character at a time. putchar() is iteratively
used to display a string upto ‘\0’ at the end of the string.

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();
}

3. gets() And puts() Functions:


The gets() function reads a line from standard input until terminated by a new line (\n). It
automatically appends ‘\0’ at the end of the string.
The puts() is used to display a string until end of the string character. It adds ‘\n’ after
displaying.
Syntax: gets(string name);
puts(string name);

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();
}

4. sscanf() And sprintf() Functions:


These functions are not used to accept or display the string in standard input-output devices.
Instead it is used to accept/display the string into a buffer variable. It is used for formatting
string.

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);

Syntax: sprintf(“buffer string,format specifiers,arguments);


Here the arguments send the information to the buffer string.
Example: char str[100];
sprintf(str,”%s%d”,”ram”,23);
puts(str);

2-Dimensional Array Of Character Type/String:

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

Accessing 2-Dimensional Character Array Elements:

It requires only row index for accessing a 2-dimensional char array elements.
Syntax: array name[index];
Example: puts(names[2]);

Initialization Of 2-Dimensional Character Array Elements:


Syntax: char array name[row][column]={“string1”,”string2”,…….”string n”};
Example: char names[2][20]={“mahatma”,”Gandhi”};
Each character occupies 1 byte of storage in the memory.

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();
}

String Built-In Functions:


C supports variety of string manipulation functions which can be used with the inclusion
of string.h header file.
The various types of string built-in functions are:
1. strlen function: It is used to find the length of the string. ‘\0’ is not counted. It returns the
number of character in the string.
Example: int len;
char str[10]={“success”};
len=strlen(str);
Here the length of the string is 7.
2. strcpy function: It is used to copy the contents of source string to the destination string.
Example: int len;
char str1[10]={“success”},str2[10];
strcpy(str2,str1);
puts(str2);
Here str1 is the source string and str2 is the destination string.
3. strcat function: It is used to join two strings, it joins second string to the first string.
Example: int len;
char str1[20]={“dennis”},str2[20]={“ritche”};
strcat(str1,str2};
Here the output will be dennis ritche.
4. strcmp function: It is used to compare two strings based o ASCII values.
It returns 0 if both are same.
It returns 1 if first string is greater than second string.

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;

ret = strstr(name, find);

printf("The substring is: %s\n", ret);


ouptput: Ritchie

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();
}

Program To Concat Two Strings Without Using Built-In Functions:

#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();
}

Program To Compare 2 Strings Without Using Built-In Function:

#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();
}

Program To Convert Upper Case Character To Lower Case Character:


#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
int i;
printf(“enter a string”);
gets(s1);
for(i=0;s1[i]!=’\0’;i++)
{
s2[i]=s1[i]+32;
}
s2[i]=’\0’;
puts(s1);
puts(s2);
getch();
}
Program To Convert A String Into A Non-Readable Form (Encryption):

#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.

Program to use of islower,isupper,tolower(),toupper().


#include<ctype.h>
#include<stdio.h>
int main()
{
char n;
printf("\nEnter an alphabet=");
n=getche();
if(islower(n))
n=toupper(ch);
else
ch=tolower(ch);
printf("\nNow alphabet=%c",n);
return(0);
}
Output
Enter an alphabet=A
Now alphabet=a

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.

Declaring a pointer variable:


Syntax: data type * variable name;
Example: int *p;

Assigning address to a pointer variable:


Syntax: pointer variable=&variable;
Example: p=&x;

Key points to remember about pointers in C:


✓ Normal variable stores the value whereas pointer variable stores the address of another
variable.
✓ The content of the C pointer always be a whole number that is address.
✓ The size of any pointer is 2 bytes (for 16 bit computer).
✓ & symbol is used to get the address of the variable.
✓ * symbol is used to get the value of variable that the pointer is pointing to.
✓ The content of a memory location when it is accessed by variable name we say it is a direct
access. If you refer the contents of memory location through the pointer then we say it is
indirect access. The indirect access is done through on indirectional operator ‘*’.
Example: x = 5; // assigns the value ‘5’ to the variables ‘x’ directly

p=&x;

*p=5;

The location pointed by P is initialized with 5 which is the location named as ‘x’

y = x; ---> Direct assignment

*q = *p; ---> Indirect assignment

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.

A pointer to a pointer is a form of multiple indirection, or a 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 as shown below.

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;

/* take the address of var */


ptr = &var;

22
/* take the address of ptr using address of operator & */
pptr = &ptr;

/* take the value using pptr */


printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);

return 0;
}
When the above code is compiled and executed, it produces the following result −

Value of var = 3000


Value available at *ptr = 3000
Value available at **pptr = 3000

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>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr;

/* let us have array address in pointer */

23
ptr = var;

for ( i = 0; i < MAX; i++) {

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the next location */


ptr++;
}

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

Pointers and Arrays:

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.

arr has two purpose -

It is the name of the array


It acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default
For better understanding of the declaration and initialization of the pointer - click here. and
refer to the program for its implementation.

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) //pointer with an array


is same as:

a[i]

Pointer to Multidimensional Array


Let's see how to make a pointer point to a multidimensional array. In a[i][j], a will give the
base address of this array, even a + 0 + 0 will also give the base address, that is the address
of a[0][0] element.

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.

Example: printf() and scanf() are present in stdio.h header file.


strcst(),strstr(),strcmp(),gets(),puts() are present in string.h header files.
sqrt,min,max, etc., are present in math.h header files.

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.

Steps in Function creation:


Function creation in C involves three steps:
STEP1: Write the function prototype in the global declaration section, that is giving
information to compiler about the function name, arguments and return value.
STEP2: Define the function that is writing the instructions of the functions to do a
particular task. Declare the datatype of return value and declare the function arguments.
STEP3: Use the function by calling its name and passing argument if any.

Note: Arguments/parameters are values which are supplied to the function. Return value is
the value returned by the function.

For example: Program to compute power of a number using functions.


#include<stdio.h>
int square(int);
void main()
{
int num;

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.

Syntax for declaring prototype of function:


Function prototype is used to inform the complier about the user defined function. It is
written in the global declaration section.
Syntax:
returntype function name(argument list);
Example:
int largest(int, int);

Syntax for defining a function:


return type function name(datatype arg1 datatype arg2)
{
local declaration
statements
return value[variable]
}

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);

Communication between functions:


Compunction happens by invoking the function and passing arguments and inturn the
function executes and may return value.
There are two types of parameters or arguments:
1. Actual parameter: Arguments found in the function call is called as actual parameter.
2. Formal parameter: Arguments found in the function definition is called as formal
parameter.

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;
}

Program to Compute Largest Of Two Numbers Using Functions:

#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”);
}

3. Functions Without Arguments And With Return Value:


It is a type of function that returns value but does not have arguments.
Syntax: Data type function name()
{
body of the function
}
Program To Compute Largest Of Two Numbers:
#include<stdio.h>
#include<conio.h>
int largest();
void main()
{
int res;
res=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;
}
}

4. Functions Without Arguments And Return Value:


It is a type of function that does not contain both arguments and return value.
Syntax: void function name()
{
body of the function.
}

Program To Compute Largest Of Two Numbers:

#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.

Program To Compute Permutation:


#include<stdio.h>
#include<conio.h>
Float npr(int, int);
int factorial(int);
void main()
{
int n,r;
float res;
printf(“enter n and r\n”);
scanf(“%d%d”,&n,&r);
res= npr(n,r);
printf(“ npr=%f”,res);
}
float npr(int n, int r)
{
float res;
res=fact(n)/fact(n-r);
return res;
}
int factorial(int n)
{
intf,i;
for(i=1;i<n;i++)
{
f=f*I;
}
return f;
}

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.

Parameter Passing Mechanisms:


There are two ways to pass value or data (parameter/arguments) to function in C-language
they are:
1. Call by value: Actual parameter values are copied to formal parameter. In call by
value, modification of formal parameter in the function will not affect the original
value ie., actual values.

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.

Program For Swapping Two Numbers Using Call By Reference:


#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);
printf(“After Swap: x=%d, y=%d”,x,y);

void swap(int *m, int *n)


{
int temp;
temp=*m;
*m=*n;
*n=temp;
}

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

min=minarray(numbers,6);//passing array with size


printf("minimum number is %d \n",min);
return 0;
}

2. Passing 2-dimensional array to the function:


2-Dimensional array can be passed by passing the array name and array size both row and
column size. Therefore, three arguments are required.
Arguments required are:
1. Array name.
2. row size.
3. column size.

Example:
#include <stdio.h>

// n must be passed before the 2D array


void print(int m, int n, int arr[][n])

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;
}

Passing Strings to A Function:

1. 1-dimensional array of string: To pass a one dimensional string to a function as an argument


we just write the name of the string array variable.

Example:

#include <stdio.h>

void displayString(char []);

int main(void) {
// variables
char message[] = "Hello World";
// print the string message
displayString(message);
return 0;
}

void displayString(char str[]) {


printf("String: %s\n", str);
}

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;

// print the name of the cities


displayCities(cities, rows);

return 0;
}

void displayCities(char str[][50], int rows) {


// variables
int r, i;

printf("Cities:\n");
for (r = 0; r < rows; r++) {
i = 0;
while(str[r][i] != '\0') {
printf("%c", str[r][i]);
i++;
}
printf("\n");
}
}

Passing Structure to a Function:


1. Passing members of structures: To pass a structure member to a function we just write
the name of structure variable dot along with member name.
Usage: s.age
Example:
struct student
{
char name[20];
int reg no;
};
main()

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);
}

3. Passing Entire Structure As Call By Reference: To pass an entire structure to a


function using reference method we just write the name of structure variable prefixed by
address operator. To access the member values we write structure variable directional
symbol and member name.
Usage: s➔names
Example:
struct student
{
char name[20];
int reg no;
};
main()
{

38
struct student a;
display(&a);
}
void display(struct student *s)
{
puts(s➔names);
}

User Defined Data Types:

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.

Declaring a structure variable:


Syntax:
struct structure name variable name;
Example:
struct student s1,s2;

Use of typedef in structures:

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;

Accessing Structure Members:


Members of the structures are accessed using .operator(dot operator).
Syntax:

39
structure variable name.members name
Example:
s1.name
printf(“regno=%d”,s1.regno);

Memory Representation of structure:


Total memory allocated=size of all members of the structure. The members are stored in
the contiguous memory location.

Example:
struct student
{
char name[20],course[5];
int regno,m[5];
};

20 bytes 5 bytes 2 bytes 10 bytes


name Course Regno Marks

Size of structure student is 37 bytes.

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.

Program To Accept Name, Course, Regno And Marks Of 5 Subjects Of A Student.


Compute The Total Marks And Display The Details:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20],course[5];
int regno,m[5];
};

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:

S[0] name course regno

S[1] course regno


name
S[2] course regno
name
S[3] name course regno

name course regno


S[4]

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:

Declaration of unions is same as structures.


Syntax:
union union name variable name;
Example: union student s1,s2;

Accessing the union elements:

Union elements can be accessed using dot(.) operator.


Syntax:
union variable name.element name.

Example: union s1.reg no

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

You might also like