Tuesday 24 July 2012

Token pasting operator in c language

Token pasting operator in c language
/* use of token pasting operator with Output */
//Token pasting operator is used to concatenate two tokens into a single token.

#include

#define PASTE(a,b) a##b
#define MARKS(sub) marks_##sub
int main()
{
int k1=15,k2=60;
int marks_os= 95, marks_ds=99;

//converting statement below to printf("%d %d",k1,k2)

printf("%d %d ",PASTE(k,1),PASTE(k,2));

//converting statement below to printf("%d %d",marks_os,marks_ds)
printf("%d %d ",MARKS(os),MARKS(ds));}

nesting of macros in c language with output

nesting of macros in c language with output
How to write code for nesting of macros in c language
#include
#define ISLOWER(c) (c>=97&&c<=122) #define ISUPPER(c) (c>=65&&c<=90)
#define ISALPHA(c) ISLOWER(c) || ISUPPER(c)
int main()
{
char chr;
printf("Enter a character:\n");
scanf("%c",&chr);


if (ISALPHA(chr) )

{

printf("%c is an alphabetical character.\n",chr);

}

else

{
printf("%c is not an alphabetical character.\n",chr);
}

return 0;
}

Array in cprogramming

Array in cprogramming
/*Array in c program with code*/

#include

main()

{

char s[ ]="man";

int i;

for(i=0;s[ i ];i++)

printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);

}

Explanation:
As we know array name is the base address for that array. Here s is the base address and i is the index number/displacement from the base address. So, in directing it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].

Void Pointer example in c language

Void Pointer example in c language
/* How to use of void pointer in c language*/

#include

main()

{

int a=10,*j;

void *k;

j=k=&a;

j++;

k++;

printf("\n %u %u ",j,k);

}

Explanation:

Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type. No pointer arithmetic can be done on it and you cannot apply indirection operator (*) on void pointers.

How to write C Program to calculate L.C.M and G.C.D of two numbers using function

How to write C Program to calculate L.C.M and G.C.D of two numbers using function
Program source code

void gcd(int,int);

void lcm(int,int);


int main()

{

int a,b;


printf("Enter two numbers: \t");

scanf("%d %d",&a,&b);


lcm(a,b);

gcd(a,b);



return 0;

}


//function to calculate l.c.m

void lcm(int a,int b)

{

int m,n;


m=a;

n=b;


while(m!=n)

{

if(m
m=m+a;
else
n=n+b;
}

printf("\nL.C.M of %d & %d is %d",a,b,m);
}

//function to calculate g.c.d
void gcd(int a,int b)
{
int m,n;

m=a;
n=b;

while(m!=n)
{
if(m>n)
m=m-n;
else
n=n-m;
}

printf("\nG.C.D of %d & %d is %d",a,b,m);

Enter a four digit number and display it in words conversion

Enter a four digit number and display it in words conversion
C Program to enter a four digit number and display it in words
void main()

{

int n,num,d=0,dig[4];


//Array of strings for numbers from one two ten

char *ones[]={" ", "One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"};


//Array of strings for numbers from ten to nineteen

char *el[]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};


// Array of strings for numbers from twenty , thirty ... upto ninety

char *tens[]={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};


//Accept four digit number

printf("\nEnter a four digit number:-\t");

scanf("%d",&num);


//store the number in another variable

n=num;


//Calculate number of digits in the given number

do

{

dig[d]=n%10;

n/=10;

d++;

}while(n>0);


//Display the number in words depending upon the number of digits

if(d==4)

printf(" %s Thousand",ones[dig[3]]);

if(d>=3&&dig[2]!=0)

printf(" %s Hundred",ones[dig[2]]);


if(d>=2)

{

if(dig[1]==0)

printf(" %s\n",ones[dig[0]]);

else if(dig[1]==1)

printf(" %s\n",el[dig[0]]);

else

printf(" %s %s \n",tens[dig[1]],ones[dig[0]]);

}


if(d==1 && num!=0)

printf(" %s %s \n",ones[dig[0]]);

if(num==0)

printf(" Zero\n");

}

Functioning of printf : Inability to perform conversions

Functioning of printf : Inability to perform conversions
Functioning of printf : Inability to perform conversions using code with output

printf("%f\n",6);

printf("%d",18.0);

}

Both the above results are unexpected. The reason is that first we let printf to convert 6 to 6.0

Then we let printf to convert 18.0 to 18

But printf is not intelligent enough to perform this conversion. So we are getting unexpected results.

swap values of two variables using call by reference comments

swap values of two variables using call by reference comments
How to write C Program to swap values of two variables using call by reference
#include


//function to swap values

void swap(int *a,int *b)

{

int temp;

temp=*a;

*a=*b;

*b=temp;


printf("\nValues of a and b within the function: %d %d",*a,*b);


}


int main()

{

int a,b;


//Accept value of a & b

printf("\nEnter value of a:");

scanf("%d",&a);

printf("\nEnter value of b:");

scanf("%d",&b);


//print values before calling swap function

printf("\nValues of a and b before calling the function: %d %d",a,b);


//Calling swap function

swap(&a,&b);


//print values after calling the swap function

printf("\nValues of a and b after calling the function: %d %d",a,b);


}

