Showing posts with label Unit-4. Show all posts
Showing posts with label Unit-4. Show all posts

Friday, November 21, 2014

4.4 ENUMERATED DATA TYPES


§  enum is “Enumerated Data type”.

§  enum is user-defined data type.

§  Syntax:

enum identifier (Value1, Value2, Value3,……Valuen};

o   In the above syntax, “identifier” is a user-defined data type.

o   Value1,Value2,…. are the set of enum values (called Enumerated Constants)

o   Using “identifier” we are creating our variables.

§  After this definition, we can declare variables to be of this “new” type.

        enum identifier v1,v2,….vn;

o   The enumerated variables can only have one of the values Value1,Value2,…

o   Default numeric value assigned to first enum value is 0.

o   Generally printing value of enum variable is as good as printing “Integer”.

 


 

4.3 UNION


A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

 

Defining a Union

To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program.

 

The general format of the union statement is as follows:

               union union_tag

               {

                               member definition;

                               member definition;

                               ...

                               member definition;

               } [one or more union variables]; 

 

§  Each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition.

§  At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional.

e.g.

               union Data

               {

                               int i;

                               float f;

                               char  str[20];

               } data; 

 

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.

 

The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string.

 

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type.

 


 

Thursday, November 20, 2014

4.2 STRUCTURES

A structure gathers together, different atoms of information that comprise a given entity.

 

Sample example:

struct book

{

char title[10];

int pages;

float price;

};

 

The general format of a structure definition is as follows:

struct tag_name

{

datatype member1;

datatype member 2;



};

 

In defining, a structure you may note the following syntax:

1.      The template is terminated with a semicolon.

2.      While the entire definition is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template.

 

Difference between array and structures

ARRAY
STRUCTURE
An array is a collection of related data elements of same type.
A structure can have elements of different types.
An array is a derived data type.
A structure is a user-define data type.
An array behaves like a built-in data type i.e. we declare an array variable and use it.
In case of structure, first we have to design and declare a data structure before the variables of that type are declared and used.

 

Declaring Structure Variables

After defining a structure format we can declare variables of that type.

General format
Sample Code
struct tag_name
{
datatype member1;
datatype member 2;
}var1,var2;
 
struct book
{
char title[10];
int pages;
float price;
}b1,b2;
 
struct tag_name
{
datatype member1;
datatype member 2;
};
struct tag_name var1,var2;
 
struct student
{
char name[10];
int rollno;
};
struct student s;
 

 

Accessing Structure members

We can access the members of a structure using a dot(.) operator.

e.g.

strcpy(b1.title,”BASIC”);

b1.pages=360;

b1.price=172.00;

 

How Structure Elements are stored

The elements of a structure are always stored in contiguous memory locations.

Sample code:

struct book

{

char title[10];

int pages;

float price;

};

struct book b1={“BASIC”,360,172.00};

 


Copying of Structures

The values of a structure variable can be assigned to another structure variable of the same type using the assignment operator.

 

/* Program to demonstrate copying of structures */

#include<stdio.h>

#include<conio.h>

void main()

{

  struct employee

  {

     char name[10];

     int age;

     float salary;

  };

  struct employee e1={"Arnav",28,40000.00};

  struct employee e2,e3;

  clrscr();

  /* Copying one by one */

  strcpy(e2.name,e1.name);

  e2.age=e1.age;

  e2.salary=e1.salary;

  /* Copying all elements at one go */

  e3=e2;

  printf("\n%s\t%d\t%f",e1.name,e1.age,e1.salary);

  printf("\n%s\t%d\t%f",e2.name,e2.age,e2.salary);

  printf("\n%s\t%d\t%f",e3.name,e3.age,e3.salary);

  getch();

}

 

NOTE: This copying of all structure elements at one go has been possible only because the structure elements are stored in contiguous memory locations.

 

Nesting of Structures

One structure can be nested within another structure. Using this facility complex data types can be created.

 

/* Program to demonstrate nesting of structures */

#include<stdio.h>

#include<conio.h>

void main()

{

  struct employee

  {

     char name[10];

     struct address

     {

       char phone[10];

       char city[10];

       int pin;

     }a;

  };

  struct employee e={"Arnav","6234560016","Dallas",4210};

  clrscr();

  printf("\nName-->%s\nPhone-->%s",e.name,e.a.phone);

  printf("\nCity-->%s\nPincode-->%d",e.a.city,e.a.pin);

  getch();

}

 

Array of Structures

An array is a collection of similar data types. Similarly, we can also define an array of structures. This means that the structure variable would be an array of objects, each of which contains the member elements declared within the structure construct.

 

/* Program to demonstrate array of structures */

#include<stdio.h>

#include<conio.h>

void main()

