Lesson 4-Structure Part2
Lesson 4-Structure Part2
The structures
Part 2
Presented by:
Dr. Imane NEDJAR
Part 2
Structures and Pointers
2
Structures Pointers
Creating a Structure
struct Student{
char name[20] ;
char first_name[20] ;
};
8
Structures Pointers & String
Accessing the Structure's Elements
#include<stdio.h>
#include<string.h>
struct Student{
char name[20] ; Name isYoubi
char first_name[20] ;}; First name is Mohamed
int main() {
struct Student e,*p;
p=&e;
strcpy (p->name, "Youbi" );
strcpy (p-> first_name, "Mohamed" );
printf("Name is %s \n", p-> name);
printf("First name first name is%s \n", p-> first_name);
return 0;} 9
Structures Pointers & String
Reading a Structure
#include<stdio.h>
#include<string.h>
struct Student{
char name[20] ;
char first_name[20] ;}; Name is Youbi
int main() { First name is Mohamed
struct Student e,*p;
p=&e;
printf("Provide the name\n");
gets(p->name);
printf("Provide the first name\n");
gets(p->first_name);
printf("Name is %s \n",p->name);
printf("First name is %s \n", p->first_name);
return 0;} 10
Structures Pointers
Arrays
struct Student{
char name[20] ;
float score[3]; };
11
Structures Pointers & Array
Accessing the Structure's Elements
#include<stdio.h>
#include<string.h>
struct Student{
char name[20] ;
float score[3]; };
int main() { int i;
Name is Youbi
struct Student e,*p; Score1=10.00
p=&e; Score 2=15.00
strcpy (p->name, "Youbi" );
p->score[0]=10;
Score 3=0.00
p-> score[1]=15;
p-> score[3]=8;
printf("Name is %s\n", p->name);
for(i=0;i<3;i++)
printf("Score %d=%d \n",i+1, p-> score[i]);
12
return 0;}
Structures Pointers & Array
#include<stdio.h> Reading a Structure
#include<string.h>
struct Student{ Provide the name
char name[20] ; Youbi
float score[3]; };
int main() { int i;
Provide the scores
struct Student e,*p; 10
p=&e; 2
printf("Provide the name\n"); 15
gets(p->name); Name is Youbi
printf("Provide the scores\n"); Score 1=10.00
for(i=0;i<3;i++)
scanf("%f",&p->score [i]);
Score 2=2.00
printf("Name is %s\n", p->name); Score 3=15.00
for(i=0;i<3;i++)
printf("Score %d=%.2f \n",i+1, p-> score[i]);
13
return 0;}