Showing posts with label programming. Show all posts

What is the access Specifier in cpp

In cpp We can customize the accessing of data member or member function.
What  does it mean, Let's consider you created a class named "acess".put the function and data which you want. 

Class access
{ 
    int data;
   
       int Function()

      {

        //definition of function;

      }

};
If data,function can be accessed by any where of program then Object Oriented Programming loss its data hiding concept.

So,CPP gives you permission to hide,show your data to the other part of program .
                for this purpose Cpp gives three Access Specifier
Public:

Private:


protected :
Public : if we want to share the data member every where of program we use this keyword .
    

                                    By default cpp apply this keyword for member ,like as above we haven't declare any access specifier ,so cpp by default apply it as public.
Thus it will be same as :

 class access 
  {
      public://By default 

      int data;

      int function()

         {
            
        //Definition of function ;
         
        }
  
}

Consider this program to understand ,how accessing is performed .


class dog
  {

     public:  // Public access specifier 

        int leg;

         void bark()
          {
             cout<<"Barking dog seldom bites ";
          }

   };
     
int main()

 {
        dog tomy ;

         cout<<"How many legs tom has ?";

                cin>>tomy.leg; 


// Above Accessing the "leg "data of that class from 

// out side of class i.e. in main function.

     if(tomy.leg<4) 
 
         cout<<"Tomy need extra care.";

     cout<<"\n See tomy bark or not .";

       tomy.bark(); // Accessing member function.

  }
   So, what we knew that if we have to access member of a class outside or by outsider function we must declare the member as Public.

Private:
 private is another access specifier of cpp ,as the name suggested ,if we have to make the member of a class private ,we use this access specifier .

   But the question is what the mean by making member private .
So,making the member private means


1.Private member can't be accessed by outside or another outsider function.
2.Private member is only accessible in the class in which it exist.
3.Private member only can be accessed by the function of that class.
  


 let's understand all the term by example .
class access 
  {
      private:  

      int data;

      int function()

         {
            
        //Definition of function ;
         
        }
  
}

This is how we declare member as private .

An example for accessing the private member :
class dog
  {

     private:

        int leg;

     public:

      void bark();   

   };
void dog::bark()

          {   
               
            cout<<"How many legs tom has ?\n";

              cin>>leg; //can accessed private member

// because function bark() is of same class.
 
            if(leg<4)
 
                cout<<"Tomy need extra care.\n";
            else

                cout<<"\n See tomy bark or not \n.";

          }
     
int main()

 {
        dog tomy ;

         cout<<"How many legs tom has ?\n";

              //  cin>>tomy.leg; Error we can't access

//private member by outsider function(main)  

    tomy.bark(); // Accessing member function since it

's public.

  }
output:
How many legs tom has ?
4
Tomy need extra care.
As we go through the program,we see that tomy.leg can't be accessed because it's being accessed by a function(main)which is not in the same class.
                                               But we can access the tomy.bark().i.e. bark() function of class dog.again from the bark() function we can accessed all member.because as i say earlier we can access the private member by the function of same class. 
   

Array of pointer and pointer to an array in c

Array of pointer
 each element of array contains the address of memory location is called  array of pointer .each index      treated as a pointer

 Ex-
  main()
   {
      int *arr[4] ;
      int a,b,c,d;
      arr[0]=&a;
      arr[1]=&b;
       arr[3]=&c;
       arr[4]=&d;
   }

 All elements of this array is containing address of these variable .

Pointer to an array

pointer to an array is a pointer which can point whole array and in simple way we can say the base address of and array is Pointer to an array.
                                     since using  base address we can access the whole array that means base address of a array points to whole array .

Ex :_

    main()
     {
         int array[6] ={1,2,3,4,5,6,};
          int *point ;
        point =array // Pointer to an array

    }
 






C program for HCF and LCM


/*HCF AND LCM */

#include<stdio.h>
#include<conio.h>
void hcff(int a,int b,int c)
{
int p,i;
p=(a<b?(a<c?a:c):(b<c?b:c));
for(i=p;i>=1;i--)
{
if(c%i==0 && a%i==0 && b%i==0)
break;
}
printf("the HCF of given number is:%d",i);
}

