Sei sulla pagina 1di 72

Function

The function in C language is also known as procedure. To perform any task, we can create function. 
A function can be called many times. It provides modularity and code reusability.

Advantage of Function
Code Reusability
By  creating  functions  in  C,  you  can  call  it  many  times.  So  we  don't  need  to  write  the  same  code 
again and again.
Code Optimization
It makes the code optimized, we don't need to write much code.
Types of Function
In built Function(Library Function)
Printf(); ,Scanf();, clrscr(); , getch();
User Defined Function
which are created by the C programmer, so that he/she can use it many times. It reduces complexity 
of a big program and optimizes the code.
Elements of User Defined Function
1. Function Declaration
2. Function Call
3. Function Definition

1.Function Declaration
a. Function Type (Return Type)
b. Function Name
c. Parameter List (Argument)
d. Terminating semicolon
Syntax –Function Declaration
Type func_name(Parameter list);
Int add(int,int);
Int add(int a,int b);
2 Function Call
Int add (int a,int b);  
Main()
{
Int y;
Y=add(10,20);     
Printf(“%d”,y);
}
3 Function Definition
          Function Header                                    
a Function Type
b Function Name
c Parameter List
          Function Body
d Local variable declaration
e Function statements
f A Return Statement
Function Header
Type function_name(parameter_list)
Int add(int a,intb);
Int add(int,int);
Int add(int x,int y) – Function Definition
Function Body
Header
{
 variable---------x
Statement Function body
Return statement….x
}

e.g.
Int message(void);
Void add(int,int);
Void add(void);

Syntax of Function definition


Type function_name(parameter_list)                   ->Function header
{
Local variable declaration;
Function statement 1;                                             -> Function body
Function statement 2;                                                                                 
………………………………….
………………………………..
A return statement
}
Return Type & Arguments

Function Declaration
Returntype  func  name (arguments);
Int add (int,int);
Void add (void);
Function Definition
Int add(int x,int y)   ->define
{
Statements
}
Main()
{
Int ans;
Ans=add(10,20);   ->Call
}