sprintf() function | implementation | how to

sprintf() function | implementation | how to
c program sprintf() function:

This function is same as printf() function but it sends the formatted output to a string instead of screen.
So we can convert a variable data type into string using sprintf() function.

/*Program to illustrate the use of sprintf() function*/

#include
int main()
{
//declare two strings
char s1[20];
char s2[20];

//declare int and float variables

int n=7890;

float f=2345.67;
//convert the variables into string
sprintf(s1,"%d",n);
sprintf(s2,"%0.1f",f);
//print the converted strings
printf("s1=%s,s2=%s\n",s1,s2);

}

sscanf() function:c program

sscanf() function:c program
sscanf() function using string in c language
sscanf() function:c program

This function is same as scanf() function but it reads from string rather than standard input.

/*Program to illustrate the use of sscanf() function*/

#include
int main()
{
//declare two strings
char s1[20]="1234";
char s2[20]="345.67";
//declare int and float variables
int n;

float f;


//convert the variables into string

sscanf(s1,"%d",&n);

sscanf(s2,"%f",&f);

//print the converted strings

printf("Value of n=%d\nValue of f=%f\n",s1,s2);

}

Swap values of two variables using call by value | output | comments

Swap values of two variables using call by value | output | comments
Swap values of two variables using call by value | output | comments
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("\nValues of a and b within the function: %d %d",a,b);
}
int main()

{
int a,b;
//Accept value of a & b
printf("\nEnter value of a:");
scanf("%d",&a);
printf("\nEnter value of b:");
scanf("%d",&b);
//print values before calling swap function
printf("\nValues of a and b before calling the function: %d %d",a,b);
//Calling swap function
swap(a,b);
//print values after calling the swap function
printf("\nValues of a and b after calling the function: %d %d",a,b);
}

Random Access To File: rewind() using function

Random Access To File: rewind() using function
How to write C program code | Random Access To File: rewind() using function

The rewind function is used to move the position of file pointer to the beginning of file. The rewind() function is useful if we want to update a given file.

struct instrument

{

int id;

char name[30];

float price;

}instr;


int main()

{

int n,i;


FILE *fp;

fp=fopen("inst1.dat","wb+");


if(fp==NULL)

{

printf("Error in opening file\n");

return 0;

}


//Accepting number of records for writing

printf("How many records do you want?\n");

scanf("%d",&n);


printf("\n--------Writing in file using fwrite-----------\n\n");

//Writing records one by one in file

for(i=0;i
{
printf("Enter the details of instrument:\n");
printf("Enter Instrument Id :\n");
scanf("%d",&instr.id);
printf("Enter Instrument Name :\n");
scanf("%s",instr.name);
printf("Enter Instrument Price :\n");
scanf("%f",&instr.price);
printf("\n");

//for writing the entire record to the file
fwrite(&instr,sizeof(instr),1,fp);
}



printf("\n\n--------Usage of rewind()-----------\n\n");

//Moving file pointer to the begining of file
fseek(fp,0,0);
printf("Position pointer in the begining-> %ld\n",ftell(fp));

//Moving file pointer to the end of file
fseek(fp,0,2);
printf("Position pointer at the end of file-> %d\n",ftell(fp));

//Moving file pointer to the begining of file using rewind
rewind(fp);
printf("Position pointer after rewind -> %d\n",ftell(fp));


fclose(fp);

}

Passing Arguments to Function: Call by value & Call by Reference

Passing Arguments to Function: Call by value & Call by Reference
We can pass arguments to a function by following two ways:

1)Call by Value

2)Call by Reference


1) Call by Value:

In Call by Value, only the values taken by the arguments are sent to the function. In call by value any changes made to the formal arguments do not cause any change to the actual arguments.


2) Call by Reference:

In Call by Reference, only the addresses taken by the arguments are sent to the function. In call by reference any changes made to the formal arguments cause changes to the actual arguments.

Random Access To File: ftell() | fseek() function

Random Access To File: ftell() | fseek() function
Random Access To File: ftell()

2. ftell()

ftell() function returns the current position of the file pointer. It returns the value after counting from the beginning of the file.

Following program will make its functioning more clear:


/*Program to understand working of ftell() function*/

#include

struct instrument
{
int id;
char name[30];
float price;
}instr;

int main()
{
int n,i;

FILE *fp;
fp=fopen("inst1.dat","wb+");

if(fp==NULL)
{
printf("Error in opening file\n");
return 0;
}

//Accepting number of records for writing
printf("How many records do you want?\n");
scanf("%d",&n);

printf("\n--------Writing in file using fwrite-----------\n\n");
//Writing records one by one in file
for(i=0;i
{
printf("Enter the details of instrument:\n");
printf("Enter Instrument Id :\n");
scanf("%d",&instr.id);
printf("Enter Instrument Name :\n");
scanf("%s",instr.name);
printf("Enter Instrument Price :\n");
scanf("%f",&instr.price);
printf("\n");

//for writing the entire record to the file
fwrite(&instr,sizeof(instr),1,fp);
}



printf("\n\n--------Usage of ftell()-----------\n\n");

fseek(fp,0L,0);
printf("\nPosition of file pointer in the beginning->%d\n",ftell(fp));

while(fread(&instr,sizeof(instr),1,fp))
{
printf("\nPosition of file pointer ->%d\n",ftell(fp));
printf("%d\t",instr.id);
printf("%s\t",instr.name);
printf("%f\t",instr.price);
}

printf("\n Size of file in bytes is %d",ftell(fp));

fclose(fp);

}



Random Access To File: fseek() function

The data stored in the file can be accessed in two ways:

1)Sequentially