void lcmf(int a,int b,int c)
{
int p,i;
p=(a>b?(a>c?a:c):(b>c?b:c));
for(i=p;i<=a*b*c;i++)
{
if(i%c==0 && i%a==0 && i%b==0)
break;
}
printf("the LCM of given number is:%d",i);
}

void main()
{
int a,b,c,ch;
clrscr();
printf("enter three number number for HCF And LCM ");
scanf("%d%d%d",&a,&b,&c);
while(1)
{
clrscr();
printf("\n\tEnter 1. for HCF :");
printf("\n\tEnter 2. for LCM :");
printf("\n\tEnter 3. for Exit :");
scanf("%d",&ch);
switch(ch)
{
case 1: hcff(a,b,c);
getch();
break;
case 2: lcmf(a,b,c);
getch();
break;
case 3: return;
default : printf("\n\tWrong choice ");getch();
}
fflush(stdin);
}

getch();
}

C program for matrix multiplication,addition and subtraction


/*Matrix Add,Sub,Multi */
#include<stdio.h>
#include<conio.h>
void main()
{
int n,**p,**q,**r,i,j,k,ch;
clrscr();
printf("enter the order of matrix\n");
scanf("%d",&n);
p=(int**)malloc(n*sizeof(int));
q=(int**)malloc(n*sizeof(int));
r=(int**)malloc(n*sizeof(int));
for(i=0;i<n;i++)
p[i]=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
q[i]=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
r[i]=(int*)malloc(n*sizeof(int));


printf("enter the element of first matrix\n");  //inputing
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&p[i][j]);
printf("enter the element of second matrix");   //inputing
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&q[i][j]);
clrscr();
printf("your entered matrix is\n");     //printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
 printf("  %d",p[i][j]);

}
printf("\n");
}
printf("\n\n");                            //printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
 printf("  %d",q[i][j]);

}
printf("\n");
}

while(1)
{

clrscr();
printf("\n\tEnter 1. for Addtion :");
printf("\n\tEnter 2. for Mult :");
printf("\n\tEnter 3. for Subtract :");
printf("\n\tEnter 4. for Exit :");
printf("\n\tEnter your choice :");
scanf("%d",&ch);
switch(ch)

{
case 1:
{
for(i=0;i<n;i++)   //Add
{
for(j=0;j<n;j++)
{
r[i][j]=p[i][j]+q[i][j];
}
}
printf("\n Addtion matrix is\n");      //output printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf(" %d",r[i][j]);
}
printf("\n");

} getch();
break;
}
case 2:
{
for(i=0;i<n;i++)   //multipicating
{
for(j=0;j<n;j++)
{
r[i][j]=0;
for(k=0;k<n;k++)
{
r[i][j]=r[i][j]+p[i][k]*q[k][j];
}
}
}
printf("\n multiplyed matrix is\n");      //output printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf(" %d",r[i][j]);
}
printf("\n");

}getch();
break;

}

case 3:
{
for(i=0;i<n;i++)   //Add

for(j=0;j<n;j++)
{
r[i][j]=p[i][j]-q[i][j];
}
printf("\n Subtract matrix is\n");      //output printing
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf(" %d",r[i][j]);
}
printf("\n");

}
}  getch();
break;
case 4 : return;
default : printf("\n\tWrong choice");
}
}
getch();
}



C program for Breadth First search In graph


/*program in C to implement Breadth First search using linked representation of graph
*/

#include <stdio.h>
#include <conio.h>
#include <alloc.h>

#define TRUE 1
#define FALSE 0
#define MAX 8

struct node
{
int data ;
struct node *next ;
} ;

int visited[MAX] ;
int q[8] ;
int front, rear ;

void bfs ( int, struct node ** ) ;
struct node * getnode_write ( int ) ;
void addqueue ( int ) ;
int deletequeue( ) ;
int isempty( ) ;
void del ( struct node * ) ;