A. Actual arguments
B. Formal Arguments
Main()
{
Int  ans;
ans=add(10,20);  ->Actual Arguments
int add(int x,int y) ->Formal Arguments
Return Type
1. Return ;
2. Return value;

Int add(int x,int y)
{
Int c;
C=x+y;
Return c;
}

Or
Int add(int x,int y)
{
Int c;
C=x+y;
Return ;
}
Or
Int add(int x,int y)
{
Int c;
C=x+y;
If(c>10)
{Return ;}……  …….  ……
Category of Function

A . Function with arguments and return value
B. Function with no arguments and no return value
C. Function with arguments and no return value
D. Function with no arguments and return value

A . Function with arguments and return value
Ex. Int add (int x,int y)
B. Function with no arguments and no return value
void add(void)
C. Function with arguments and no return value
Void add(int x, int y)
D. Function with no arguments and return value
Int add(void)
Practical Example A. Function with arguments and return value

#include<stdio.h>
#include<conio.h>
int add(int,int); //Function Declaration
void main()
{
int a,b,sum;
clrscr();
printf("Enter first number");
scanf("%d",&a);
printf("Enter Second number");
scanf("%d",&b);
sum=add(a,b); //Function Call
printf("Sum is %d",sum);
getch();
}
//Value of Actual arguments a & b Copy in Formal arguments x,y
int add(int x,int y) // Function Definition
{
int c;
c=x+y;
return c;
//or return(x+y);
}
Function with No Arguments and No return value

#include<stdio.h>
#include<conio.h>
void add(void); //Function Declaration
void main()
{
clrscr();
add(); //Function Call
getch();
}
void add(void) //Function Definition
{

int a,b,ans;
printf("Enter First Number");
scanf("%d",&a);
printf("Enter Second Number");
scanf("%d",&b);
ans=a+b;
printf("Sum is : %d",ans);
}
Function with Arguments and No return value
Void add (int,int) //Declaration
main()
{
int a,b;
clrscr();
printf("Enter first number");
scanf("%d",&a);
printf("Enter Second number");
scanf("%d",&b);
add(a,b); //Function Call
getch();
}
//Value of Actual arguments a & b Copy in Formal arguments x,y
void add(int x,int y) // Function Definition
{
int c;
c=x+y;
Printf(“Addition is %d”,c);
}
Function with NO Arguments and return value
Void sqr (void) //Declaration
main()
{
int ans;
clrscr();
ans=sqr(); //Function Call
Printf(“Squere is %d”,ans);
getch();
}
//Value of Actual arguments a & b Copy in Formal arguments x,y
int sqr(void) // Function Definition
{
int s; or b;
Printf(“Enter a Value”);
Scanf(“ %d”,&s);
Return(s*s);
Or
b=(s*s);
Return b;
}
Nesting of Function

mul()
add()
{
……….
……..
…….
…..
Mul();   -Nesting
}

main()
{
add();
}
Example 1
 #include<stdio.h>
 #include<conio.h>
Int greater (int,int);
Void dis(void);
Main()
{
Clrscr();
Disp();
Getch();
}
Int greater (int x,int y)
If(x>y)
{
Return x;
}
Else
{
Return y;
}
}
Void disp(void)
{
Int a,b,ans;
Printf(“Enter First Number”);
Scanf(“%d”,&a);
Printf(“Enter Second Number”);
Scanf(“%d”,&b);
ans=greater(a,b);  ->Nesting
Printf(“Greate r value is %d”,ans);
}
Example 2
#include<stdio.h>
#include<conio.h>
void func1();
void func2();
void func3();
void main()
{
clrscr();
func1();
getch();
}
void func1()
{
printf("\nIts is function 1");
func2();
}
void func2()
{
printf("\nIts is function 2");
func3();
}
void func3()
{
printf("\nIts is function 3");
}
Example 3 
void italy();
void japan();
void brazil();
void main()
{
clrscr();
printf(" I am in main\n");
italy();
printf("i am finally back in main\n");
getch();
}
void italy()
{
printf("I am in italy\n");
japan();
printf("I am back in italy\n");
}
void japan()
{
printf("i am in japan\n");
brazil();
}
void brazil()
{
printf("i am in brazil\n");
}
Recursion
A function to call itself. Recursive functions are very useful to solve many mathematical problems, 
such as calculating the factorial of a number, generating Fibonacci series, etc.

Int sub(int x)
{
Int i,a;
………..
………..
i=sub(a);   ->Recursion
}

Program
#include<stdio.h>
#include<conio.h>
Int fact(int);
Main()
{
Int  no,ans;
Clrscr();
Printf(“Enter a Number”);
Scanf(“%d”,&no);
Ans=fact(no);
Printf(“Factorial is %d”,ans);
Getch();
}
Int fact(int x)
{
Int f;
If(x==0)
{
Return 1;
}
Else
{
F=x*fact(x-1);   ->Recursion
Return f;
}
}

Call by value & Call by reference


To understand the call by reference, 
you must have the basic knowledge of pointers

Call by value
Original value is not modified
A copy of value is passed to the function
Call by reference
Original value is modified
An address  of a value is passed to the func.
Function Call
a. Call by value     b. Call by reference
Example 
Void disp(int x);
 main()
{
100
Int a=100;                                                                           Value
Disp(a);
}
Void disp(int x)                               2122            - Address
{
X=x+100;
}
Ex. void change(int num) {  
    printf("Before adding value inside function num=%d \n",num);  
    num=num+100;  
    printf("After adding value inside function num=%d \n", num);  
}  
  int main() {  
    int x=100;  
    clrscr();  
      printf("Before function call x=%d \n", x);  
    change(x);//passing value in function  
    printf("After function call x=%d \n", x);  
      getch();  
    return 0;  
}  
Array
Array in C language is a collection or group of elements (data). C array is 
beneficial if you have to store similar elements i.e. it is a collection of similar 
datatypes

Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements 
of an array easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of 
code only.
4) Random Access: We can access any element randomly using the array.
Types of Array
a. One dimensional array                        marks[0]
b. Two dimensional array marks[1]
c. Multidimensional array marks[2]
marks[3]
A. One dimensional array marks[4]
Declaration
data_type array_name[array_size];  
int marks[5];  
         Subscript
Two dimensional array
data_type array_name[row_no][column_no];
Example:
Int subject[2][3];
No of element=r*c
                             2*3=6

column[0] column[1] column[2]


Row[0] [0,0] [0,1] [0,2]

Row[1] [1,0] [1,1]    [1,2]                            

Initialization of one dimensional array
Int a=20;  int sub[5];