2)Randomly


Following functions are used for random access file processing:

-> fseek()

-> ftell()

-> rewind()


1) fseek()


The fseek() function is used to set the position of file pointer at the specified byte.

Declaration:

int fseek(FILE *fp, long displacement, int origin);

where,

fp – file pointer

displacement – it denotes the number of bytes which are skipped. If we want to displace backwards then its value is negative and if we want to displace forward the value is taken as positive.

origin – It is the relative position from where the displacement can take place. We can assign one of the following values to it:








/*Program to understand working of fseek() function*/


#include


struct instrument

{

int id;

char name[30];

float price;

}instr;


int main()

{

int n,i;


FILE *fp;

fp=fopen("inst1.dat","wb+");


if(fp==NULL)

{

printf("Error in opening file\n");

return 0;

}


//Accepting number of records for writing

printf("How many records do you want?\n");

scanf("%d",&n);


printf("\n--------Writing in file using fwrite-----------\n\n");

//Writing records one by one in file

for(i=0;i
{
printf("Enter the details of instrument:\n");
printf("Enter Instrument Id :\n");
scanf("%d",&instr.id);
printf("Enter Instrument Name :\n");
scanf("%s",instr.name);
printf("Enter Instrument Price :\n");
scanf("%f",&instr.price);
printf("\n");

//for writing the entire record to the file
fwrite(&instr,sizeof(instr),1,fp);
}


printf("\n\n--------Reading from file using fseek()-----------\n\n");
printf("Enter the record number to be read:");
scanf("%d",&n);

fseek(fp,(n-1)*sizeof(instr),0);
fread(&instr,sizeof(instr),1,fp);
printf("%d\t",instr.id);
printf("%s\t",instr.name);
printf("%f\t",instr.price);

fclose(fp);

}

Storage Classes in C: Static (static) | register | Auto

Storage Classes in C: Static (static) | register | Auto
 Storage Classes in C: Static (static)

how to write code for Storage Classes in C: Static (static)

3)Static:

There are two types of static variables:

(i) Local Static Variables

(ii)Global Static Variables


(i)Local Static Variables:

The scope of local static variable is same as that of an automatic variable.

The lifetime of a local static variable is more than that of the automatic variable. It is created at compile time and its life is till the end of program.

It is not created and destroyed each time the control enters a function or block.

It is created only once. It is not initialized every time the function is called.

If we do not initialize a static variable. The value taken by it is zero.

We can initialize them only by constants or expressions representing constants.



/* Program to understand the usage of local static variables*/

#include<stdio.h>

int main()

{

//Call update function 3 times to see its effect on static integers

update();

update();

update();

return 0;

}

int update()

{

static int z;

printf("\nThe value of z = %d",z);

z=z+10;

return 0;

}




Here we can see that we haven’t initialized the variable z but it is initialized automatically with value 0.

Also , the previous value of z is retained.


(ii)Global Static Variables:

When global variables are used, the static specifier doesn’t

extend the lifetime since they already have a lifetime which is equal to the lifetime of the program.

In this case, the static specifier is used to hide information.

If an external variable is static it can’t be used by other files of the program.



In above fig. the variable y is declared as static external variable, so we cannot use y in flies other than f1.c by putting the extern declaration in those files.


 Storage Classes in C: Auto (Automatic)

Storage Classes in C: Auto (Automatic) | output


A variable in addition to data type has an attribute which is its storage class.

If we will use storage class properly the program will become more efficient and faster.


The general syntax of a storage class is:

Storage_class data_type variable_name;


There are four types of storage classes:

1)Automatic

2)External

3)Static

4)Register


A storage class is responsible for the four aspects of a variable:

1)Lifetime:

Time between the creation and destruction of a variable.


2)Scope:

Scope means the locations where the variable is available for use


3)Initial Value:

Default value taken by an uninitialized variable


4)Place of Storage:

The place in memory which is allocated to store the variable in memory.


1)Automatic:

All the variables declared without any storage class specifier are called as automatic variables.


This can be also done using the keyword auto.

The uninitialized automatic variables have garbage values.

There scope is limited inside the block or function inside the block where they are declared and we can’t use them outside these blocks and functions.


Now let us understand them using following programs:


/*Program to understand the working of automatic variables*/

#include


void fun()

{

int n=30;

printf("\nInside Function........");

printf(" \n n= %d",n);

}


int main()

{

int n=5;


printf("Before calling Function........");

printf("\n n= %d",n);


fun();


printf("\nAfter calling Function........");

printf("\n n= %d",n);



}



This storage class can be applied only to local variables . The scope, lifetime and initial value of register variable are same as that of the automatic variables.


The difference between the automatic and register variable is their place of storage.

The automatic variables are stored in the memory while the register variables are stored in CPU Registers.