void main( )
{
struct node *arr[MAX] ;
struct node *v1, *v2, *v3, *v4 ;
int i ;

clrscr( ) ;

v1 = getnode_write ( 2 ) ;
arr[0] = v1 ;
v1 -> next = v2 = getnode_write ( 3 ) ;
v2 -> next = NULL ;

v1 = getnode_write ( 1 ) ;
arr[1] = v1 ;
v1 -> next = v2 = getnode_write ( 4 ) ;
v2 -> next = v3 = getnode_write ( 5 ) ;
v3 -> next = NULL ;

v1 = getnode_write ( 1 ) ;
arr[2] = v1 ;
v1 -> next = v2 = getnode_write ( 6 ) ;
v2 -> next = v3 = getnode_write ( 7 ) ;
v3 -> next = NULL ;

v1 = getnode_write ( 2 ) ;
arr[3] = v1 ;
v1 -> next = v2 = getnode_write ( 8 ) ;
v2 -> next = NULL ;

v1 = getnode_write ( 2 ) ;
arr[4] = v1 ;
v1 -> next = v2 = getnode_write ( 8 ) ;
v2 -> next = NULL ;

v1 = getnode_write ( 3 ) ;
arr[5] = v1 ;
v1 -> next = v2 = getnode_write ( 8 ) ;
v2 -> next = NULL ;

v1 = getnode_write ( 3 ) ;
arr[6] = v1 ;
v1 -> next = v2 = getnode_write ( 8 ) ;
v2 -> next = NULL ;

v1 = getnode_write ( 4 ) ;
arr[7] = v1 ;
v1 -> next = v2 = getnode_write ( 5 ) ;
v2 -> next = v3 = getnode_write ( 6 ) ;
v3 -> next = v4 = getnode_write ( 7 ) ;
v4 -> next = NULL ;

front = rear = -1 ;
bfs ( 1, arr ) ;

for ( i = 0 ; i < MAX ; i++ )
del ( arr[i] ) ;

getch( ) ;
}

void bfs ( int v, struct node **p )
{
struct node *u ;

visited[v - 1] = TRUE ;
printf ( "%d\t", v ) ;
addqueue ( v ) ;

while ( isempty( ) == FALSE )
{
v = deletequeue( ) ;
u = * ( p + v - 1 ) ;

while ( u != NULL )
{
if ( visited [ u -> data - 1 ] == FALSE )
{
addqueue ( u -> data ) ;
visited [ u -> data - 1 ] = TRUE ;
printf ( "%d\t", u -> data ) ;
}
u = u -> next ;
}
}
}

struct node * getnode_write ( int val )
{
struct node *newnode ;
newnode = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
newnode -> data = val ;
return newnode ;
}

void addqueue ( int vertex )
{
if ( rear == MAX - 1 )
{
printf ( "\nQueue Overflow." ) ;
exit( ) ;
}

rear++ ;
q[rear] = vertex ;

if ( front == -1 )
front = 0 ;
}

int deletequeue( )
{
int data ;

if ( front == -1 )
{
printf ( "\nQueue Underflow." ) ;
exit( ) ;
}

data = q[front] ;

if ( front == rear )
front = rear = -1 ;
else
front++ ;

return data ;
}

int isempty( )
{
if ( front == -1 )
return TRUE ;
return FALSE ;
}

void del ( struct node *n )
{
struct node *temp ;

while ( n != NULL )
{
temp = n -> next ;
free ( n ) ;
n = temp ;
}
}

Some basic of printf

This is the system define function  used to print something on monitor screen .

Definition of this function is written in header file stdio.h  and this is the reason we write #include<stdio.h> at top of our program code 

prototype of printf : 

 int printf(char const *,...) ;

printf always return integer value , and the value is equal to how much character or anything else printed on monitor screen.

printf("%d",2);   will return 1
printf("this is core");  will return 12

printf("%f",2.3)     will return 8( because this time printf     print  2.300000  on monitor screen )


Now parameter of printf is (char const *,...) 
first parameter is char const * (constant character string ) 

Ex- "what a look" , "Never go back" "12gshs"  

second parameter is three dot ...    this is called ellipsis
meaning of the ellipsis is you can put variable number of argument in printf 


variable number of arguments means sometime you are using printf to print one value , sometime more than one 

Have a look on this program it will be more clear 




#include<stdio.h>
void ellipsis(int var,...);