sub[0] or int a[4] {10,20,30,40};
sub[1]
sub[2]
10
sub[3]
sub[4]
Sub[2]=10;
Example One dimensional Array
Main()
{
Int sub[5],I,total=0;
Printf(“Enter 5 subject no :”);
For (i=0;i<5;i++)
{
Scanf(“%d”,&sub[i]);
Total=total+sub[i];
}
Printf(“Elements are”);
For(i=0;i<5;i++)
{
Printf(“%d”,sub[i]);
}
Printf(“Total is : %d”,total”);
Getch();
}
//Addition of two array in C
#include<stdio.h>
#include<conio.h>
void main()
{
int arr1[5],arr2[5],arr3[5],i;
clrscr();
printf("Enter 5 number-First Array:\n");
for(i=0;i<5;i++)
{ scanf("%d",&arr1[i]); }
printf("Enter 5 number-Second Array:\n");
for(i=0;i<5;i++)
{ scanf("%d",&arr2[i]); }
for(i=0;i<5;i++)
{
arr3[i]=arr1[i]+arr2[i];
}
printf("Sum of Elements are\n");
for(i=0;i<5;i++)
{
printf("\t%d",arr3[i]);
}
getch();
}
Example Two dimensional Array
Main()
{
Int sub[2][3],I,j,total=0;
Printf(“Enter 6 no :”);
For (i=0;i<2;i++)    ->Outer-Row
{
For (j=0;j<3;i++)    ->Inner-Column
{
Scanf(“%d”,&sub[i][j]);
}
}
Printf(“Values are”);
For(i=0;i<2;i++)
{
For(j=0;i<3;i++)
{
Printf(“\t%d”,sub[i][j]);
Total=total+sub[i][j];
}
Printf(“\t%d”,total”);
Total=0;
Printf(“\n”);
}
Getch();}
Multi Dimensional Array
C allows for arrays of two or more dimensions. A two-dimensional (2D) array 
is an array of arrays. A three-dimensional (3D) array is an array of arrays of 
arrays.
How to Declare a Multidimensional Array in C
Example 1.   int table[5][5][20];
Example 2.   float arr[5][6][5][6][5];
In Example 1: int designates the array type integer.
table is the name of our 3D array.
Our array can hold 500 integer-type elements. This number is reached by 
multiplying the value of each dimension. In this case: 5x5x20=500.
In Example 2: Array arr is a five-dimensional array.
It can hold 4500 floating-point elements (5x6x5x6x5=4500).
Can you see the power of declaring an array over variables? When it comes 
to holding multiple values in C programming, we would need to declare 
several variables. But a single array can hold thousands of values.
A 3D array is essentially an array of arrays of arrays: it's an array or collection 
of 2D arrays, and a 2D array is an array of 1D array.
The conceptual syntax for 3D array is this:
data_type array_name[table][row][column];
If you want to store values in any 3D array point first to table number, then 
row number, and lastly to column number.
Initializing a 3D Array in C
#include<stdio.h>
#include<conio.h>
 void main()
{int i, j, k;
int arr[3][3][3]=   
        {
            {
            {11, 12, 13},
            {14, 15, 16},
            {17, 18, 19}
            },
            {
            {21, 22, 23},
            {24, 25, 26},
            {27, 28, 29}
            },
            {
            {31, 32, 33},
            {34, 35, 36},
            {37, 38, 39}
            },
        };clrscr();
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        for(k=0;k<3;k++)
        {
        printf("%d\t",arr[i][j][k]);
        }
        printf("\n");
    }
    printf("\n");
}
getch();
}
Storing Values in a Continuous Location Using a Loop
void main()
{
int i, j, k, x=1;
int arr[3][3][3];
clrscr();
printf(":::3D Array Elements:::\n\n");
 
for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        for(k=0;k<3;k++)
        {
        arr[i][j][k] = x;
        printf("%d\t",arr[i][j][k]);
        x++;
        }
        printf("\n");
    }
    printf("\n");
}
getch();
}
Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as 
argument. To pass array in function, we need to write the array name only in 
the function call.
functionname(arrayname);//passing array  
No. ways to declare function that receives array as argument.
return_type function(type arrayname[])  
return_type function(type arrayname[SIZE])  

C program to pass a single element of an array to function

