Objective-C: Structures

Structure is a user defined data type which is used to store different type of data together under a unique name.

Declaring Structure   

  • A structure is declared using keyword struct.
    • The variables of structure are declared within curly braces and are called   data members of the structure.
    • A structure is always terminated with a semicolon.
      • A structure can have one or many variable that may be given at the time of declaration or further in the program.
      • The members of structure are accessed via dot operator ‘.’.

 

  Syntax1: Without declaring variable of structure

 struct structure_name

{

    data-type var1;

    data-type var2;

    ………;

    data-type varn;

};

 

struct structure_name s1,s2,..;

 

   Syntax2: Declaring with variables

struct structure_name

{

    data-type var1;

    data-type var2;

    ……;

    data-type varn;

}s1,s2,…;

Program 

 

Explanation

  • A structure student is declared with two data members, name and age.
  • Variable of the structure is declared as s.
  • The data members of structure student are initialized using ‘.’ Operator.

Structure within Structure

A structure can also be defined in another structure and is called nesting of structure.

 

Program

  #import <Foundation/Foundation.h>

 int main (int argc, const char *argv[]){

struct student

{

    char* name;

 

   struct marks

   {

    float mark;

    char* subject;

      }mrk; 

   

    }s;   

   

         NSLog(@“Enter Name of the student : ”);

         Scanf(“%s”,&s.name);

         NSLog(@“Enter Subject : ”);

         Scanf(“%s”,&s.mrk.subject);

         NSLog(@“Enter Marks obtained : ”);

         Scanf(“%f”,&s.mrk.mark);

 

      

   NSLog(@“\tRecord of student”);

 

         NSLog(@“NAME   :%s”,s.name);

         NSLog(@“Subject:%s”,s.mrk.subject);

         NSLog(@“Marks  : %f”,s.mrk.mark);

     

 return 0;

}

Output:

Enter Name of the student: Alice

Enter Subject : Computers

Enter Marks obtained: 86

      Record of student

NAME   : Alice

Subject: Computers

Marks  : 86