void main()

{

int a=5,b=10,c=20;


ellipsis(a);
ellipsis(a,b);
ellipsis(a,b,c);

}

void ellipsis(int var,...)

{

printf("%d",var);


}
output :- 5 5 5 
So printf can have variable number of argument , 


printf  format specifier have the following form 

%[flag][width][.precision] [F|N|H|L] type_char

Each  format specifier  begins with % (percent character )


details of all specifier with example 

[flag] - (optional)        work  
   
   -                  :-     Left-justifies the result, pads on the right with blanks. If not given, it right                   
                              justifies the result, pads on the left with zeros or blanks.

+                       data is preceded by + or – sign if number is +ve and 
                         -ve respectively.
 0(blank)          If value is nonnegative, the output begins with a blank instead of a plus;   

                                 negative values still begin with a minus.

#                         Specifies that arg is to be converted using an alternate form.

Note: Plus (+) takes precedence over blank () if both are given.


    
[width]             (optional)       It is +ve integer .It defines minimum field width. If length of data is    smaller than width. In case right adjustment in put first (width-length of data) number of blank space then prints data.      

width specifier 
n                      At least n characters are printed. If the output value has less than n characters,   
                             the output is padded with blanks (right-padded if - flag given, left-padded
                             otherwise).


0n                     At least n characters are printed. If the output value has less than n characters, 

                                is filled on the left with zeros.


*                The argument list supplies the width specifier, which must precede the actual         

                        argument being formatted.



  #include<stdio.h>
void main()

{

char str[12]="world_of_c";

printf("%15s\n",str);

printf("%-15s\n",str);

printf("%10s\n",str);

printf("%-10s\n",str);

printf("%(-10)s\n",str);

printf("%-(-10)s\n",str);

printf("%10s\n",str);

}


[.precision]   : (optional)this is used to print maximum number of character in case of string and in case of integer minimum  number of digit 


1. in case of string precision is a integer,which indicate
how many character of string will be printed .if the string length is less than the precision length the whole string will be printed 
  



#include<stdio.h>
int main()
{
   char str[10]=''worldwide"; 
 printf("%.2s",str);   // .precision      .2 
}


output :- wo 


What is function in c

We can define function as a block of code which has a name and a special task , we can call it from any where of c program using its name .
If you are not getting the point by its definition then consider on a simple function "printf()" 
what is printf()   ??
its a function and according to definition it has a name(printf) and specific work (to print on monitor screen ).
it's a system define function but we can also define our own function .
So we can categories function in two type

1.System define function . 
Ex- printf(), scanf(),gtes, puts, strcpy() ....etc

2. User define function 
 Ex-    whatever name and task we give 

let's go for write own function and understand how it works ,how many types of aspects of it 

main()
 {
   printf("Implement of function");
   user();
   }
user()
{
   printf("This is the simplest one");
 }
look on this code segment , simplest example of function calling .
Since main() is a function and execution begins from main  actually,  so in every program main must be present .

here execution begins from main and print the message 
Implement of function
and now we are invoking function user(Define by user)
So control goes to user and print the message 
"This is the simplest one "
after this control goes back to main and program terminate .


If we define own  function in any program there should be three part of the function 
1. Function prototype  
2. Function call 
3. Function definition   

program that will  make you familiar to these terms  

Program to sort the element of array .(Bubble sort)

#include<stdio.h>
#include<alloc.h>
  int *array,n;
void sort_array();  // Function prototype 
int main()
 {
 int i;
printf("How many element you want in array \n");
scanf("%d",&n);

array=(int*)malloc(sizeof(int)*n);

printf("Enter the element into array\n"); 

  for(i=0;i<n;i++)
scanf("%d",(array+i)); 

// array before sorting 
  printf("See what you entered\n  ");

 for(i=0;i<n;i++)
printf("%d\n",*(array+i)); 



sort_array();           // function calling 

// array after sorting (after calling the function sort_array()) 
printf("Array after sorting \n ");
  for(i=0;i<n;i++)
printf("%d\n",*(array+i));  // a[i] will also work 

return 0 ;
}
void sort_array()    // Function definition 