#include <stdio.h>
void display(int age)
{   
 printf("%d", age);
}
int main()
{    int ageArray[] = { 2, 3, 4 };
    display(ageArray[2]);   //Passing array element  ageArray[2] only.    
return 0;}
Output
4
Passing Arrays as Function Arguments in C
Void disp(int[],int);
Void main()
{
Int arr[5],I;
Printf(“Enter the five value in an Array”);
For(i=0;i<5;i++)
{
Scanf(“%d”,&arr[i]);
}
Disp(arr,5);
Getch();
}
Void disp(int ar[],int s)
{
Int I,sum=0;
Printf(“Elements are:”);
For(i=0;i<5;i++)
{
Printf(“%d”,ar[i]);
Sum=sum+ar[i];
}
Printf(“Total=%d”,sum);
}
Pass two-dimensional arrays to a function
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{    
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);    
// passing multi-dimensional array to displayNumbers  function    
displayNumbers(num);    
return 0;
}
void displayNumbers(int num[2][2])
{
 // Instead of the above line,   
 // void displayNumbers(int num[][2]) is also valid
    int i, j; 
   printf("Displaying:\n");   
  for (i = 0; i < 2; ++i)
  for (j = 0; j < 2; ++j)              
  printf("%d\n", num[i][j]);
}
Arrays of Strings in C
Array of characters is called a string. A string is terminated by a null character /0
There are two ways to declare string in c
1. By char array 2. By string literal

DeclarationA of string using


M array A N \0
Char s[5] ;       S[0] S[1] S[2]          S[3] S[4]

Initialization of strings using array


char c[] = "abcd"; OR
 char c[50] = "abcd"; 
OR, char c[] = {'a', 'b', 'c', 'd', '\0'}; 
OR, char c[5] = {'a', 'b', 'c', 'd', '\0'};
      S[0] S[1] S[2]          S[3] S[4]
a b c d \0

A M A N \0
Char name[5][10];
Char name[MAX] [LENGTH]; O M \0
      R A M \0
      
No. of string  Length of each string
#include<stdio.h>
#include<conio.h>
void main()
{
Char name[10];
Int I;
Printf(“Enter a string”);
Scanf(“%s”,name)
While(name[i]!=‘\0’)
{
Printf(“%c is trored at %u”,name[i],&name[i]);
i++;
}
Getch();
}

Char name [3][10]= {“amit” , “sumi” , “aman”};
Name[0] amit name[1] sumit name[2] aman

Name[1][1] u –If you want a single character from string then we need to use both 
subscript else not.
Example 
#include<stdio.h>
#include<conio.h>
Void main()
{
Char ch [3][10],I;
Printf(“Enter 3 string”);
For(i=0;i<3;i++);
{
Scanf(“%s”,&ch[i]);
}
Printf(“Strings are “);
For(i=0;i<3;i++)
{
Printf(“%s”,ch[i]);
}
Getch();
}
C gets() and puts() functions
The gets() function reads string from user and puts() function prints the string. Both 
functions are defined in <stdio.h> header file.
 
void main(){  
    char name[50];  
    clrscr();  
    printf("Enter your name: ");  
    gets(name); //reads string from user  
    printf("Your name is: ");  
    puts(name);  //displays string  
    getch();  }  
void main(){  
    char name[50];  
    clrscr();  
    printf("Enter your name: ");  
    gets(name); //reads string from user  
    printf("Your name is: ");  
    puts(name);  //displays string  
    getch();  }  

Strlen() function
The strlen() function returns the length of the given string. It doesn't count null character 
'\0'.
Syntax: strlen(string variable);  or variable name= strlen(string variable); 
#include <stdio.h>  
void main()  
{  
   char ch[20]={‘i', ‘n', ‘n', ‘o', ‘z', ‘a', ‘n', ‘t', '\0'};  
   printf("Length of string is: %d",strlen(ch));  
}  
Output:
Length of string is: 8
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
Int I;
Char name[10];
Printf(“Enter a string”);
Scanf(“%s”,name);
i=strlen(name);
Printf(“String length is %d”,i);
Getch();}
Strcpy() function
The strcpy(destination, source) function copies the source string in destination.