The main advantage of register variables is that they can be accessed much faster as that of the variables stored in the memory.

So the variables which are used frequently can be assigned register storage class. We can declare loop counters as register variables as they are frequently used.


Let us see their use in the following program:


/*Program to illustrate the use of register variables*/


#include


int main()

{

register int i;


int j;


printf("\nUsing register storage class.......:\n");

for(i=0;i<200;i++)

printf("%d\t",i);


}

Storage Classes in C: External (extern)

Storage Classes in C: External (extern)
Storage Classes in C: External (extern) | output

External:

Those variables that are needed by many functions and files can be declared using the external variables.

The uninitialized external variables are assigned zero as their initial value.

The keyword extern is used for declaring the variables as external.

Let us understand this concept in some more detail


Suppose we are having a multi-file program which is written in three files f1.c, f2.c and f3.c as shown below:





Here in file f1.c the variable x is defined and initialized with 8. This variable can be used in main() and fun1() but it can’t be accessed by other two files f2.c and f3.c

Suppose we want the second file f2.c to access the variable x so we need to do the following declarations as shown in the figure below:

Now the variable x can be accessed and modified in both the files f1.c and f2.c and if any alterations are there then they will be reflected in both the files.

So we have seen that the declaration of any variable using extern keyword will extend its scope.

Addition of matrix | 5*5 matrix addition

Addition of  matrix  | 5*5  matrix addition
Addition of 5*5 matrix

void main()

{

int a[5][5],i,j,row[5];

clrscr();


//Read Matrix

printf("\n-----Enter 5X5 matrix below:-------\n");

for(i=0;i<5;i++)

{

for(j=0;j<5;j++)

{

scanf("%d",&a[i][j]);

}

}


//Display Matrix

printf("\n\n----- The matrix you entered is:-------\n");

for(i=0;i<5;i++)

{

for(j=0;j<5;j++)

{

printf("%d\t",a[i][j]);

}

printf("\n");

}


//Perform column-wise Addition

printf("\nPerforming Calculations.........\n");

for(j=0;j<5;j++)


{ row[j]=0;


for(i=0;i<5;i++)

{

row[j]=row[j]+a[i][j];

}

}


//Display Result of column-wise calculation

printf("------The result of column-wise addition is:----\n");

for(i=0;i<5;i++)

{

printf("Column %d ",i+1);

printf("\t %d\n",row[i]);

}

getch();

}

even or odd using bitwise AND

even or odd using bitwise AND
/*Program to check whether a given number is even or odd using bitwise AND */
int main()
{
int n;
//mask having least significant bit 1 and other bits are 0
int msk=0x1;
//Accept any number
printf("Enter a number:\n");

scanf("%d",&n);


//A number will be odd if its least significant bit
//i.e the right most bit is 1
//A number will be even if its least significant bit is 0

if((n & msk) ==0)
{
printf("Number is even\n");

}

else
{
printf("Number is odd");
}
}

How to Write Program for file I/O using fread and fwrite

How to Write Program for file I/O using fread and fwrite
How to Write Program for file I/O using fread and fwrite

struct employee
{
int id;
int name[30];
float sal;
}emp;