{
 int i, j,temp;
for(i=0;i<n;i++)
 {
for(j=i;j<n;j++)
{
if(array[i]>array[j])
{
temp=array[i];
array[i]=array[j];
 array[j]=temp;
}
 }
 }  
}  // closing of function 


If you go through the program you will see all three terms function prototype, function call and function definition .

function prototype :- it's a layout of function we are going to use in our program ,using this compiler knows that what is return type of function, how many argument it has . compiler makes a table of information about this function and keep for future use .

function call :  - we use the function name  to transfer the control to the function definition ,as in program , after executing it control goes to definition of function and complete its work !! 

function definition : - it's body of function i.e. what is the work of function we write in body of function(definition ) after executing the name of function control comes to function definition

C program for factorial using recursion

This program will help you to understand that how recursion works  !!


#include<stdio.h>
int facto(int);  // prototype of function
int main()
{
  int n ,result;
printf("Enter the no for calculate the factorial ");
scanf("%d",&n);
result=facto(n) ;//calling the function
printf("Factorial of %d is %d ",n,result);
return 0;
}
int facto(int n) // function defintion
{
int sum=1;
if(n==0)
 return 1 ;
else
sum =n*facto(n-1);
return sum ;
}

What is recursion in c language ?

As we know a function can be called  by another function  to accomplish a specific task ,and even a function can be called by itself and this is calling RECURSION .
In another word when a function called by itself  then this method is called RECURSION .
Before going to learn recursion first of all we should learn  what is function and how is it called .  

#include<stdio.h>
void next_func() ; // function prototyping 
main ()
{
  printf("Right now i am in main and now going to another function \n ");
  next_func();   //  function calling 
  printf("I am again in main");
}
void next_func()   // function definition 
{
  printf("Now i am in  next_func \n ");
}

output :-Right now i am in main and now going to another function 
             Now i am in  next_func
             I am again in main


here the function next_func is calling by main . one more thing should be in your mind that when a function is called ,after executing that function the control goes back to the function from where is it called .

Consider on next code segment 

#include<stdio.h>
void recursion() //function prototyping 
main()
{
 printf("This is example of recursion \n ");
 recursion();  // function calling 
}
void recursion()
{
  printf("Now control is in function recursion \n ");
 recursion();
}

output :- This is example of recursion 
             Now control is in function recursion
             Now control is in function recursion
              .
              .
              .
              .
              .
            Now control is in function recursion  
Infinite times (until the stack is overflow...... will discuss later what is stack overflow  )


This is the example of recursion , here function recursion is calling by itself and this is what recursion .
1st main function get execute and print the message " This is example of recursion "
in next line function (recursion ) is calling  and control goes to function recursion .....
here the message  
" Now control is in function recursion" will print and in new line the function called by itself again the message will print and it will continue until the stack will not full .
Now one another question is arising is what is STACK ???
the answer is very simple function calling and returning is done by machine using stack concept ,
when a function is called the address of function is push  into stack and when the control returns to another function  the address is pop.
in this situation function RECURSION is called again and again so it is pushing in stack again and again ...
so we get message STACK OVERFLOW .
   
 
In next article a use of recursion function is given for calculate the factorial of a number .

          

Count frequency of element in array

// This program will help you to generate the frequency of all element present in array


#include<stdio.h>

int main()

  int  *arr,i,j,k,n,temp,f=0;

  printf("Enter the numer of array \n  ");
   scanf("%d",&n);

  arr=(int*)malloc(sizeof(int)*n);    // allocating  the space         

  printf("Enter the element now \n");
    for(i=0;i<n;i++)
      scanf("%d",(arr+i));          // feeding the value in array

 // sorting the array

  for(i=0;i<n;i++)
     {
       for(j=i;j<n;j++)
         {
              if(arr[i]>arr[j])
              {
                 temp=arr[i];
                 arr[i]=arr[j];
                 arr[j]=temp;
              }
         }
     }
  for(i=0;i<n;i++)
    {
     if(arr[i]==arr[i+1])
         f++;
    else
      {
        printf("Frequency of %d is %d \n ",arr[i],(f+1));
          f=0;
      }
    }
  return 0;
 }