void main()  
{  
   char ch[20]={‘i', ‘n', ‘n', ‘o', ‘z', ‘a', ‘n', ‘t', '\0'};  
   char ch2[20];  
   strcpy(ch2,ch);  
   printf("Value of second string is: %s",ch2);  
}  
Output:
Value of second string is: innozant
Void main()
{
Char name[20];
Strcpy(name,”kanika”);
Printf(“copied string are %s”,name);
Getch();

Strcat() function
The strcat(first_string, second_string) function concatenates two strings and result is 
returned to first_string.
Syntax : strcat(destination string,source string);
#include <stdio.h>  
void main()  
{  
   char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};  
   char ch2[10]={'c', '\0'};  
   strcat(ch,ch2);  
   printf("Value of first string is: %s",ch);  
}  
Output:
Value of first string is: helloc
Void main()
{
Char str1[]=“This is “;
Char str2[]=“innozant”;
Printf(“First string is %s”,str1);
Printf(“First string is %s”,str2);
Strcat(str1,str2);
Printf(“Final string is %s”,str1);
Getch();
}

Void main()
{
Char str1[]=“This is “;
Char str2[]=“innozant”;
Printf(“First string is %s”,str1);
Printf(“First string is %s”,str2);
Strcat(str1,str2,4);
Printf(“Final string is %s”,str1);
Getch();
}

Output:This is inno
Strcmp() function
The strcmp(first_string, second_string) function compares two string and returns 0 if 
both strings are equal.
#include <stdio.h>  
void main()  
{  
   char str1[20],str2[20];  
  printf("Enter 1st string: ");  
  gets(str1);//reads string from console  
  printf("Enter 2nd string: ");  
  gets(str2);  
  if(strcmp(str1,str2)==0)  
      printf("Strings are equal");  
  else  
      printf("Strings are not equal");  
}  
Output:
Enter 1st string: hello Enter 2nd string: hello 
Strings are equal
Void main()
{
Int v;
Char str1[10],str2[10];
Printf(“Enter first string”);
Scanf(“%s”,str1);
Printf(“Enter first string”);
Scanf(“%s”,str2);
V=strcmp(str1,str2);
If(v<0)
{
Printf(“str 1 is less than str2”);
}
Else if(v>0)
{
Printf(“str1 is greater tha str2”);
}
Else
{
Printf(“str1 is equal to str2”);
}
Getch();
}
Strrev() function
The strrev(string) function returns reverse of the given string. Let's see a simple example 
of strrev() function.
#include<stdio.h>  
#include<conio.h>  
void main(){  
  char str[20];  
  clrscr();  
  printf("Enter string: ");  
  gets(str);//reads string from console  
  printf("String is: %s",str);  
  printf("\nReverse String is: %s",strrev(str));  
  getch();  
}    
Output:
Enter string: innozant String is: innozant Reverse String is: tnazonni
……………………………………………………………………………………..
Void main()
{
Char name[10];
Printf(“Enter a string”);
Scanf(“%s”,name);
Strrev(name);
Printf(“Reverse  of entered string %s”,name);
Getch();
}

Strlwr()
The strlwr(string) function returns string characters in lowercase. Let's see a simple 
example of strlwr() function.
#include<stdio.h>  
#include<conio.h>  
void main(){  
  char str[20];  
  clrscr();  
  printf("Enter string: ");  
  gets(str);//reads string from console  
  printf("String is: %s",str);  
  printf("\nLower String is: %s",strlwr(str));  
  getch();  
}    
Output:
Enter string: INNOzant String is: INNOzant Lower String is: innozant
Strupr() function
The strupr(string) function returns string characters in uppercase. Let's see a simple 
example of strupr() function.
#include<stdio.h>  
#include<conio.h>  
void main(){  
  char str[20];  
  clrscr();  
  printf("Enter string: ");  
  gets(str);//reads string from console  
  printf("String is: %s",str);  
  printf("\nUpper String is: %s",strupr(str));  
  getch();  
}    
Output:
Enter string: innozant String is: innozant Upper String is: INNOZANT
1) Pointer reduces the code and improves the performance, it is used to retrieving 
strings, trees etc. and used with arrays, structures and functions.
2) We can return multiple values from function using pointer.
3) It makes you able to access any memory location in the computer's memory.

Void main()
{
Syntax
Int a=100;
Datatype * Pointer name Int *p; P=&a;  
Int *p; D referencing concept printf(“Value of A %d”,a);
Int b=100; printf(“Value of A %d”,*p); 
P=&b; getch();
Printf(“%d”,*p); }    
Int a=100;
Int *p;

