Monday, 20 April 2015

Basic Structure Usage in C

the simple code to use structure is

#include stdio.h
#include conio.h

struct person{
char name[15];
int age;
};//please note the semicolon

void main(){
struct person p1; /* struct person --> datatype
p1 --> variable name */
printf("enter the name of person : ");
scanf("%s",&p1.name);/* please note the & sign
i don't know why we have include that & sign for string*/

printf("enter the age of %s",p1.name);
scanf("%d",&p1.age);

printf("the age of %s is %d",p1.name,p1.age);

getch();// to hold the display
}//end of main



we can avoid struct in the datatype declaration using typedef

using typedef we can rewrite the above code as following

#include stdio.h
#include conio.h

typedef struct{
char name[15];
int age;
}person; /* please note the variable name
typedef struct --> datatype
person --> variable name */
void main(){

person p1;

printf("please enter the name of person");
scanf("%s",&p1.name);
printf("enter the age of %s",p1.name);
scanf("%d",&p1.age);

printf("the age of %s is %d",p1.name,p1.age);
getch();//to hold the display
}//end of main


and the output of both is same
strings

No comments:

Post a Comment