int main()
{
int i,n;

FILE *fwptr,*frptr;

//open file for writing
fwptr=fopen("emp.dat","wb");

// checking if file exists or not
if(fwptr==NULL)
{
printf("File doesn't exist");
return 0;
}

//Accepting number of records for writing
printf("How many records do you want?\n");
scanf("%d",&n);

frequency of a given string within the string

frequency of a given string within the string
/*How To find the frequency of a given string within the string*/

#define MAXS 256

void main()

{

char s[MAXS],t[MAXS];

char *p;

int count=0;


// Accept string

printf("Enter some string:\n");

gets(s);


//Accept substring

printf("Enter search pattern:\n");

gets(t);


//Move pointer to the begining of string

p=s-1;


// Check for the substring and increment its occurence

while((p=strstr(p+1,t))!=NULL)

{

count++;

}

printf("Number of occurences=%d",count);

}

remove all the comments from a C

remove all the comments from a C
/*Program to remove all the comments from a C program*/

int main()

{

char c1,c2,src[30],dest[30];

FILE *fsrc,*fdest;

/*Accept names of source and destination files */

printf("Enter the names of source and destination files:\n");

scanf("%s %s",src,dest);

/*opening source file */

fsrc=fopen(src,"r");

if(fsrc==NULL)

{

printf("Source file cannot be opened");

return 0;

}


/*opening destination file */

fdest=fopen(dest,"w");


if(fdest==NULL)

{

printf("Destination file cannot be opened");

return 0;

}

while((c1=getc(fsrc))!=EOF)

{

/*earch begining of a comment by / and store in c1 */

if(c1=='/')

{

/*search b* and store in c2 */

if((c2=getc(fsrc))=='*')

{

while(1)

{

/*search for * */

if((c1=fgetc(fsrc))=='*')

{

/*search for / */

if((c1=fgetc(fsrc))=='/')

break;

}

}

}

else

{

putc(c1,fdest);

putc(c2,fdest);

}

}


else

{

putc(c1,fdest);

}

}


printf("Source file copied to destination after removing the comments.\n");


/*closing files*/

fclose(fsrc);

fclose(fdest);


return 0;

}

print the bit pattern of a 16 bit integer

print the bit pattern of a 16 bit integer
/* How to write Program for printing the bit pattern of a 16 bit integer with comments*/

//declaring function bit(int)

void bit(int);

void main()

{

int val;

printf("Enter the value of integer to print its bit pattern:\n");

scanf("%d",&val);



printf("The bit pattern for integer %d is\n",val);

//printing binary pattern requires the testing of each bit

//so we will test each bit starting from the 15th bit till we reach to left

//this will be achieved by bit(val) function

bit(val);

}

void bit(int n)

{

int i,m;



for(i=15;i<=0;i--)

{



//testing ith bit

//testing ith bit requires masking

//the masking is done through 1<

m=1<



if((n&m)==0)

{

printf("0");

}

else

{

printf("1");

}

}

}

swapping of of 2 integers using bitwise XOR operator

swapping of of 2 integers using bitwise XOR operator
swapping of of 2 integers using bitwise XOR operator.
/*Program to swap the values of 2 integers using bitwise XOR operator*/
#include
void main()
{
int value1, value2;
printf("Enter the values of two integers:\n");
scanf("%d %d",&value1,&value2);
printf("\n-----------Before Swapping-------------");
printf("\nBefore swapping the values of variables are:\n");
printf("Value1=%d \nValue2=%d",value1,value2);
value1= value1^value2;value2= value1^value2;value1= value1^value2;
printf("\n\n\n-----------After Swapping-------------");
printf("\nAfter swapping the values of variables are:\n");
printf("Value1=%d \nValue2=%d",value1,value2);
}
Bitwise XOR

perform I/O in a given file using Integer I/O

perform I/O in a given file using Integer I/O
 perform I/O in a given file using Integer I/O

/* Program to perform I/O in a given file using Integer I/O */


#include<stdio.h>

main()
{
//declaring pointer to file
FILE *fp;

int num;
char chr='\n';

printf("------------Writing in file:-----------------\n");
/* Writing in File*/

//Opening file for writing
fp=fopen("number.dat","wb");

//Checking file exists or not
if(fp==NULL)
{
printf("Error in opening file:\n");
return 0;
}

else

//If the file exists then writing numbers into it
{
printf("Writing numbers in File...");
for(num=1;num<=10;num++)
 {
putw(num,fp);
}
 printf("Done...");
 } //Closing the file
fclose(fp);
/* Reading in File*/
//Opening file for reading printf("\n\n------------Reading from file:-----------------\n");
 fp=fopen("number.dat","rb");
 if(fp==NULL)
 {
printf("Error in opening file:\n");
 return 0;
} //If the file exists then reading through it
 else
{
printf("Text found in the file is:\n");
while((num=getw(fp))!= EOF)
 printf("%d \n",num);
} //closing the file fclose(fp); }

perform I/O in a given file using Character I/O with comments

perform I/O in a given file using Character I/O with comments
 perform I/O in a given file using Character I/O
 /* Program to perform I/O in a given file using Character I/O */

#include<stdio.h>

main()
{
//declaring pointer to file
FILE *fp;

char chr;

printf("------------Writing in file:-----------------\n");
/* Writing in File*/

//Opening file for writing
fp=fopen("thought.txt","w");

//Checking file exists or not
if(fp==NULL)
{
printf("Error in opening file:\n");
return 0;
}

else

//If the file exists then writing into it character by character
{

printf("Enter text to be written in file:\n");
while((chr=getchar())!= EOF)
fputc(chr,fp);
}

//Closing the file
fclose(fp);


/* Reading in File*/
//Opening file for reading
printf("\n\n------------Reading from file:-----------------\n");
fp=fopen("thought.txt","r");

if(fp==NULL)
{
printf("Error in opening file:\n");
return 0;
}

//If the file exists then reading through it character by character
else
{

printf("Text found in the file is:\n");
while((chr=fgetc(fp))!= EOF)
printf("%c",chr);
}

//closing the file
fclose(fp);
}

Pyramid | Star pattern | for loop | source code

Pyramid | Star pattern | for loop  | source code
Pyramid | Star pattern | for loop  | source code 
* To print Pyramid Pattern shown below


        *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *

*/

#include<stdio.h>
int main()
{
int i,j,n;

printf("Enter no. of lines: ");
scanf( "%d",&n);


//for loop for number of lines
for(i=1;i<=n;i++)
{
//for loop for spaces
for(j=1;j<=n-i;j++)
{
printf(" ");
} //for loop for stars in first half
for(j=1;j<=i;j++)
{
printf("* ");
} //for loop for stars in second half
for(j=1;j<i;j++)
{
printf("* ");
} printf("\n");
}
return 0;
}

Monday 23 July 2012

Sunday 22 July 2012

Difference between malloc() and calloc() | Dynamic Memory Allocation

Difference between malloc() and calloc() | Dynamic Memory Allocation
What is Difference between malloc() and calloc()

malloc():

Declaration:
void * malloc(size_t size);

It is used to allocate memory dynamically. The argument size is used to specify the number of bytes to be allocated.
The type size_t is defined in stdlib.h as unsigned int.

If malloc() is successful , it returns pointer to the first byte of allocated memory. It returns void pointer which can be cast to any type of pointer.

It is used as:
ptr=(datatype *) malloc (specified size);

So the ptr is of type datatype . (datatype *) is used to typecast the pointer returned.


calloc():
Declaration:
Void *calloc(size_t n,size_t size);

The calloc() function is used to allocating multiple blocks of memory. It is similar to malloc() but there are 2 differences:
1) calloc() takes two arguments. The first arguments specifies the number of blocks and the second argument specifies the size of each block.

2)The memory allocated my malloc() contains garbage value whereas the memory allocated by calloc() is initialized to zero.
But the initialization done by calloc() is not reliable. So it is advised to explicitly do the initialization.