Name       a              p


To print the address 
Value  100 3033 of variable
%u –unsinged 
Address        3033     3145 %x-Hexadecimal
Normal Variab %X
%p—Better use this 
The address of operator '&' returns the address of a variable. But, we need to use %u to 
display the address of a variable.
void main(){      
int number=50;    
clrscr();      
printf("value of number is %d, address of numb
er is %u",number,&number);  
getch();      
}      
Output
value of number is 50, address of number is
fff4

void main(){      
int number=50;  
int *p;    
clrscr();  
p=&number;//stores the address of number variable  
      
printf("Address of number variable is %x \n",&number);  
printf("Address of p variable is %x \n",p);  
printf("Value of p variable is %d \n",*p);  
  
getch();      
}      
Main()
{
Int a=100;
Int *p;
P=&a;
Printf(“%d”,a);                100
Printf(“%d”,*p);              100
Printf(“%p”,&a);               2323
Printf(“%p”,p);                 2323
Printf(“%p”,&p);              3234
Pointer Program to swap 2 numbers without using 3rd variable
#include<stdio.h>  
#include<conio.h>  
void main(){  
int a=10,b=20,*p1=&a,*p2=&b;  
clrscr();  
 printf("Before swap: *p1=%d *p2=%d",*p1,*p2);  
*p1=*p1+*p2;  
*p2=*p1-*p2;  
*p1=*p1-*p2;  
 printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);  
 getch();  }  
Output :Before swap: *p1=10 *p2=20  After swap: *p1=20 *p2=10 
Array of Pointers
Main()
{
Int marks[]={10,20,30};
Int *point[3],i;
For(i=0;i<3;i++)
{
Printf(“%d”,marks[i]);
point[i]=&marks[i];
}
For(i=0;i<3;i++)
{
Printf(“%d”,*point[i]);
}
Getch();
}
Increment and Decrement on Pointer
Incrementing a pointer is used in array because it is contiguous memory location. 
Moreover, we know the value of next location.
#include <stdio.h>          
void 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++ or p=p+1;     / p- - or p=p-1;
printf("After increment: Address of p variable is %u \n",p);      
}    
C Pointer Addition
We can add a value to the pointer variable.

#include <stdio.h>          
void 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  // p=p-3 –subtracting 3 from pointer variable 
printf("After adding 3: Address of p variable is %u \n",p);      
}    
Pointer to Pointer

**p1 *p Int a=100 
        a

3156 2156 100

    3160                    3156                           2156
#include<stdio.h>
#include<conio.h>
Void main()
Int a=100;
Int *p
Int **p1;
P=&a;
P1=&p;
Printf(“Value of A %d”,a);            -100
Printf(“%d”,*p);                             -100
Printf(“%d”,**p1);                        -100
Printf(“%u”,*p1                            -2156
Getch();
}
**p1 *p Int a=100 
        a

3156 2156 100

    3160                    3156                           2156
#include<stdio.h>  
int main(){  
int number=50;      
int *p;//pointer to int    
int **p2;//pointer to pointer        
p=&number;//stores the address of number variable      
p2=&p;    
printf("Address of number variable is %x \n",&number);      
printf("Address of p variable is %x \n",p);      
printf("Value of *p variable is %d \n",*p);      
printf("Address of p2 variable is %x \n",p2);      
printf("Value of **p2 variable is %d \n",*p);      
return 0;  
}   
Address of number variable is fff4 
Address of p variable is fff4 
Value of *p variable is 50 
Address of p2 variable is fff2
 Value of **p variable is 50 
Passing pointer to Function or Call by reference or Pointer as a function argument or
A function that return multiple values
#include<stdio.h>
#include<conio.h>
Void swap(int *,int *);
Main()
{
Int a,b;
Printf(“Enter value for A”);
Scanf(“%d”,&a);
Printf(“Enter value for B”);
Scanf(“%d”,&b);
Printf(“Values before swaping”);
Printf(“Value for A %d”,a);
Printf(“Value for B %d”,b);
Swap(&a,&b);
Printf(“Values after swaping”);
Printf(“Value for A %d”,a);
Printf(“Value for B %d”,b);
Getch();
}
Void swap(int  x,int y)
{
Int t;
t=*x;
*x=*y;
*y=t;
}
Pointer to Function in C
Void add(int x,int y)
Syntax: <function return type> (<* pointer name>) (function argument type)
Ex. Void (*ptr) (int,int);