{

  struct marks

  {

    int sub1;

    int sub2;

    int sub3;

  }s[5];

  int i;

  clrscr();

  printf("Enter the marks of students:\n");

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

  {

    printf("\nEnter marks of Student-%d:",i+1);

    scanf("%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3);

  }

  printf("\n\n Marks of students:\n");

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

  {

    printf("\nStudent-%d:",i+1);

    printf("%d\t%d\t%d",s[i].sub1,s[i].sub2,s[i].sub3);

  }

  getch();

}

 

Passing Structures as arguments in Functions

Like an ordinary variable, a structure variable can also be passed to a function. We may either pass individual structure elements or the entire structure variable at one go.

 

/* Program to demonstrate passing structures to functions */

#include<stdio.h>

#include<conio.h>

#include<string.h>

  struct record

  {

    char name[10];

    int rollno;

    float percent;

  }r;

void display(struct record r);

void main()

{

  clrscr();

  strcpy(r.name,"Arnav");

  r.rollno=20;

  r.percent=92.0;

  display(r); 

  getch();

}

void display(struct record r)

{

  printf("\nSTUDENT RECORD");

  printf("\nName:");

  puts(r.name);

  printf("Roll#:%d",r.rollno);

  printf("\nPercentage:%f",r.percent);

}

 

Tuesday, November 11, 2014

4.1.7 DYNAMIC ARRAYS

NOTE: the process of allocating memory at compile time is known as static memory allocation and the arrays that receive static memory allocation are called static arrays.

 

In C, it is possible to allocate memory to arrays at run time. This feature is known as dynamic memory allocation and the arrays created at run time are called dynamic arrays.

 

Dynamic arrays are created using pointer variables and memory management functions like malloc(), calloc(), realloc(). These functions are included in the header file <stdlib.h>. The concept of dynamic arrays is used in creating and manipulating data structures as linked lists, stacks and queues.

 

4.1.6 MULTIDIMENSIONAL ARRAY

The general form of a multi-dimensional array is:

            type   array_name[s1][s2][s3]…[sn];

                        where si is the size of the ith dimension.

e.g.      int survey[3][5][2];

            float table[5][4][5][3];

 

4.1.5 CHARACTER ARRAYS / STRINGS


A string is a sequence of characters that is treated as a single data item.

 

Declaring and Initializing String Variables

·         C does not support strings as a data type.

·         C, however, allows us to represent strings as character arrays.

 

General form:

   char string_name[size];

 

The ‘size’ determines the number of characters in the string_name.

e.g. char city[10];

        char name[30];

 

when the compiler assigns a character string to a character array, it automatically supplies a null character(\’0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one.

 

Initialization

     char city[9] = “NEW YORK”;

     char city[9] = {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};

 

·         C also permits us to initialize a character array without specifying the number of elements. In such cases, the size of the array will be determined automatically, based on the number of elements initialized.

e.g.  char city[ ] = {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};

 

·         We can also declare the size much larger than the string size in the initialize.

e.g. char str[10] = “GOOD”;

 

G
O
O
D
\0
\0
\0
\0
\0
\0

 

 

Reading Strings from Terminal

1.      Using scanf() Function

char address[10];

scanf(“%s”,address);

            Here, scanf() is used with %s format specification to read a string of characters.

           

NOTE: that unlike previous scanf calls, in the case of character arrays, the ampersand (&) is not required before the variable name.

·         The problem with the scanf( ) function is that it terminates its input on the first white space it finds.


Reading a Line of Text
C supports a format specification known as the edit set conversion code%[ ] that can be used to read a line containing a variety of characters, including whitespaces.
e.g.    char line[80];
          scanf(“%[\n]”,line);
          printf(“%s”, line);
The above program segment reads a line of input from the keyboard and display the same on the screen.
 

 

 

 

 


2.      Using getchar() and gets() Functions

a.      getchar()

This function is used to repeatedly read successive single characters from the input and place them into a character array.

            An entire line of text can be read and stored in an array. The reading is terminated when the newline character(‘\n’) is entered and the null character is then inserted at the end of the string.

General format:

               char ch;

   ch = getchar();

                       

                        Code Segment:

                                    char line[80],ch;

                                    int c = 0;

                                    printf(“Enter text:”);

                                    do

                                    {

                                                ch=getchar();

                                                line[c] = ch;

                                                c++;

                                    } while(ch !=’\n’);

 

b.      gets()

This function is available in the <stdio.h> header file.

General format:

               gets(str);

   where str is a string name.

This function reads characters into the character array from the keyboard until a new-line character is encountered and then adds a null character to the string.

                       

                        Code Segment:

                                    char line[80];

                                    gets(line);

 

Writing Strings to Screen

1.      Using printf() Function

The format %s can be used to display an array of characters that is terminated by the null character.

                        printf(“%s”,name);

 

2.      Using putchar() and puts() Functions

a.      putchar()

C supports another character handling function putchar() to output the values of character variables. It takes the following form:

            char ch = ‘A’;

            putchar(ch);

 

Code Segment:

                                    char name[6] = “ARNAV’;

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

                                          putchar(name[i]);

 

b.      puts()

The function puts() is defined in the header file <stdio.h>.

General format:

               puts(str);

   where str is a string name.

                       

                        Code Segment:

                                    char line[80];

                                    gets(line);

                                    puts(line);

 

All the string handling functions are prototyped in:

#include <string.h>

 
The common functions are described below:

1.      strcpy

This library function is used to copy a string and can be used like this:

strcpy(destination, source)

 (It is not possible in C to do this: string1 = string2).

Take a look at the following example:

 
               str_one = "abc";
               str_two = "def";
               strcpy(str_one , str_two); // str_one becomes "def"

Note: strcpy() will not perform any boundary checking, and thus there is a risk of overrunning the strings.

2.      strcmp

This library function is used to compare two strings and can be used like this:

strcmp(str1, str2)

  • If the first string is greater than the second string a number greater than null is returned.
  • If the first string is less than the second string a number less than null is returned.
  • If the first and the second string are equal a null is returned.

Take look at an example:

               printf("Enter you name: ");
               scanf("%s", name);
               if( strcmp( name, "jane" ) == 0 )
                               printf("Hello, jane!\n");
 
Note: strcmp() will not perform any boundary checking, and thus there is a risk of overrunning the string.

 


3.      strcat

This library function concatenates a string onto the end of the other string. The result is returned. Take a look at the example:

               printf("Enter you age: ");
               scanf("%s", age);
               result = strcat( age, " years old." ) == 0 )
               printf("You are %s\n", result);
 
Note: strcat() will not perform any boundary checking, and thus there is a risk of overrunning the strings.

 

4.      strlen

This library function returns the length of a string. (All characters before the null termination.) Take a look at the example:

 
               name = "jane";
               result = strlen(name); //Will return size of four.