/* Program to understand the use of malloc and calloc*/

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

int main()
{

int *ptr1,*ptr2,i;

//Allocating memory using calloc
ptr1=(int *) calloc(5,sizeof(int));

//Allocating memory using malloc
ptr2=(int *) malloc(5*sizeof(int));



printf(" \n----------Using calloc:-------------\n");

//Check if memory is available

if(ptr1==NULL)
{
printf("Out of memory." );
return 0;
}

//Accept the integers for calloc
for(i=0;i<5;i++)
{
 printf("Enter an integer:");
scanf("%d",ptr1+i);
 } //display the integers for calloc
 printf("The integers entered by you are:");
 for(i=0;i<5;i++)
{
 printf("%d\t",*(ptr1+i));
}
printf("\n\n\n----------Using Malloc:-------------\n"); //Check if memory is available
if(ptr2==NULL)
{
 printf("Out of memory." );
 return 0;
} //Accept the integers for malloc
 for(i=0;i<5;i++)
 {
printf("Enter an integer:");
 scanf("%d",ptr2+i);
} //display the integers for malloc
 printf("The integers entered by you are:");
 for(i=0;i<5;i++)
 {
 printf("%d\t",*(ptr2+i));
}
 return 0;
 }

UNDERSTANDING THE USE OF realloc() FUNCTION

UNDERSTANDING THE USE OF realloc() FUNCTION
UNDERSTANDING THE USE OF realloc() FUNCTION
realloc():
Declaration:
void *realloc(void *ptr, size_t newsize);
It is used for reallocation of memory. If we want to increase or decrease the memory that have already been allocated by malloc() or calloc().

The memory size is altered without any loss of old data.

It takes two arguments:
1)The first argument is the pointer to the memory block that was already allocated by malloc() and calloc().
2)The second argument is the new size of the block.


Let us understand it with the help of program:
* Program to understand the use of realloc()*/

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

int main()
{

int *ptr,i;


//Allocating memory using malloc
ptr=(int *) malloc(5*sizeof(int));



printf(" \n----------Using malloc:-------------\n");

//Check if memory is available

if(ptr==NULL)
{
printf("Out of memory." );
return 0;
}

//Accept the integers with size using malloc
printf("Enter 5 integers:\n");
for(i=0;i<5;i++)
 {
scanf("%d",ptr+i);
 }
 printf("The integers entered are:\n");
for(i=0;i<5;i++)
 {
printf("%d\t",*(ptr+i));
}
printf(" \n\n\n----------Using realloc:-------------\n");
 //Allocating size for 4 more integers using realloc
 ptr=(int *) realloc(ptr,9*sizeof(int)); //Check if memory is available
if(ptr==NULL)
 {
 printf("Out of memory." );
 return 0;
}
 //Accept the new data
printf("Enter 4 more integers:\n");
for(i=5;i<9;i++)
{ scanf("%d",ptr+i);
} //display the integers with size using calloc
 printf("The integers entered are:\n");
 for(i=0;i<9;i++)
 {
printf("%d\t",*(ptr+i));
} return 0;
 }

Unformatted Input functions: getch() | getche() | getchar() | fgetchar()

Unformatted Input functions: getch() | getche() | getchar() | fgetchar()
 Unformatted I/O functions : getch() , getche() , getchar() , fgetchar()
#include<stdio.h>
#include<conio.h>

int main()
{

char ch;

printf("\n(using getch) Press any key to continue..");

//character will not be echoed by getch()
getch();

printf("\n(Using getche())Press any key to echo..." );
//character will be echoed by getch()
ch=getche();

printf("\n (Using getchar())Type any character:");
getchar();//macro present in conoio.h

printf("\n(Using fgetchar()) Type another character:(Y/N)");
fgetchar(); //function present in conio.h


return 0;
}

Unformatted Output functions in c

Unformatted Output functions in c
/*How to write Program to illustrate unformatted Output: putch(), putchar(), fputchar()*/

putch(), putchar(), fputchar() all are used to output one character at a time.

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

int main()
{

char ch='z';

printf("\nBy using putch:");
putch(ch);

printf("\nBy using putchar:");
putchar(ch);

printf("\nBy using fputchar:");
fputchar(ch);

return 0;


}

Difference between functions and macro

Difference between functions and macro
We should not leave a space between the macro template and its argument in the macro definition.
#define SQUARE (x) (x*x)
int main()
{
int n,m;
printf("Enter the number to find the square:");
scanf("%d",&n);

m=SQUARE(n);

printf("Square of %d is %d",n, m);
}

