Program to input a number and calculate its factorial using recursion in C Language



//To input a number and calculate its factorial using recursion.

#include
#include
long int fact(int);

main()
{
int i,n;
long int f;
clrscr();
printf("Input a number : ");
scanf("%d",&n);
f=fact(n);
printf("\nFactorial of %d is %ld",n,f);
}
long int fact(int m)
{
long int f;
if(m<=1)
return(1);
else
f=m*fact(m-1);
return(f);
}

Related Links :

Program To trace terms of Fibonacci series usng recursion Function in C Programming.



//To trace terms of Fibonacci series usng recursion.

#include
#include

main()
{
int n,i;
clrscr();
printf("Input term number ");
scanf("%d",&n);
printf("Fibonacci series upto %d terms is \n",n);
for(i=1;i<=n;i++)
printf("%d ",fibo(i));
}
//Started Function
//www.lernc.blogspot.com
fibo(int n)
{
int f;
if(n==1 || n==2)
return(1);
else
{
f=fibo(n-1)+fibo(n-2);
}
return(f);
}
//www.lernc.blogspot.com

Related Links :

Program to Copy one string into other without using string function in C Programming



//Copy one string into other without using string function
//www.lernc.blogspot.com
#include
#include

main()
{
int i;
char a[15],b[15];
clrscr();
i=0;
printf("\n Input a string \n");
scanf("&s",a);
while(a[i]!='\0')
{
b[i]=a[i];
i++;
}
b[i]='\0';
printf("\n Copied string is %s",b);
}

//www.lernc.blogspot.com


http://www.lernc.blogspot.com

Related Links :

Program to Copy one string into other using string function in c language.


//www.lernc.blogspot.com

#include
#include
#include

main()
{
char a[15],b[15];
clrscr();
printf("\n Given the string \n");
gets(a);
strcpy(b,a);
printf("\n Copied string is ");
puts(b);
}

//www.lernc.blogspot.com

Related Links :

Program to show String concatenation using string function in c language.




#include
#include
#include

main()
{
char a[15],b[15];
clrscr();
printf("\n Given first string \n");
gets(a);
printf("Give second string \n");
gets(b);
strcat(b,a);
printf("\n resultant string is ");
puts(b);
}

Related Links :

Program to show String concatenation without using string function in C Language.



//String concatenation without using string function
//www.lernc.blogspot.com

#include
#include

main()
{
int i,l;
char a[15],b[30];
clrscr();
i=0;
printf("\n Given first string \n");
scanf("%s",a);
printf("Given second string \n");
printf("www.lernc.blogspot.com");
scanf("%s",b)
l=strlen(b);
while(a[i]!='\0')
{
b[l+i]=a[i];
i++;
}
b[l+i]='\0';
printf("\n Concatenated string is %s",b);
}

Related Links :

Program To compare two strings using string functions.



#include
#include
#include

main()
{
char a[80],b[80]
int n;
clrscr();
printf("input a string ");
gets(a);
printf("input another string ");
gets(b);
clrscr();
printf("first string is : ");
puts(a);
printf("\nsecond string is : ");
puts(b);
n=strcmp(a,b);
if(n==0)
printf("\nentered strings are same");
else
printf("\nentered strings are different");
}

Related Links :

Program To display the statistics of given string using character functions.





#include
#include
#include
#include

main()
{
char text[80];
int vow, con, dig, spa, deli, work;
int i;
clrscr();
vow=con=dig=spa=deli=word=0;
printf("Input a sentence\n");
gets(text);
for(i=0;text[i]!='\0';i++
{
switch (text[i])
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vow++;
break;
default:
if(isalpha(text[i]))
con++;
else
if(isspace(text[i]))
spa++;
else
if(isdigit(text[i]))
dig++;
else
if/(ispunct(text[i]))
deli++;
}
}
word=spa+1
printf("\nLengh of string is %d characters",i);
printf("\nTotal vowels = %d",vow);
printf("\nTotal consonants = %d",con);
printf("\nTotal spaces = %d",spa);
printf("\nTotal Words = %d",word);
printf("\nTotal Digits = %d",dig);
printf("\nTotal delimeters = %d",deli);
}

Related Links :

To display the statistics of given string.




(Vowels, consonants, digits, spaces, delimiters, words)

#include
#include

main()
{
char ss[80]
int i,v,c,s,d,p;
clrscr();
i=v=c=s=d=p=0;
printf("Input a sentence\n");
gets(ss);
for(i=0;ss[i]!='\0'i++)
{
switch(ss[i])
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
v++;
break;
case' ':
s++;
break;
default:
if(ss[i]>='0' && ss[i]<='9')
d++;
else
if((ss[i]>='a' &&
ss[i]<='z')||(ss[i]>='A'
&& ss[i]<='Z'))
c++;
else
p++;
}
}
printf("\nIn given string\n";
printf("\nVowels = %d",v);
printf("\nConsonants = %d",c);
printf("\nDigits = %d",d);
printf("\nSpaces = %d",s);
printf("\nDelimiters = %d",p);
printf("\nWords = %d",s+1);
}

Related Links :

To check whether entered word is palindrome.





#include
#include
#include