Syntax : pointer_name =&function name;
                           or
Pointer_name=function_name;
Ptr=&add;
Or
Ptr=add;

Call function through pointer


Ptr(10,20); -Implicit
or
(*ptr) (10,20);  -Explicit
#include<stdio.h>
#include<conio.h>
Void add(int x,int y)
{
Printf(“First Value %d”,x);
Printf(“Second Value %d”,y);
Printf(“Addition is %d”,x+y);
}
Main()
{
Int a,b;
Void (*ptr) (int,int);  -Make pointer for that function
ptr=add;  -Point out the function
Printf(“Enter first no”);
Scanf(“%d”,&a);
Printf(“Enter Second no”);
Scanf(“%d”,&b);
Ptr(a,b);      -Function call through pointer
Getch();
}
Void Pointer

The void pointer, also known as the generic pointer or general purpose, is a special 


type of pointerthat can be pointed at objects of any data type! A void pointer is 
declared like a normal pointer, using the void keyword. We cannot dereference 
generic pointer to any other pointer.
Syntax :Void *p;
Int a=100;
Float b=2.2;
P=&a
P=&b

Referencing:
Int a=100;
Int *p;
P=&a; -Referencing  (To hold the address of a variable)

Dereferencing
Printf(“Value of A %d”,*p);
Printf(“Value of A %d”,*p); Syntax is wrong in case of void pointer

*p –Wrong           *(int *) p-Right
Printf(“Value of A %d”,*(int*)p);

Example of Void Pointer


Main()
{
Int a=100;
Void *p;
P=&a;
Printf(“value of A  %d”,*(int*)p);
Getch();
}
Pointer and Array in C

#include<stdio.h>
#include<conio.h>
Main()
Int *p;
Int arr[5],I,total=0;
Printf(“Enter 5 Elements:”);
For(i=0;i<5;i++)
{
scanf(“%d”,&arr[i]);
}
P=arr;
Printf(“Elements are:”);
For(i=0;;i<5;i++)
{
Printf(“%d”,*p);
Total=total+*p;
P++;
}
Printf(“total=%d”,total);
Getch();
}
#include<stdio.h> int main(){ int num = NULL; printf("Value of Number ", ++num); return 0; }
Above program will never print 1, so keep in mind that NULL should be used only when you are dealing with pointer