The above program won’t run. It wouldn’t find the template for above call.
So be cautious of such mistakes.

Now let’s see the differences between macros and functions

Difference between Macros and Functions


1) In a macro call the macro template is replaced by the preprocessor with its macro expansion.
Whereas when a function is called the control is passed to the function along with its arguments and after performing operations on it the result is returned back.

2) If we make use of macros the program runs faster but the size of program increases.
Functions make the program smaller and compact.

3) If we want to make use of less memory space then we should use functions.
If we want our program to run faster we should use macros.

importance of enclosing macro expansion wihtin parentheses

importance of enclosing macro expansion wihtin parentheses

 importance of enclosing macro expansion wihtin parentheses

/* Program to illustrate the importance of enclosing macro expansion wihtin parentheses */

If we fail to enclose the entire macro expansion in the parentheses then we may get some unexpected results.

Consider the following program:

#include<stdio.h>
#define SQUARE(x) x*x //Macro definition without parentheses

int main()
{
int i;
i=27/SQUARE(3);
printf("%d",i);
return 0;
}

Here we expected that the output would be 3.

Lets see the actual output:
Shocked, the reason is that the above macro is expanded as:

i=27/3*3;
Following the associativity rule (left to right) first 27/3 is solved which gives 9.
i.e. i=9*3;
So we get the out put as 27 not 3.


So how to write the macro for getting the correct out put.
Following program will illustrate you this thing.

#include<stdio.h>
#define SQUARE(x) (x*x) //Macro definition with parentheses

int main()
{
int i;

i=27/SQUARE(3);
printf("%d",i);
return 0;
}

Array Initialization with different storage classes

Array Initialization with different storage classes
Array Initialization
Following are the examples that demonstrate this:
1) int n[4]={1,2,3,4};
2) int num[]={1,2,3,4};

If we do not specify the values of array elements they contain garbage values.

If we initialize the array where it is declared than it is optional to specify the dimension. As shown in second example above.

By default storage class of an array is auto. And if we do not initialize the array garbage value is taken.

If the storage class of an array is declared to be static, then all the array elements have default initial value as zero.

Let us understand the above by using an example:

/* Program for understanding the initialization of arrays*/

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

void main()
{
int i;

//int x[];
//if we will uncomment the above declaration then it will cause an error
//because if we don't initialize the array at the time of declaration
//then we must specify its dimension

int y[]={1,2,3,4};
int marks[4];//Declaration of array
static int star[4];
printf("\n \nBy default value assigned to an array with storage class auto:");
for(i=0;i<4;i++) 
printf("\n marks[%d] is %d",i,marks[i]); //reading stored data from array 
printf("\n\n By default value assigned to an array with storage class static:");
for(i=0;i<4;i++)
{
printf("\n star[%d] is %d",i,star[i]); 
}
printf("\n\n Accessing elements of array(i.e. array y declared without specifying the dimension");
for(i=0;i<4;i++)
{
printf("\n y[%d] is %d",i,y[i]);

}

Bound Checking of an Array in C

Bound Checking of an Array in C
Bound Checking of an Array in C

In C there is no check to see whether the bounds of an array exceeds the size of the array.
We know that array elements are placed in contiguous memory locations.
If data is entered having a subscript exceeding array size then it is placed in memory outside the array.
This may lead to unpredictable results.
There are no error or warning messages to warn that we are exceeding the array size.
We can use the following program to see what happens when array bounds exceed the array size:

/* Program for understanding the bounds of an array*/

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

void main()
{
int i,num[2];

//Assigning values to array elements beyond its size
for (i=0;i<10;i++)
 {
 num[i]=i; 
} //Printing the value assigned to the array
 for(i=0;i<10;i++)
printf("num[%d]= %d" ,i,num[i]);
 }
 }

ARRAYS: Introduction, working and advantages

ARRAYS: Introduction, working and advantages
ARRAYS: Introduction, working and advantages

Definition:
An array is a set of similar data types.

E.g. int marks[6];

--> In the above statement int is a data type of variable and marks is the name of the variable.

-->We can have 6 elements which are marks[0], marks[1], marks[2], marks[3], marks[4], marks[5].

-->So the subscript in bracket will take values from 0 to 5 and not 1 to 6.

--> [6] tells that there will be 6 elements of type int in our array.

--> This number is called the dimension of the array.

Consider the following program

/* Program for accepting marks of six subjects and calculating the average using array*/
#include<stdio.h>
#include<conio.h>