main()
{
char a[20]
int i,l,status=0;
clrscr();
printf("Input a string\n");
gets(a);
l=strlen(a);
for(i=0;i<=l/2;i++)
{
if(a[i]!=a[l-1-i])
{
printf("\nEntered string is not palindrome");
status=1;
break;
}
}
if(status==0)
printf("\nEntered string is palindrome");
}

Related Links :

To count the occrance of two successive vowels in a string.





#include
#include

main()
{
char n[80];
int j,l,count=0,x;
clrscr();
printf("Input a string ");
gets(n);
l=strlen(n);
for(j=0;j<1-1;j++)
{
switch(n[j])
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
x = checknext(n[j+1]);
if(x==1)
count++;
}
}
printf("\nIn entered string, two successive vowels occurs %d time(s)",count);
}
checknext(char x)
{
if(x=='a'||x=='A'||x=='e'||x=='E'||x=='i'||x=='I'||x=='o'||x=='O'||x=='u'||x=='U')
return(1);
else
return(0);
}

Related Links :

To arrange array elements in sorted order (ascending) using bubble sort method.





#include
#include

main()
{
int a[20],n,i,j,t;
clrscr();
printf("input size of array ");
scanf("%d",&n);
printf("\nInput %d array elements\n",n);
for(i=0;iscanf("%d",&a[i]);
printf("\nOriginal array is\n");
for(i=0;iprintf("%d ",a[i]);
for(i=0;i{
for(j=0;j{
if(a[i]{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\nSorted array is\n");
for(i=0;iprintf("%d ",a[i]);
}

Related Links :

To calculate product of two arrays (Matrix Multiplication).





#include
#include

main()
{
int a[5][5],b[5][5],c[5][5];
int i,j,k;
int r1,c1,r2,c2;
clrscr();
printf("Input size of first array");
scanf("%d%d",&r1,&c1);
printf("Input size of second array");
scanf("%d%d",&r2,&c2);
if(c1==r2)
{
printf("\nInput %d elements of first array",r1*c1);
for(i=0;ifor(j=0;jscanf("%d",&a[i][j]);
printf("\nInput %d elements of first array",r1*c1);
for(i=0;ifor(j=0;jscanf("%d",&b[i][j]);
clrscr();
printf("\nEntered first array is \n");
for(i=0;i{
for(j=0;j{
printf("%d",&a[i][j]);
}
printf("\n");
}
printf("\nEntered second array is \n");
for(i=0;i{
for(j=0;j{
printf("%d ",b[i][j]);
}
printf("\n");
}
printf("\nProduct of above arrays is\n");
for(i=0;i{
for(j=0;j{
c[i][j]=0;
for(k=0;k{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
]printf("%d ",c[i][j]);
}
printf("\n");
}
}
else
printf("\nWrong dimensions, not suitable for product ...");
}

Related Links :

To search given element in sorted array using binary search method.



To search given element in sorted array using binary search method.

#include
#include

main()
{
int a[100],n,i,ITEM,MID,LB,UB,found=0;
clrscr();
printf("Enter number of nodes in array ");
scanf("%d",&n);
for(i=0;i{
printf("Input INFORMATION at NODE %d",i+1);
scanf("%d",&a[i]);
}
printf("Enter element to be searched : ");
scanf("%d",&ITEM);
LB=0;
UB=n-1;
MID=(LB+UB)/2;
while(LB<=UB)
{
if(a[MID]==ITEM)
found=MID;
if(a[MID]>ITEM)
UB=MID-1;
else
LB=MID+1;
MID=(LB+UB)/2;
}
if(found==0)
printf("\nThe element is not present ");
else
printf("\nElement found at position %d",found+1);
getch();
}

Related Links :

To input a square matrix and calculate sum of



To input a square matrix and calculate sum of
1. Diagonal element
2. Lower triangular elements
3. Upper triangular elements

#include
#include

main()
{
int a[5][5],i,j,m,n,s=0,sl=0,su=0;
clrscr();
printf("Input array size ");
scanf("%d%d",&m,&n);
if(m==n)
{
printf("\nInput %d elements ",m*n);
for(i=0;ifor(j=0;jscanf("%d",&a[i][j]);
clrscr();
printf("\nEntered array is \n");
for(i=0;i{
for(j=0;j{
printf("%d",&a[i][j]);
if(i==j)
s=s+a[i][j];
if(isu=su+a[i][j];
if(i>j)
sl=sl+a[i][j];
}
printf("\n");
}
printf("\nSum of diagonal elements = %d",s);
printf("\nSum of upper triangular matrix is %d",su);
printf("\nsum of lower triangular matrix is %d",sl);
}
else
printf("\nWrong dimensions, not a square array ...");
}

Related Links :

To input and print a 3-dimensional integer array.





#include
#include

main()
{
int m[5][5][5],a,b,c,i,j,k;
clrscr();
printf("Input dimension of 3-D array ");
scanf("%d%d%d",&a,&b,&c);
printf("Input %d integers \n",a*b*c);
for(i=0;ifor(j=0;jfor(k=0;kscanf("%d",&m[i][j][k]);
printf("\nEntered 3 dimensional array is\n");
for(i=0;i{
for(j=0;j{
for(k=0;k{
printf("%d ",m[i][j][k]);
}
printf("\n");
}
printf("\n");
}
getch();
}

Related Links :

To merge two sorted integer arrays.




#include
#include

main()
{
int i,j,k,m,n,r,a[10],b[10],c[20];
clrscr();
printf("Input size of two matrices ");
scanf("%d%d",&m,&n);
printf("\nInput %d elements of first array in ascending order \n",m);
for(i=0;iprintf("\nInput %d elements of second array in ascending order\n",n);
for(i=0;ii=j=k=0;
while(i{
if(a[i]{
c[k]=a[i];
i++;
k++;
}
else
{
c[k]=b[j];
j++
k++;
}
}
if(m>i)
{
for(r=i;r{
c[k]=b[r]
k++;
}
if(n>j)
{
for(r=j;r{
c[k]=b[r];
k++
}
}
printf("\nSorted mearged array is\n");
for(i=0;i}

Related Links :

To input roll number and marks in 3 subjects for 5 students and print the result sheet.





#include
#include

main()
{
ind r[5],m1[5],m2[5],m3[5],i;
float p[5];
clrscr();
for(i=0;i<5;i++)
{
printf("\nInput roll number and marks in 3 subject for student %d \n",i+1);
scanf("%d%d%d%d",&r[i],&m1[i],&m2[i],&m3[i]);
}
clrscr();
for(i=0;i<75;printf("-"),i++);
printf("\nRoll no\t Marks obtained in \t Percentage\t Result");
printf("\n\t sub1 sub2 sub3\n");
for(i=0;i<75;printf("-"),i++);
for(i=0;i<5;i++)
{
p[i]=(m1[i]+m2[i]+m3[i])/3.0;
printf("\n%d\t%d\t%d\t%d\t%5.2f\t",r[i],m1[i],m2[i],m3[i],p[i]);
if(p[i]<40.0)
printf("\tfail");
else
printf("\tpass");
}
printf("\n");
for(i=0;i<75;printf("-"),i++);
}

Related Links :

To claculate sum of 2 on-dimensional array.





#include
#include

main()
{
int m,n,i;
int a[15],b[15],c[15];
clrscr();
printf("Input size of first array ");
scanf("%d",&n);
printf("\nInput size of second array ");
scanf("%d",&m);
if(n==m)
{
printf("\nInput %d elements of first array\n",n);
for(i=0;iscanf("%d ",&a[i]);
printf("\nInput %d elements of second array\n",m);
for(i=0;iscanf("%d ",&b[i]);
clrscr();
printf("\nFirst array is \n");
for(i=0;iprintf("%d ",a[i]);
printf("\nSecond array is \n");
for(i=0;iprintf("%d ",b[i]);
printf("\nSum of above 2 arrays is\n");
for(i=0;i{
c[i]=a[i]+b[i];
printf("%d ",c[i]);
}
}
else
printf("\nArray sizes are different, not possible to add arrays ");
}

Related Links :

Convert a 4 digit number to equivalent roman number using array.





#include
#include

main()
{
int n,n1,i,k;
int a[]={1000,500,100,50,10,5,1};
char b[]={'M','D','C','L','X','V','I'};
clrscr();
printf("Input a number ");
scanf("%d",&n);
printf("\nROMAN equivalent of %d is ",n);
for (k=0;k<7;k++)
{
n1=n/a[k];
for(i=0;iprintf("%c",b[k]);
n=n%a[k];
}
}

Related Links :

The find the first occurnce of a number in an array. Also find its position.




#include
#include

main()
{
int a[10],i,n,p,s;
clrscr();
printf("Input array size ");
scanf("%d",&n);
printf("\nInput %d elements ",n);
for(i=0;iscanf("%d",&a[i]);
printf("\nInput an element to be searched ");
scanf("%d",&s);
for(i=0;i{
if(a[i]==s)
{
printf("\nFirst occurence of %d is at position %d",s,i+1);
break;
}
if(i==n)
printf("\n%d not found is array",s);
}
}

Related Links :

To delete duplicate elements in an array.





#include
#include

main()
{
int a[20],i,j,k,n;
clrscr();
printf("input array size ");
scanf("%d",&n);
printf("\ninput %d array elements\n",n);
for(i=0;iscanf("%d",&a[i]);
clrscr();
printf("original array is\n");
for(i=0;i{
for(j=i+1;j{
if(a[j]==a[i])
{
for(k=j;k{
a[k]=a[k+1];
}
n--;
}
else
j++;
}
}
for(i=0;iprintf("%d ",a[i]);
}

Related Links :

To print a 4 digit number in words using switch()





#include
#include

main()
{
int n,m,d,s=0,i,j,p,k;
clrscr();
printf("Input a 4 digit number ");
scanf("%d",&n);
m=n;
k=3;
if(n>9999)
{
printf("\nNot a 4 digit number");
}
else
for(i=1;i<=4;i++)
{
d=n%10;
p=1;
for(j=1;j<=k;j++)
{
p=p*10;
}
s=s+d*p;
n=n/10;
k--;
}
printf("\nThe number %d in words is;",m);
for(i=1;i<=4;i++)
{
d=s%10;
switch(d)
{
case 1:
printf("One ");
break;
case 2:
printf("Two ");
break;
case 3:
printf("Three ");
break;
case 4:
printf("Four ");
break;
case 5:
printf("Five ");
break;
case 6:
printf("Six ");
break;
case 7:
printf("Seven ");
break;
case 8:
printf("Eight ");
break;
case 9:
printf("Nine ");
break;
case 0:
printf("Zero ");
break;
}/* end of switch() */
s=s/10;
}/* end of for() */
}

Related Links :

To print a 4 digit number in words using switch()





#include
#include

main()
{
int n,m,d,s=0,i,j,p,k;
clrscr();
printf("Input a 4 digit number ");
scanf("%d",&n);
m=n;
k=3;
if(n>9999)
{
printf("\nNot a 4 digit number");
}
else
for(i=1;i<=4;i++)
{
d=n%10;
p=1;
for(j=1;j<=k;j++)
{
p=p*10;
}
s=s+d*p;
n=n/10;
k--;
}
printf("\nThe number %d in words is;",m);
for(i=1;i<=4;i++)
{
d=s%10;
switch(d)
{
case 1:
printf("One ");
break;
case 2:
printf("Two ");
break;
case 3:
printf("Three ");
break;
case 4:
printf("Four ");
break;
case 5:
printf("Five ");
break;
case 6:
printf("Six ");
break;
case 7:
printf("Seven ");
break;
case 8:
printf("Eight ");
break;
case 9:
printf("Nine ");
break;
case 0:
printf("Zero ");
break;
}/* end of switch() */
s=s/10;
}/* end of for() */
}

Related Links :

To convert decimal number to binary number





#include
#include

main()
{
int a[16],n,i=1,j,x=0;
clrscr();
printf("Input a decimal number ");
scanf("%d",&n);
while(n>0)
{
x=n%2;
a[i]=x;
n=n/2;
i++;
}
printf("\nBinary equivalent is : ");
for(j=i-1;j>=1;j--)
printf("%d",a[j]);
}

Related Links :

To print prime factors of an integer number





#include
#include
#include

main()
{
int n,i=2,r;
clrscr();
printf("give a number ");
scanf("%d",&n);
printf("\n%d = 1",n);
while(i<=n)
{
if(n%i==0)
{ printf(" x%d ",i);
n=n/i;
continue;
} i++;
}
if(n>1) printf(" %d ",n);
getch();
}

Related Links :

To print reverse of five digit number





#include
#include

main()
{
int i;
long int n,n1,a,b,c;
clrscr();
printf("give five digit number ");
scanf("%ld",&n);
n1=n;
for(i=1;i<=5;i++)
{
a=n1%10;
b=n1-a;
printf("%d",a);
n1=b/10;
}
}

Related Links :

To find the nature and value of roots of quadratic equation.





#include
#include
#include

main()
{
int a,b,c;
double d,e,x1,x2;
clrscr();
printf("Enter values of coefficients of quadratic equation ");
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
e(-b)/(float)(2*a);
if(d==0)
{
x1=-b/(float)(2*a);
printf("\nRoots are real and equal\n");
printf("\nroot 1 = root 2 = %f",x1);
}
else
{
if(d>0)
{
printf("\nRoots are real and different\n");
x1=e+ sqrt(d)/(float)(2*a);
x2=e- sqrt(d)/(float)(2*a);
printf("\nRoot 1 = %f",x1);
printf("\nroot 2 = %f",x2);
}
else
{
printf("\nRoots are immaginary\n");
d=d*(-1);
x1=sqrt(d)/(float)(2*a);
x2=sqrt(d)/(float)(2*a);
printf("\nRoot 1 = %f + %f i",e,x1);
printf("\nRoot 2 = %f - %f i",e,x2);
}
}
getch();
}

Related Links :

To convert binary number to decimal equivalent.





#include
#include

main()
{
long int n;
int x,s=0,i=0,flag=1;
clrscr();
printf("Input a binary number ");
scanf("%ld",&n);
while(flag==1)
{
x=n%10;
s=s+x*power(i);
i=i+1;
n=n/10;
if(n==0)
flag=0;
}
printf("\nDecimal equivalent = %d",s);
}
power(int i)
{
int j,p=1;
for(j=1;j<=i;j++)
p = p*2;
return(p);
}

Related Links :

Memory management functions in C

malloc()
• On execution of malloc() function, the memory is allocated to local variable.
• This memory is taken form free pool.
• The parameter for malloc() is an integer that specifies the number of bytes needed.
• The prototype of this function is in header file alloc.h, stdlib.h
• Syntax:
void *malloc(size n);
• This returns a pointer to n bytes of un-initialized storage or NULL if the request can not be satisfied.
• Example:
char *string;
string = malloc(n);
• In above statement, a string of type char* is declared where n is the variable containing number of bytes needed.

Related Links :

Storage classes in C

• Storage class helps us to define
1. Where to store the variable
2. What is the initial value of variable?
3. How much is the life of a variable?
4. What is the scope of the variable?
• There are 4 storage classes – auto, static, register, and extern.
• auto:
o An auto variable is created each time the block in which it is declared is entered and is destroyed each time the block is exited.
o Such variable can be declared only in functions.
o By default, a local variable is auto but it can be declared to be of another storage class by the use of explicit storage class in its declaration.
o A function cannot be declared as auto.

• static
o These variables remain in existence throughout the execution of the program.
o Global and local variables can be declared as static but not formal arguments.
o When a global variable or function is declared explicitly to be static, its scope is restricted to the file in which it is declared.
• register
o A local variable or formal parameter can be declared to be register.
o Here declaration means to store the variable in a machine register instead of the main memory.
o It is like auto variable since it disappears when the function exists.
o The only restriction is that a register variable must be of a type whose size is not longer than the size of a register.
o The address of register cannot be taken and hence & operator may not be used.
o A function of global variable cannot be declared as register.
• extern
o This storage class does not allocate any memory for a variable but declares it to have been created elsewhere in the program.
o This declaration must be used to access a global variable declared in another file in which it may be used in either global or local declaration.
o A formal parameter cannot be extern.
o A function is by default extern although this storage class needs never to be used in a function definition declaration.


Related Links :

Different file opening modes in C

• File opening mode specifies the purpose for which programmer wants to open the file.
• C provides three basic purposes; read, write and append.
• And the basic modes area “r” for reading, “w” for writing, and “a” for appending data.
• All basic and mixed modes are tabulated below:
Mode Purpose
r Read in text mode
w Write in text mode
a Append in text mode
r+ Read + write in text mode
w+ Write + read in text mode
a+ Append + read in text mode
rb Reade in binary mode
wb Write in binary mode
ab Append in binary mode
rb+ Read + write in binary mode
wb+ Write + read in binary mode
ab+ Append + read in binary mode
• The file opening mode to be used depends upon requirement and “whether the file already exists?”
• Some important situations are given below.
Mode File already exist File does not exist
r Read -
w Overwrite Create
a Append Create

Related Links :

Difference between functions and macros in C

• Macro templates are replaced by macro expansion by preprocessor.
• Whenever function is called, execution goes to that function, calculations are performed and execution returns to main.
• Macros are faster than functions.
• In macros program size increases if called for more times.
• In function program remains compact even though called for several times.
• No address is associated with macro identifier and hence pointers cannot be used with macros.
• When we pass the arguments to the macro, it never checks for their data types and checks for only the number of arguments.

Related Links :

Enumeration: declaration with example in C


• Enumeration is a type specifier.
• It is a unique type with integer constants.
• Enumerations are unique types with values ranging over a set of named constants called enumerators.
• The identifiers in an enumerator list are declared as constants of type int, and may appear wherever constants are required
• Its syntax is vary much same as that of structure or union.

Related Links :

Differentiate between union and structure in C.

• Union and structure are two secondary data types in C which are sued to represent and entity in database.
• Although the syntax of union and structure is very much similar, the purpose of both is different.
• Structure is a set of heterogeneous data elements stored in successive memory locations whereas union is a set of heterogeneous data elements in which the storage of each element originate at the same location.
• Union is more memory economical than structure.
• Memory requirement of structure is the sum of memory requirement of all members whereas memory requirement of union is the memory of element that requires maximum memory.
• Union is mainly used when we need to use only member at a time, even if several members are declared.

Related Links :

typedef with structures in C

• Using typedef with structure, programmer can define new data type names for structure.
• The syntax for typedef with structure is very much similar to typedef with other types.
• It can be made more clearly using following example.
• In the following definition, p is an array of 10 records, which has the same structure as the person.
typedef struct
{
char name[10];
int height, weight;
}person;
Person p[10];

Related Links :

Purpose of typedef feature in C

• The typedef feature provides the facility for defining new data type name.
• That is, using typedef programmer can define own data type names that represent the existing data types.
• Syntax
typedef type identifier;
Where, type is the existing data type and identifier is the new name given to existing data type.
• Example
typedef int integer;
After this declaration in program, the integers can be declared using word integer like-
integer a,b;

Related Links :

Pointer definition in C


• Pointer is a variable that holds the address of data rather than the data itself.
• Address is a memory location.
• Pointers provide facility to play with memory locations.
• Other languages like BASIC, COBOL, FORTRAN etc. do not provide such facility.
• Pointer points to something that is stored somewhere in memory.
• We can use pointer to point any variables viz. integer, character, float, array string, structure, file etc.
• Pointers are used to point to different data and different data structures.
• Pointers can also be initialized as an expression that involves the address of previously defined data of appropriate type.

Related Links :

Recursion: definition and example in C

• A user – defined function, which calls itself, is called a recursive function and the process is called recursion.
• In many programming situations, we required to execute same function several times.
• A function is called recursive, if
A. There exit some base criterion for which function will not call itself but will return some constant. And
B. In every recursive call, the argument must tent to base criterion.
• For example,
To calculate sum of number 1…100
Sum(100) =100+sum(99)
=100+99+sum(98)
=100+99+…+sum(1)
Here the function sum()is the recursive function.
While calculating sum(100), we are calling function sum(99)
In C programming the function is implemented as
int sum (int n)
{
int s:
if (n==1)
return(1);
else
s=n+sum(n-1);
return(s);
}

Related Links :

Need of User Defined Functions in C

• Functions are the building blocks where every program activity occurs.
• Functions are self-contained program blocks that carry out some specific, wel-defined task.
• User defined functions are subordinate to main() and also to one another.
• If facilitates top-down modular programming.
• Length of program can be reduced using functions.
• It makes debugging easier.
• It provides the facility of reusability of module.

Related Links :

strcat()

• This function concatenates (combines) one string into another and returns the concatenated string.
• The prototype of function is defined in header file string.h
• Syntax
Char *strcat(char*dest, const char *src);
• The first argument of function is destination string and second argument is source string.
• The function combines source string into destination string and returns destination string i.e. first argument of function.
• Example:
strcat(a, “xxx”);
here, “xxx” is concatenated to string variable a.

Related Links :

Syntax and usage of strcmp(), strcat() in C.

strcmp()
• This function compares two strings (variables / constants) and returns integer value.
• The prototype of function is in header file string.h
• Syntax
int strcmp(const char*s1,const char*s2);
where s1 and s2 are two strings.
• The function compares string s2 with string s1.
• If s1s2, it returns value greater than zero.
• While comparing it compares ASCII value of symbol
• Example
a = strcmp(a1,a2);
This compares two string variables a1 and a2.
b = strcmp(“mouse”, “Mouse”);
This compares two string constants.

Related Links :

Purpose of the getchar() with example in C.

• This function is used to get a character from standard input i.e. Keyboard.
• On successful execution, it returns character read.
• The prototype of this function is in the header file stdio.h.
• Syntax
int getchar (void);
• Example
ch = getchar();

Related Links :

Storage of two-dimensional array in memory in C

• A two dimensional array has two subscripts.
• First subscript is for row and second for column.
• The syntax for declaration of two dimensional array is
data_type arr[row_size][column_size];
• Consider the example int aa[5][5];
Here aa is an integer array of size 5x5
i.e. total 25 elements.
• The array elements are represented using the subscript.
• While storing in memory, each dimension of the array is indexed from zero to it’s maximum size-1.
• The first subscript indicate row and second subscript indicates column.
• For eg. Consider an integer array of size 2x3 as
int b[2][3]={10,20,30,40,50,60};
The array b is represented in memory as

Col.0 Col.1 Col.2
row0 10 20 30
row1 40 50 60

Where,
b[0][0]=10
b[0][1]=20
b[0][2]=30
b[1][0]=40
b[1][1]=50
b[1][2]=60

Related Links :

Difference between array and ordinary variable in C

• The difference between the definition of array and ordinary variable is the, array is always declared, initialized, and accessed using subscript whereas ordinary variable do not have any subscript.
• The syntax for ordinary variable definition is
data_type v1, v2, ….;
• And the syntax for array variable is
data_type v1[N1],v2[N2],…;
where v1,v2 are name of variable and N1, N2 are the integer constants indicating the maximum size of array.

Related Links :

Array definition in C

• In a program when programmer needs several variables of same type then instead of defining several variables, it is possible to define a single variable with several subscripts.
• This subscripted variable is called array.
• Array is defined as a finite set of homogeneous data elements stored in successive memory locations.
• Array may have one or many dimensions.
• If there is only one subscript then it is called single subscripted variable or one dimensional array and it represent one dimensional matrix i.e. either row matrix or column matrix.
• If there are two subscripts then it is called double subscripted variable or two-dimensional array and it represent two dimensional matrix.

Related Links :

continue statement in C

• Syntax: continue;
• This statement can be used only in the iteration statements i.e. do, while, and for.
• It causes the transfer of control to the loop continuation part of the loop and re-evaluates the condition.
• This statement has no argument.
• Example:
while (i<=n)
{
if(n%i==0)
{
n=n/i;
continue;
}
i++;
}

Related Links :

Error handling during input/output operations in C

• During input/output, Errors in C occurs due to missing of Semicolon (;),
Comma(,)
Quotation marks(“),
Incompatible format specifier (%),
• Other than these, the commonly occurring errors during input/output are explained below with their cause.

Related Links :

Trigraph characters is C

• The C character set is contained within seven-bit ASCII.
• In order to write programs in the reduced set, corresponding single characters replace the occurrences of the trigraph characters.
• The replacement occurs before any processing.
Trigraph charager replaced by
??= #
??/ \
??’ ^
??( [
??) ]
??! |
??< { ??> }
??- ~

Related Links :

To convert binary number to decimal equivalent.




#include
#include

main()
{
long int n;
int x,s=0,i=0,flag=1;
clrscr();
printf("Input a binary number ");
scanf("%ld",&n);
while(flag==1)
{
x=n%10;
s=s+x*power(i);
i=i+1;
n=n/10;
if(n==0)
flag=0;
}
printf("\nDecimal equivalent = %d",s);
}
power(int i)
{
int j,p=1;
for(j=1;j<=i;j++)
p = p*2;
return(p);
}

Related Links :

Escape sequence: purpose & characteristics in C

• The escape sequence characters are also called as backslash character constants.
• These are used for formatting the output.
• The escape sequence characters are
\a audible bell
\b back space
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ back slash
\0 null character
\’ single quote
\” double quote
\000 octar number
\xhh hexadecimal number
• Characteristics
1) Although it consists of two characters, it represents single character.
2) Every combination starts with back slash(\)
3) They are nonprinting characters.
4) It can also be expressed in terms of octal digits or hexadecimal sequence
5) Each escape sequence has unique ASCII value.
6) Escape sequence in character constants and string literals are replaced by their equivalent and then adjacent string literals are concatenated.

Related Links :

Rules for constructing variable name in C

• Variable name may be a combination of alphabets, digits or underscores.
• Sometimes, compilers in which case its length should not exceed 8 characters impose an additional constraint on the number of characters in the name.
• First character must b e alphabet or an underscore.
• No. comma or blank space is allowed.
• Among the special symbols, only underscore can be used in variable name.
No word, having a reserved meaning in C can be used for variable name.

Related Links :

C program which can be used as command name cat to concatenate the files, whose names are supplied as arguments to command.




#include

#include

main(int argc, char *argv[ ])
{
FILE *s, *t;
char c;
if(argc!= 3)
{
puts("Wrong no. of parameters.\n");
printf("Correct command should be filename file 1 file2.");
}
s = fopen(argv[ 1 ], "r");
if(s = NULL)
printf("source file not found\n");
exit();
}
t = fopen(argv[2],"a");
if(t==NULL)
{
puts("target file cannot be created \n")
fclose(s);
exit();
}
while((fgete(s))!= EOF)
fputc(c,t);
puts("Files concatenated successfully.\n");
fclose(s);
fclose(t);
}

Related Links :

the purpose of putchar function? How putchar is used within C program? Compare putchar with getchar function.

putchar() is a standard library function defined in stdio.h header file. It is used for printing one character on the screen at a time.

The syntax of this function is,

putchar(ch);

where, ch is a char type variable.

The following program shows how to use this function.




#include
main()
{
char ch = 'A';
putchar(ch);
}

Upon execution this program prints out A on screen.

getchar() is standard library function to get one character from keyboard. The getchar() function echo's the character on screen followed by enter key. The syntax of this function is

ch = getchar().

Both the functions are defined in stdio.h header file.

Related Links :

Program to copy one file into another using character arrays.



#define MAX 80
#include
#include

main()
{
FILE *fs, *ft;
static char sfn[MAX];
static char tfn[MAX];
char ch, str[MAX];

puts("Enter source filename.");
gets(sfn);

if((fs = fopen(sfn, "r")) == NULL)
{
puts( "Source file does not exists.");
exit(0);
}

puts("Enter target filename");
gets(tfn);

if(fp = fopen (tfn, "w") == NULL )
{
puts("Target file cannot be created.");
fclose(fs);
exit(0);

}
while(1)
{
if (fgets(str, fs=NULL) fputs (str, ft);
else
break;
fclose(fs);
fclose(ft);
}
}

Related Links :

Opening and closing of a data file in C

Many applications require that information be written or read from an auxiliary storage device. Such information is stored on the device in the form of a data file. Thus, a data file allows us to store information permanently and to access and alter that information whenever necessary. There are two types of data files, one is stream-oriented (or standard) data files and second is system-oriented (or low-level) data files.

When working with a stream - oriented data file, the first step to establish a buffer area, where information is temporarily stored while being transferred between computers memory and the data file. The buffer area is established by writing

FILE * Pointer var;

Where, FILE is a special structure type that establishes the buffer area and pointer variable indicates the beginning of buffer area. The FILE is defined in a, file "stdio.h".
A data file must then be opened before it can be created and processed. The library function 'fopen' is used to open a file. The syntax of fopen is

pintervar = fopen (filename, mode)

where, filename is name of datafile which you wish to open and mode indicates the mode in which this file will get open up. The modes in which the user can open a file are :

Modes Meaning

  • "r" Open an existing file for reading only.
  • "w" Open a new file for writing. If already exist then create new one by deleting old one.
  • "a" Open an existing for appending.
  • ( To append means add at the end).
  • "r + " Open an existing file both for reading and writing.
  • "w + " Open a new file both for reading and writing.
  • "a + " Open an existing file both for reading and appending.

The fopen function returns a pointer to the beginning of buffer area associated with the file. A NULL value is returned if the file cannot be opened, for ex., when an existing data file cannot be found.

A data file opened using fopen must be closed at the end of the program. A library function fclose is used for this purpose.
The syntax for fclose is :

fclose (pointervar);

Some applications involved the use of data files to store block of data, where each block consist of a fixed number of continuous bytes. Each block will generally represent a complex data structure such as a structure or a array. For such application, it may be desirable to read the entire block from the data file or write the entire block to the data file, rather than reading and writing a individual component.

The library functions fread and fwrite are used for this purpose. These function are often referred to as unformatted read & write functions. Similarly, data file of this type are referred to as unformatted data file.

In syntax of each of these function requires four arguments:

1) a pointer to a data block,
2) the size of data block
3) the number of data blocks being transferred and
4) the pointer variable attached to the file.


The syntax for fwrite is :

fwrite(ptr, sizeof (block), no of data blocks, pointerver)
Ex. fwrite(&bank, sizeof (record), 1, fs);




#include
#include
main()
{
FILE *fs, *ft;
char ch;
if((fs= fopen("c :\\biol.c", "rt")) == NULL)
{
puts("File not found."); exit(0);
}
if((ft = fopen("c:\\bio1 .d", "w")) = = NULL)
{
puts("Target file cannot be created.");
fclose(fs);
exit(0);
}
while((ch = getc (fs))!= EOF)
{
putc(ch, ft);
}
puts("File copied successfully.");
fclose(fs);
fclose(ft);
}

Related Links :

Unformatted console I/O functions.

The functions under this category are :
getch() putch() gets()
getche() putchar() puts()
getchar() fputchar()
fgetchar()


These above listed function broadly fall into two categories, the one which deal with a single character and the second which deal with a string of characters.

Explanations :

getch() : This function will read a single character the instant it is typed by programmer without waiting for the Enter Key to be hit. The typed character is not echoed on screen.

getche() : This function will also read a single character the instant it is typed by programmer without waiting for the Enter key to be hit, just like getch() function. The additional character 'e' in function getch() echoes the character on screen that you typed. This is a point of differences between getch() & getche().

getchar() : It works similar to that of getch() and also echoes the character you typed on the screen but it also requires enter key to be hit immediately after the character that you typed. It is a macro.

fgetchar() : It will echo the character on screen and it requires hit of Enter key immediately following the character. The only difference between getchar() and fgetchar() is that the former is a macro and latter is function.

putch() : It writes a character to the screen.

putchar() : It writes a character to the screen and is a macro.

fputchar() : It writes a character to the screen (function version).

(Note : putch(), putchar() and fputchar() can output only one character at a time on screen.)

gets() : It gets a string from the keyboard and it is necessary on programmers part to terminates that string with an Enter key. That's why spaces and tabs are acceptable as a part of the input string if any gets() is used to read only one string at a time.

puts() : It outputs a string to the screen puts() can outputs only one string at a time.

Related Links :

What is a function prototype?

In the portion of program, where user defines variable, functions can be declared or defined using following syntax :

data-type name of function (datatype 1 arg1, datatype 2 arg 2,datatype n arg n);

where arg 1, arg 2, .......arg n are arguments of this function and datatype 1 datatype are data types of these individual arguments. Function declaration written in its fashion are called function prototype.

Ex.
int fort (int n);
int ncr (int n, int r);
float ncr (int n, int r);


The data type written before name of the function is the type of result the function returns. The use of function prototype is not mandatory in C. Function prototype are desirable, because they further facilitate error checking between the call to a function and the corresponding function definition.

When the function is called, the name of the actual arguments need not be the same as the names shown in the declaration. However, the data types of the actual arguments must conform to the data types of the arguments within the declaration.

Related Links :

Program to determine whether given character is vowel or consonant

In english language A,E,I,O,U vowels. Following program takes one character and checks it for vowel condition using || (or) as logical operator.




#include

main()
{

char ch;
clrscr();

pritnf("\nEnter any character:");
fflush(stdin);
scanf("%c",&ch);
if (ch == 'A' || ch = 'a'|| ch = 'E ' || ch == 'e' || ch == T || ch == 'i' ||
ch == 'O' || ch == 'o' || ch == 'U' || ch = 'u')
{
printf("\n The entered character %c is Vowel.\n", ch);
}
else
{
printf("\nThe entered character %c is not Vowel.\n",ch);
}
}

Related Links :

a program to convert and print this distance in meters, feet, inches and centimeters.



main()
{
float km, m, cm, inch, feet;
printf("\nEnter distance in kilometer:");
scanf("%f",&km);
m=km*1000;
cm=m*100;
inch=cm/2.54;
feet=inch/12;
printf("Meters : %f",m);
printf("Centrimeters: %f",cm);
printf("Inches: %f",inch);
printf("Feet: %f",feet);
}

Related Links :

Rules of a function that returns a value.

1) Function name should follow the rules of variable name.
2) Actual argument(s) and formal argument(s) should be same in number as well as their data type(s).
3) Function may or may not return any value. Function by default returns only integer value.
4) Function can return only one value at a time. To return any value from function, return statement should be used.
5) If a function returns a value other than the integer value then, return data type should be mentioned before the function name in function declaration. Also, prototype definition of such a function should be mentioned before main, if function call precedes function definition.
6) Function which doesn't return any value should be declared as void function.

e.g.


float square(float);
/* prototype definition */




main()
{
float s;
s = square(2.5);
/* function call*/

printf("%",s);
}

/*function declaration*/

float square(float n)
{
return(n*n);
}

Related Links :

program to convert given decimal number into binary.



main()
{
unsigned int i,j, k
clrscr();
printf("Enter a number in decimals");
scanf("%d",&j);
printf("Binary equivalent of decimal is");
for(i = 0;i<10;i++)
{
k= 1 <<(15-i);
if((j && k) = 0)
printf ("0") else
printf("1");
}
}





if input is 2044
out put is 0000011111111100

if input is 98

output is 0000000001100010


Related Links :

What are directed and undirected graphs?

In a directed graph, each edge is represented by a directed pair , V1 is the tail and V2 is the head of the edge. Therefore, and represent two different edges. An unidirectional graph is a graph in which the pair of vertices representing any edge is unordered. Thus the pairs (V1, V2) and (V2, V1) represent the same edges.

Related Links :

program to print binary equivalent of a decimal number Note MSP should print first and LSB last.



main()
{
int n;
printf("\nEnter any number:"); scanf("%d", &n); dec2bin(n);
} dec2bin(int n)
{
if(n == 0)
return ; else
{
dec2bin (n/2); printf("%d", n%10);
}
}

Related Links :

Write a recursive function to find sum of digits of any number input through keyboard.



main()
{
int s, n;
printf("\nEnter any number:");
scanf("%d",&n);
s =sum(n);
printf("\n Sum of digits = %d",s);
}
sum(int n)
{
if(n<10)
return(n); else
return(n %10 + sum(n/10)) ;
}


Related Links :


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!