Search This Blog

Tuesday, April 28, 2020

Recursion full explaination in C Programming.

Mr. abhijeet dwivedi

          C-Programming:-

In this tutorials, you will learn:-

Recursion:-


A function is called recursive when it calls itself. There are is always if statement in recursive function to force the function to return without the recursive call being executed otherwise the function goes in an indefinite loop.

For example:

//Write a program to print factorial of any given no using recursion.

#include<stdio.h>
int fact(int);
int main()
{
int n, r;
printf("enter any no: ");
scanf("%d",&n);
r= fact(n);
printf("factorial is = %d", r);
}
int fact (int x)
{
int f;
if(x==1)
return(1);
else
f=x*fact(n-1);
return(f) ;
}

OUTPUT:

enter any no: 3 
factorial is = 6

Types of factorial:-

There are 4 types of factorial are:-

1. Direct recursion:-

A function is called direct recursion if it calls the same function again.

For example:

structure of direct recursion 
fun ( ) {
    // some code
fun ( ) ;
   // some code
}

2. Indirect recursion:

A function (let say fun) is called indirect recursion if it calls another function (let say fun 2) and then fun 2 calls function direct and indirectly.
structure of indirect recursion

For example:

fun() {                        fun2( ){
 // some code                // some code
fun2( ) ;                     fun ( ) ;
// some code               // some code
}                                          }

3. Tailed recursion: 

A recursion function is said to tailed recursive of the recursive if the recursive call is the last thing done by the function there are is no need to keep records of the previous steps.

For example:

void fun(int n)
{
if(n==0)
return ;
else
printf("%d",n);
return fun(n-1) ;
}
main()
 {
fun(3);
return 0 ;
}

OUTPUT:

3  2  1

4. Not tailed recursion:

A recursion function is said to be not talked recursive. If the recursive calls are not the lost thing done by the function different returning back. There the some something left to execute.

For example:

void fun(int x)
{
if(x==0)
return 0 ;
fun(x-1);
printf("%d",x);
}
int main()
{
fun(3)
return 0 ;
}

OUTPUT:

1  2  3

Advantages of recursion.

* It will be useful when the same kind of job has to be continued for a finite number of inputs.
* This function is very useful in tree transversal and stack.
* We can solve complex tasks easily using recursion.

Disadvantages of recursion:

* It recursion function there are must be a contain somewhere in the function to return without the recursive call being executed.
* It is difficult to trace the logic of the function.
* It executed a little bit slow because to maintain the stack. 

Thanks for reading....... 

If anyone have any doubt to related this topic , Plese comment.   



Sunday, April 26, 2020

Top 10 important question for BCA second semester in C Programming.

Mr. abhijeet dwivedi

             C-Programming:-

In this tutorial, you will learn:-

Top 10 Questions are:

 

 

Q1. What is an array? Explain it's types with suitable example.

Ans: Array is a collection of homogeneous data items that share a common name. Array contains a similar kind of value on the same name it allocates contiguous or sequential memory. 

There are two types of an array are:-

*Single dimension array:-

Single dimension array also known as a 1D array that contains either row or column of a given size in memory. 
Syntax:- datatype      array name [size];
                   int                      arr [20] ;

For example:-

//write a program to accept value in an array and print.