void main()
{
int avg, sum=0,i;
int marks[6];//Declaration of array

//Accept marks of six subjects
printf("Enter marks of six subjects:");

for(i=0;i<6;i++)
{
scanf("%d",&marks[i]); //storing data in array
}
for(i=0;i<6;i++) 
{
sum=sum + marks[i]; //reading stored data from array 
avg=sum/6; //calculate average
printf("Average Marks:=%d",avg);
}

-->Once an array is declared the individual elements are referred with the help of subscript.
-->Subscript is the number in the bracket.
-->The subscript specifies the position of element in the array
-->All array elements are numbered starting from 0

E.g. marks[2]
-->Here, the subscript is 2 i.e the number in bracket
-->Marks[2] refers to the 3rd element and not the second element

--> So in the above program and with above input values
i.e. 90 80 90 80 90 95

marks[0]=90
marks[1]=80
marks[2]=90
marks[3]=80
marks[4]=90
marks[5]=95

-->This ability of using variables by using subscripts is what makes an array useful
-->Ordinary variables can hold only one value at a time
-->Suppose if we would have done the above program without using an array this would have been something like shown below:

/* Program for accepting marks of six subjects and calculating the average without using array*/

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

void main()
{
int avg, sum=0,i;
int marks1,marks2,marks3,marks4,marks5,marks6;
//Accept marks of six subjects
printf("Enter marks of six subjects:");
scanf("%d %d %d %d %d %d",&marks1,&marks2,&marks3,&marks4,&marks5,&marks6);

sum=marks1 + marks2 + marks3 + marks4 + marks5 + marks6;
avg=sum/6;

printf("Average Marks:=%d",avg);
}
-->We can see in the previous version of the program we were handling only one variable that was an array variable
-->So handling array is much easier, it is clear from the programs that we have seen

-->So an array is a name given to group of ‘similar quantities’.
-->The importance of quantities being similar is that we can refer to them by its position in the group.
-->Array elements are stored at contiguous memory locations.

Comparing two strings using pointers

Comparing two strings using pointers

How to write Program for comparing two strings using pointers*/
//function for comparing two strings
int pstrcmp(const char *str1,const char *str2)
{
while(*str1!='\0'&&*str2!='\0'&&*str1==*str2)
{
str1++;
str2++;
}
//value returned when strings are of equal length
if(*str1==*str2)
return 0;
else
//value returned when strings are not of equal length
return(*str1-*str2);
}

//main function
main()
{
char str1[100],str2[100];
int n;
clrscr();

//accept two strings from user
printf("Enter some string:");
gets(str1);
printf("Enter second string:");
gets(str2);

//store the value returned by pstrcmp function in n
n=pstrcmp(str1,str2);
//decide which string is greater depending upon its value of n
if(n>0)
printf("First string is greater");
else if(n<0)
printf("Second string is greater");
else
printf("Both the strings are equal");
getch();
}

How to print table of 1st 10 natural numbers

How to print table of 1st 10 natural numbers

 How to print table of 1st 10 natural numbers

/*Program to print table of 1st 10 natural numbers*/
#include<stdio.h>
#include<conio.h>

//main function

void main ()
{
int i,j;
clrscr();

//first for loop for incrementing number
for(i=1;i<11;i++)
{ //second for loop for printing the table of individual number
for(j=1;j<11;j++)
printf("%4d",i*j);
printf("\n");
}
getch();
}

How to read a file and display it in c

How to read a file and display it in c

 How to read a file and display it in c

/*Program to read a file and display it*/

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

void main()
{
FILE *fp;
int ch;
char fname[32];
clrscr();

//Accept file name
printf("Enter File name:\n");
scanf("%s",fname);

//open file
fp=fopen(fname,"r");
if(fp==NULL)
{
printf("ERROR:File cannot open");
getch();
return;
}

//display file till end
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
getch();
}

Add and display record using structures and file

Add and display record using structures and file

How to add and display record using structures and file (fprintf) 

/*Program to add and display record using structures and file*/

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

//structure for person
struct person
{
char name[30];
unsigned long pn;
};

//main function
int main()
{
int choice;
FILE *fp;
struct person p;
clrscr();

//open file in append mode
fp=fopen("person.txt","a+");
if(fp==NULL)
{
printf("FILE CAN'T OPEN.\n");
exit(1);
}

//menu
while(1)
{
printf("\n1.Add Record\n");
printf("2.Display Records\n");
printf("3.EXIT\n");
printf("Enter your choice...\n");
scanf("%d",&choice);


switch(choice)
{

//Add Record in file
case 1:printf("Enter name & Phone number\n");
scanf("\n\n %s %lu",p.name,&p.pn);
fprintf(fp,"%s %pn \n" ,p.name,p.pn);
break;

//Display records from begining
case 2:fseek(fp,0,SEEK_SET);
while(fscanf(fp,"%s %lu",p.name,&p.pn)!=EOF)
printf("\n\n %s %lu \n",p.name,p.pn);
break;

//exit
case 3:exit(1);
default:printf("UNKNOWN CHOICE\n");
}
}

//close file
fclose(fp);
}

 

Programming language basics

Programming  language basics
Programs means what we  understand?
it  shows like programming language .
programming language shows programs which include ..
examples  of c language , c++ programming  ,examples of  java
programming language , asp.net with c# and VB .
next is old language that is perl .
we can also consider php is programming language.
Now comes to the next part of programming language that id database
database  which includes oracle , sql server , and many more also
Ms-access.
to learn any of programming  language we have to know about basics
of  programming language . whether that is c language or java.
to get idea about more about programming language check with simple
programs in given language i.e  prime number  examples  , perfect
number examples   , armstrong number and database connection  with examples.
to understand each program do execution line by line.and next and
last think  is to execute particular program in given respective tool.
like if you want to execute Asp.net  you should have idea about
visual studio.to understand more details go to tutorials .