Int main() Int main()
{ {
Int *ptr=NULL; Int num=NULL;
Printf(“The value of ptr is %u”,ptr); Printf(“Value of Number”,++num);
Return 0; Return 0;
Above program will never print 1,so keep in 
Mind that NULL should be used  only when 
You are dealing with pointer
Dynamic Memory Allocation

#include<stdlib.h>

Memory Allocation
Contiguous Memory Allocation
Reallocation
malloc() function in C
The malloc() function allocates single block of requested memory.
It doesn't initialize memory at execution time, so it has garbage value
initially.It returns NULL if memory is not sufficient.
The syntax of malloc() function is given below: void * malloc(size in byte) –
Declare in header file –This malloc function returns a pointer which point the
first byte of block created.
1.ptr=(cast-type*)malloc(byte-size)
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0; }
calloc() function in C
The calloc() function allocates multiple block of requested memory.
It initially initialize all bytes to zero.
It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
1.ptr=(cast-type*)calloc(number, byte-size)
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Realloc()  Function 
Syntax: void *realloc(void *ptr,New size in bytes);
Syntax use in program : pointer=(cast_type*)realloc(ptr,new size in 
byte);

#include<stdlib.h>
Main()
{
Int s,*p,*ptr,I,sum=0,*q;
Printf(“Enter size fro array”);
Scanf(“%d”,&s);
Ptr=(int*)malloc(s*sizeof(int));
P=ptr;
Printf(“Memory allocated %u”,ptr);
If(ptr==NULL)
{
Printf(“out of memory);
Exit(0);}
Printf(“Enter %d elements”,s);
For(i=1;i<=s;i++)
{
Scanf(“%d”,ptr);
Sum=sum+*ptr;
Ptr++;
}
Printf(“Elements are:”);
For(i=1;i<=s;i++)
{
Printf(“%d”,*p);
P++;
}
Printf(“Addition is %d”,sum);
Printf(“Enter new size for array”);
Scanf(“%d”,&s);
Ptr=(int*)realloc(ptr,s*sizeof(int));
If(ptr==NULL)
{
Printf(“out of memory”);
Exit(0);
}
Printf(“Reallocated memory %u”,ptr);
Q=ptr;
Printf(“Enter %d elements”,s);
For(i=i<=s;i++)
{
Scanf(“%d”,ptr);
Sum=sum+*ptr;
Ptr++;
}
Printf(“Elements are “);
For(i=1;i<=s;i++)
{
Printf(“%d”,*q);
Q++;
}
Printf(“Addition is %d”,sum);
Getch();
}
File Handling in c language is used to open, read, write, search or close file. It is used for 
permanent storage.
It will contain the data even after program exit. Normally we use variable or array to store 
data, but data is lost after program exit. Variables and arrays are non-permanent storage 
medium whereas file is permanent storage medium.
Opening File: fopen() file_pointer=fopen(“filename”,”mode”) 
A.File pointer b.File Name c.Mode
The fopen() function is used to open a file. The syntax of fopen() function is
1.FILE *fopen( const char * filename, const char * mode );
2.FILE *fp; fp=fopen(“karan”,”r”);
Closing File: fclose()
The fclose() function is used to close a file. The syntax of fclose() function is given below:
1.int fclose( FILE *fp );
2.Fclose(fp);
The fprintf() function is used to write set of characters into file. It sends formatted output
to a stream.
Syntax:
1.int fprintf(FILE *stream, const char *format [, argument, ...])
1.#include <stdio.h>
2.main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7.}
The fscanf() function is used to read set of characters from file. It reads a word from
the file and returns EOF at the end of file.
Syntax:
1.int fscanf(FILE *stream, const char *format [, argument, ...])
#include <stdio.h>  
main(){  
   FILE *fp;  
   char buff[255];//creating char array to store data of file  
   fp = fopen("file.txt", "r");  
   while(fscanf(fp, "%s", buff)!=EOF){  
   printf("%s ", buff );  
   }  
   fclose(fp);  }    Output : Hello file by fprintf
Storing Employee Information
1.#include <stdio.h>
2.void main()
3.{
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24.}
Now open file from current directory. For windows operating system, go to
TC\bin directory, you will see emp.txt file. It will have all information you put
there while execute the program.
C fputc() and fgetc()

The fputc() function is used to write a single character into file. It outputs a character to a
stream.
Syntax: int fputc(int c, FILE *stream)
#include <stdio.h>  
main(){  
   FILE *fp;  
   fp = fopen("file1.txt", "w");//opening file  
   fputc('a',fp);//writing single character into file  
   fclose(fp);//closing file  
}  

The fgetc() function returns a single character from the file. It gets a character from the stream. It 
returns EOF at the end of file.
Syntax:int fgetc(FILE *stream)  
void main(){  
FILE *fp;  
char c;  
clrscr();  
fp=fopen("myfile.txt","r");  
  
while((c=fgetc(fp))!=EOF){  
printf("%c",c);  
}  
fclose(fp);  
getch();  
}  
C fputs() and fgets()
The fputs() and fgets() in C programming are used to write and read string from
stream. Let's see examples of writing and reading file using fgets() and fgets()
functions.
Writing File : fputs() function
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax: int fputs(const char *s, FILE *stream)  
#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
clrscr();  
  
fp=fopen("myfile2.txt","w");  
fputs(“Welcome to innozant",fp);  
  
fclose(fp);  
getch();  
}  

Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax: char* fgets(char *s, int n, FILE *stream)
1.#include<stdio.h>
2.#include<conio.h>
3.void main(){
4.FILE *fp;
5.char text[300];
6.clrscr();
7.
8.fp=fopen("myfile2.txt","r");
9.printf("%s",fgets(text,200,fp));
10.
11.fclose(fp);
12.getch();
13.}

C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file 
at desired location. There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR 
and SEEK_END.
Syntax:int fseek(FILE *stream, long int offset, int whence)  
void main(){  
   FILE *fp;  
     fp = fopen("myfile.txt","w+");  
   fputs("This is Innozant", fp);  
    fseek( fp, 7, SEEK_SET );  
   fputs(“Deepak Kumar", fp);  
   fclose(fp);  
}  

Potrebbero piacerti anche