#include<stdio.h>
int mian()
{
int a[5]  i , j ;
printf("enter 5 values");
for(i=0 ; i<5 ; i++)
{
sacnf("%d",&a[i]);
}
printf('values are \ n");
 for(j=0 ; j<5 ; j++)
{
printf('%d",a[j]);
}
return 0 ;
}

OUTPUT

enter 5 values 1
2
3
4
5
 values are 1
2
3
4
5

* Multidimension array (2D array) :-

Multidension are like 2D array that contain double dimension having row and column.
Syntax for declaration of 2D array.
Data type   array name [row][column]

 for example :-

Write a program to printf this pattern using array:-

1 0 1

0 1 0

1 0 1 

#include<stdio.h>
int main()
{
int a[3][3] , i , j ;
printf("enter the values ");
for (i=0 ; i<3 ; i++)
{
for( j=0 ; j<3 ; j++)
{
if(i==j)
{
printf("a[i][j]=1");
}
else
{
printf("a[i][j]=0");
}
}
}
printf("values are \n ");
for(i=0 ; i<3 ; i++)
for(j=0 ; j<3 ; j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
return 0 ;
}

OUTPUT

1 0 1 
0 1 0
1 0 1  

Q2. Define string with all it's library function.

  Ans: A group of characters is known as a string. C doesn't support any string as a datatype. We can create a string using character array.
Syntax:-       Datatype    array name [size] ;
for e.g:        char arr[] = "codeswithabhi" ;

There are some library function of string in C Programing are:-

1. strlen () :  It is used to find the length of the string .
2. strrev () : It is used to reverse the given string.
3. strcpy () : It is use to copy one string to another string.
4. strcat () : It is used for concatenation(this function combines both strings in one string.)
5. strlwr() : This function is used to convert upper case string to lower case.
6. strcmp() : It is used for comparing whether both string are identical or not.
7. strupr() : This function is used to converts given string into upper case.

Q3. What is a pointer and explain it features with suitable example.

Ans: Pointer is a varible That stores the address of another variable. The pointer is represented by ( * ) sign.
declaration , initializing and accessing of pointer.
pointer declaration name a pointer variable and specifies the type of object to which the variable points.
  Avariable declared as a pointer holds a memory address.

Syntax:   Datatype      * pointer name

 #include<stdio.h>
int main()
{
int x=10 ;
int *p ;
p=&x ;
printf("value of p is =%d",*p);
return 0 ;
}

OUTPUT:

value of p is =10 

Features of pointer:-

* Pointer saves memory space.
* Execution time with pointer is faster cause data is manipulated with the address is direct access to memory location.
* Pointer reduces length and complexity of program.
* Pointer is efficient in handling data & associated with an array.
* 2D, 3D, and many more dimensional array representation is easy in pointer.

Q4. define static memory allocation.

Static memory allocation:-

The static memory is allocated during compilation time, when a variable is declared, based on their types, compiler allocate space in memory, these variables can be indirectly accessed with the help of pointer variable, This way assigning the pointer variable is called static memory allocation.

let see one example to more clear this topic:-

// Write a program to find the sum of two numbers using pointer...

#include<stdio.h>
int main ( )
{
int a, b, c ;
int *a , * b ;
printf("enter value of a & b \n");
scanf("%d %d", &a , &b );
*a=&a;
*b=&b;
c = *a + *b ;
printf("\n sum of a and  b is = %d", c);
return( 0 ) ;
}

OUTPUT

enter the value of a & b 10
20
sum of a and b is = 30

 Q5 Explain structure with the help of one example.

 Structure:-

It is a collection of different data type variable groups together under a single name.

Syntax :-

struct  structure name 
{
data type  mem 1 ;
data type  mem 2 ;
data type  mem 3 ;
, , , ,  , , ,    , , , , , , 
, , , ,  , , ,    , , , , , , 
data type  mem n;

 Declaration of structure:-

struct book 
{
int pages ;
char name [ 100 ] ;
float price ;
} b ;

 

#include<stdio.h>
struct book 
{
int pages ;
char name [ 100 ] ;
float price ;
};
int main (  )
{
struct book  b ;
printf("enter pages , book name , price of book");
scanf("%d%s%f ", &b.pages , b.name , &b.price);
printf("\n details of books are ");
printf(" pages of book are = %d", b.pages);
printf("writer name = %s", b.name);
printf(" price of book = %d",b.price);
return ( 0 );
}

OUTPUT

enter pages , writer name , price of books  1600
codeswithabhi
234.23
 details of book are 
pages of books = 1600
write name  =  codeswithabhi
price of books = 234.23

Q6. What is Nested structure in C programming?

Nested structure :-

A structure that contain another structure as a member of a variable is known as nested structure .

For example:-

#include<stdio.h>
int main ()
{
struct address 
{
char city [30];
 char colony [30];
int pin ;
};
struct employ 
{
char name [30];
struct address a;
};
struct employ e = { "abhi" , "kanpur" , "abc" , "208011" } ;
printf("%s\n%s", e.a.colony , e.a.city);
printf("%d\n %s", e.a.pi , e.name );
return( 0 );
}

OUTPUT 

abhi
kanpur 
abc
208011

 

Q7. Difference between Arry and structure.

Difference between array and structure:-

                       Array

                            Structure

 1

 An array behave like a built in data type all we have to do this to declare an array variable and use it.
 First we have to design and declare a data type structure before the variable are declare and use.

 2

An array is the collection of similar data type.
 A structure have a collection of different data type.

 3

An array is a derived data type,.
 A structure is a user defined data type.

 

Q8. Define Union with all types of declarations.

Union:-

* Union is user-defined data type just like structure.
* Each member of the structure is assigned its own unique storage area whereas union all the members share common storage area.
* All members share common areas so only one member can be active at a time.
* Union are used when all the members are not assigned a value at the same time.

syntax:-

Union tag name 
{
datatype  member 1;
datatype  member 2 ;
 };

There are 3 types of declaration of union in C are :-

1.
 union sample 
{
int a;
float b;
char c;
};
union sample s;
2
union  sample 
[
int a ;
float b;
 char c;
}s;
3. 
union 
{
int a ;
float b;
char  c;
}s;

Initialization and accessing of union :-

Union sample
{
int a;
float b;
char c;
};
int main ( )  
{
union sample s ={ 10 , 10.5 , 'a' };
printf('%d \ n ", s.a);
printf('%f  \ n", s.b);
printf('%c \ n ", s.c);
return( 0 );
}

OUTPUT

10
10.5
a

 

Q9.Difference between structure and union.

Ans:


                   Union

                          Structure

 1.

 All members share the same storage area.
Each member is assigned its own unique storage area.

 2.

The maximum memory required by the member is allocated.
The total memory required by all members is allocated.

 3.

Only one member is active at a time
All member is active at a time.

 4.

Only first member can be initialized
All members can be initialized.

 5.

Require less memory.
Require more memory.

Q10. Write a short note on the following are:-

  a. Bit field:-

A  bit field is a data structure that allows the programer to allocate memory to structure and union in bit in order to utilize computer memory in an efficient manner.
* It used to reduce memory consumption 
* Easy to emplement
* Provide flexibility to the code.

For example:-

#include<stdio.h>
struct data
{
int d: 5;
int m : 4 ;
 };
 int main()
 {
 struct data d;
printf("size %d \ n ", size of (d));
return 0 ;
}

b. Macros:-

Macro area piece of code in a program which is given sam name
whenever this name is encountered by the compiler th replaces the name with an actual piece of code.

For example:-

#include<stdio.h>
#include<conio.h>
#define line 5
void main()
{
int i ;
for(i=1 ; i<line ; i++)
{
printf("%d",i);
}
getch();
}

OUTPUT:-

1
2
3
4
5

 c.  Compiler control  

Compiler control directives are a type of directive which helps to compile a specific portion of the program or to skip compilation of some specific part of the program based on some condition.
Syntax:-
indef macro name 
s1 ;
s2 ;
s3 ;
,,
,,
,,
sn ;
#endif

 d. Typedef :

The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use. 

syntax:-

1
typedef unsigned int size_t;
From here on out, you would be able to use size_t instead of unsigned int. Note that in C, typedefs can also be used to remove some of the burden associated with declaring structs. In C, struct variables must be declared by a combination of the keyword struct and the name of the struct:
1
struct my_struct_type my_struct_variable;
This can be annoying, so some programmers use typedef to create shorter names:
typedef struct my_struct_type my_short_type_t;
1


 e. Bitwise operator :

In C programming the following 6 operator are bitwise operator are:-

1.  &( Bitwise AND ):-

The &(bitwise AND ) in C takes two number as operands and does AND on every bit of two number . The result of AND is 1 only of both bits are 1 .

2. | ( Bitwise OR ) :-

The | (bitwise OR ) in C takes two numbers as operands and does OR every bit of two numbers the result of OR is 1 if any of the two bits is 1 .

3. ^ ( Bitwise XOR ):-

The ^ ( Bitwise XOR ) in c takes two number as operands and does XOR on every bit of two numbers . The result of XOR is 1 if the two bits are different. 

4. << ( Left shift ) :-

The << ( Left shift ) in C takes two numbers , left shifts the bits of the first operands , the second operands decides the numbers of places to shift.

5. >> ( Right shift ) :-

The >> ( Right shift ) in C takes two numbers , right shift the bits of the first operands , the seconds operands decides the number of place to shift .

6. ~ ( Bitwise NOT ):-

The ~ ( Bitwise NOT ) in C takes one number and inverts all bits of it.

Thanks for reading..........

 

Saturday, April 25, 2020

File handling in C Programming

Mr. abhijeet dwivedi

         C-Programming:-

In this tutorial, you will learn:-

What is the file?



* Computer stores files to secondary storage so that the content of files remain intact when a computer tur off.
* When a computer reads a file, it copies the file from the storage devices to memory; when it writes to a file, it transfers data from memory to the storage device.
* C uses a structure called FILE ( defined in stdio.h ) to store the attributes of a file.

Steps in processing a file :-

1. Create the file through pointer variable like:
FILE * p;
2. Open the file
3. Read or write data.
4. Close the file.

 The basic file operation are:-

* fopen : By this function we open a file.
* fclose  -  close the opened file.
* fread - to read entire records from a file.
* fwrite - to write an entire record into a file.
* ftell/ tgetpos - tell you where the file pointer is located.
* fputc - Write character in file.
* fgetc - Read character from a file.
* getw - Read number from a file.
* putw -  write number into a file.
* fputs - To write a string in a file.

 Mode
   Meaning
   r
 Open text file in read mode.
* If file exists, the maker is poistioned at begining.
* If file doesn't exist, it is created.
   w
 Open text file in write mode.
* If file exists, it is erased.
* If file doesn't exist, it is created.
    a
 Open tezt file in append mode.
* If file exists, the maker is positioned at end.
* If file doesn't exists, it is created.

Additionally:-

* "r+" (read + write ) in this mode we can also write and modify existing data. The file to be opened must exist and the previous data of the file is not erased. The mode is also called update mode.
* "w+"(write + read) if the file doesn't exist then a new file is created and if the file exists then the previous data is erased.

A structure named FILE is defined in the file stdio.h that contains all the information about the file like:-
* Name of file.
* Status.
* Buffer size.
* Current position.
* End of file status. 

 File open:-

The file function (fopen) server opens file

Syntax:-

FILE *fopen("filename ", "mode") ;

More on fopen :-

* On success fopen () return a pointer of type FILE and on error, it returns NULL.
* We asssign the return value of fopen to our pointer variable.
FILE * p1 ;
p1 = fopen("MYFILE.TXT", "W");
p1 = fopen("A:\\DOCUMENTS\\MYFILE.TXT","W");

Errors in fopen:-

* If an error occurs in opening a file, then fopen() return NULL.
FILE *p;
p=fopen("abc.txt","r");
if(p==NULL)
{
printf("error in opening file");
exist(1);
}

Errors may occur due to following reason:-

* If we try to open the file in read mode and if the file doesn't exist or we do not have read permission on that file.
* If we try to create a file but there is no space on disk or we don't have write permissions.
* If we try to create a file that already exists and we don't have permission to delete that file.
* Opening system limits the number of files that can be opened at a time and we are trying to open more files than that number.

Closing a file:-

*When we finish with mode, we need to close the file before ending the program or beginning another mode with the same file.
* To close a file, we use fclose
 There are some I\O function in file handling:-
* fprintf()

syntax:- 

 fprintf(fp,"string",variable);

For example:-

int i=10;
float x= 2.3;
char c='s' ;
FILE *f;
fp= fopen("out.txt","w");
fprintf("fp,'T%d%f%c",i,x,c);

 * fscanf()

Syntax:-    

 fscanf(fp,"string",identifiers) ;
 for example:-
FILE *fp ;
Fp= fopen("input.txt","r");
int i;
fscanf(fp,"%d",i);

*getc() :-

syntax:-   

identifier = getc(file pointer) ;
for example:-
FILE *fp ;
fp =fopen("input.txt","r");
char ch ;
ch getc(fp);

* putc():-

Write a character.

for example:-

FILE *fp;
char ch;
putc (ch,fp) ;

End of file:-

There are a number of ways to test for the end of life condition.
FILE *fptr1;
int istatus;
istatus = fscanf(fptr,"%d",&var);
if( istatus == feof(fptr1) 
{
printf("end of file encounted \ n ");
}

Reading and writing files:-

#include<stdio.h>
int main()
{
FILE *outline , *intile ;
int b = 5 , f;
float a = 13.3 , c =16.68 , e , g ;
outline =  fopen ("testdata","r");
fprintf(outline,"%f%d%f",a,b,c);
fclose (outline) ;
 infile= fopen("testdata","r");
fscanf(infile,"%f%d%f ", &e, &f , &g);
printf("%f%d%f \n",a,b,c);
printf("%f%d%f \ n",e,f,g) ;
}
return(0);
}

Example:-

#include<stdio.h>
int main()
{
cgar ch ;
FILE *fp ;
fp =  fopen ("out.txt","r");
while(!feof(fp) )
{
ch = getc(fp) ;
printf("\n%c",ch);
}
return(0) ;
}

fread:-

Declaration :-

a fread(void *ptr, a ,a , FILE *stream) ;

Remark :-

fread reads a specific number of equal sized data items from an input stream into a block.
Size      = Length of each items read, in bytes
n           =  Number of items  read .
stream = File pointer

Example:- 

#include<stdio.h>
int main()
FILE *f ;
char buffer [11] ;
If(f= fopen("fred.txt","r"));
{
fread (buffer, 1 , 10 , f) ;
 buffer [10] = 0 ;
fclose (f);
printf("first 10 character of the file :\ n%s\n",buffer);
}
return 0;
}

fwrite()

Declaration :-

a fwrite(void *ptr,  size, a, FILE *stream);

For example:-

#include<stdio.h>
#include<conio.h>
void main()
{
char a[10] = {'1','2','3','4','5','6','7','8,'9','a'};
FILE *fs;
fs=fopen("project.txt","w");
fwrite(a,1,10,fs);
getch();
}

fseek():-

This function sets the file position indicator for the stream pointed to by stream or you can say it seek a specified place within in a file and modify it.
SEEK_SET       Seeks from beginning of file.
SEEK_CUR      Seeks from current position.
SEEK_END      Seeks from end of file.

Example:-

#include<stdio.h>
int main()
{
FILE *f;
f = fopen("mylife.txt,"w");
fputs("hello world",f);
fseek(f,6, SEEK_SET) ;          SEEK_CUR , SEEK_END
fputs("india",f) ;
return 0 ;
}  

ftell ()

Offset = ftell(file pointer) ;
"ftell" returns position for input or output on the file.
#include<stdio.h>
int void 
{
FILE *stream ;
stream = fopen("mylife.txt",'w");
fprintf(stream, "This is a test");
printf("%ld \ n", ftell(stream));
fclose (stream);
return 0 ;
}

Bitwise operator in C Programming

Mr. abhijeet dwivedi

           C-Programming:-

In this tutorial you will learn:-

Bitwise operator :- 


In C programming the following 6 operator are bitwise operator are:-

1.  &( Bitwise AND ):-

(bitwise AND ) takes two number  and does AND on every bit of two number . The result of AND is 1 only of both bits are 1 .

2. | ( Bitwise OR ) :-

The | (bitwise OR ) in C takes two numbers as operands and does OR every bit of two numbers the result of OR is 1 if any of the two bits is 1 .

3. ^ ( Bitwise XOR ):-

 ( Bitwise XOR ) takes two number  and does XOR on every bit of two numbers .

4. << ( Left shift ) :-

The << ( Left shift ) in C takes two numbers , left shifts the bits of the first operands , the second operands decides the numbers of places to shift.

5. >> ( Right shift ) :-

 ( Right shift )  takes two numbers , right shift the bits of the first number the seconds number decides the number of place to shift .

6. ~ ( Bitwise NOT ):-

The ~ ( Bitwise NOT ) in C takes one number and inverts all bits of it.

Note point:-

* The left shift and right shift operators should not be used for negative number . if any of the operands is a negative number it result in undefined behaviour .
for example :-  -1 << 1   and 1 << -1 is undefined.
* The bitwise XOR operator is the most useful operator from technical interview perspective
It is used in many problems . 
A simple example is:-
A set of number where all element occur even number of time except one number find odd occuring number this problem can be efficiently solved by just doing XOR of all numbers.


#include<stdio.h>
int findodd( int arr [] , int n )
{                                       // user define method
int res = 0 , i ;
for ( i=0 ; i<n ; i++)
{
res ^ = arr[i];
return(0);
}

// Driver mode :-

 #include<stdio.h>
int main ( void ) 
{
int arr [] = { 12 , 12 , 14 , 90 , 14 , 14 , 14 };
int n = sizeof(arr)  , sizeof(arr[0]);
printf("The odd occuring element is = %d",find odd (arr,n));
return (0);
}

OUTPUT:-

The odd occuring element is = 90
HD wallpaper: code, javascript, programming, source code, null ...

Thanks for reading........