Sunday, May 19, 2019

Enumerations


An enum is a keyword, it is an user defined data type. All properties of integer are applied on Enumeration data type so size of the enumerator data type is 2 byte. It work like the Integer.
It is used for creating an user defined data type of integer. Using enum we can create sequence of integer constant value.

Syntax

enum tagname {value1, value2, value3,....};
  • In above syntax enum is a keyword. It is a user defiend data type.
  • In above syntax tagname is our own variable. tagname is any variable name.
  • value1, value2, value3,.... are create set of enum values.
enumeration in c
It is start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the list. If constant one value is not initialized then by default sequence will be start from zero and next to generated value should be previous constant value one.

Read carefully

Example of Enumeration in C

enum week {sun, mon, tue, wed, thu, fri, sat};
enum week today;
  • In above code first line is create user defined data type called week.
  • week variable have 7 value which is inside { } braces.
  • today variable is declare as week type which can be initialize any data or value among 7 (sun, mon,....).

Example of Enumeration in C

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

enum ABC {x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf("Sum: %d",a);
getch();
}

Output

Sum: 3

Example of Enumeration in C

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

enum week {sun, mon, tue, wed, thu, fri, sat};
void main()
{
 enum week today;
 today=tue;
 printf("%d day",today+1); 
 getch();
}

Output

3 day
Here "enum week" is user defined data type and today is integer type variable which initialize Tuesday. In above code we add "today+1" because enum is start from 0, so to get proper answer we add "1". Other wise it give "2nd day".

Example of Enumeration in C

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

enum week {sun, mon, tue, wed, thu, fri, sat};
void main()
{
for(i=sun; i<=sat; i++)
{
 printf("%d ",i); 
} 
getch();
}

Output

1 2 3 4 5 6 7
In above code replace sun, mon, tue,.... with Equivalent numeric value 0, 1, 2,...

Structure and Union

Structure is a user defined data type which hold or store heterogeneous data item or element in a singe variable. It is a Combination of primitive and derived data type.




Why Use Structure in C

In C language array is also a user defined data type but array hold or store only similar type of data, If we want to store different-different type of data in then we need to defined separate variable for each type of data.
Example: Suppose we want to store Student record, then we need to store....
  • Student Name
  • Roll number
  • Class
  • Address
For store Student name and Address we need character data type, for Roll number and class we need integer data type.
If we are using Array then we need to defined separate variable.

Example

char student_name[10], address[20];
int roll_no[5], class[5];
If we use Structure then we use single variable for all data.

Syntax

struct stu
{
char student_name[10];
char address[20];
int roll_no[5];
int class[5];
};
Note: Minimum size of Structure is one byte and Maximum size of Structure is sum of all members variable size.
Note: Empty Structure is not possible in C Language.

Defining a Structure

Syntax

struct tagname
{
Datatype1 member1;
Datatype2 member2;
Datatype3 member3;
...........
};
At end of the structure creation (;) must be required because it indicates that an entity is constructed.

Example

struct emp
{
int id;
char name[36];
int sal;
};
sizeof(struct emp) // --> 40 byte (2byte+36byte+2byte)

Syntax to create structure variable

struct tagname variable;

Difference Between Array and Structure

ArrayStructure
1Array is collection of homogeneous data.Structure is the collection of heterogeneous data.
2Array data are access using index.Structure elements are access using . operator.
3Array allocates static memory.Structures allocate dynamic memory.
4Array element access takes less time than structures.Structure elements takes more time than Array.

Example of Structure in C

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

struct emp
{
int id;
char name[36];
float sal;
};

void main()
{
struct emp e;
clrscr();
printf("Enter employee Id, Name, Salary: ");
scanf("%d",&e.id);
scanf("%s",&e.name);
scanf("%f",&e.sal);

printf("Id: %d",e.id);
printf("\nName: %s",e.name);
printf("\nSalary: %f",e.sal);
getch();
}

Output

Output: Enter employee Id, Name, Salary: 5 Spidy 45000 Id : 05 Name: Spidy Salary: 45000.00

Syntax to access structure members

By using following operators we can access structure members.

Syntax

.     struct to member
-->   pointer to member
When the variable is normal type then go for struct to member operator.
When the variable is pointer type then go for pointer to member operator.

Difference Between Structure and Pointer in C

Structure in C refer to a collection of various data types for example you create a structure named "Student" which contains his name , roll no, DOB etc. Name is string, Roll no is int.
While pointer refer to address in C & symbol are used to point some particular place in C memory.


Union

union is quite similar to the structures in C. It also store different data types in the same memory location. It is also a user defined data type same like structure.

union and structure are almost same

StructureUnion
struct student
{
int roll;
char name[10];
float marks;
}u;
union student
{
int roll;
char name[10];
float marks;
}u;

Defining a union

Union can be defined in same manner as structures, for defining union use union keyword where as for defining structure use struct keyword.

Syntax

union tagname
{
datatype member1;
datatype member2;
.......
.......
};

Example of Union

union emp
{
int ID;
char name[10];
double salary;
}u;

Accessing members of an union

The member of unions can be accessed in similar manner as Structure with union reference. Suppose, we you want to access name variable in above example, it can be accessed as u.name.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.

Difference between Structure and Union

StructureUnion
1For defining structure use struct keyword.For defining union we use union keyword
2Structure occupies more memory space than union.Union occupies less memory space than Structure.
3In Structure we can access all members of structure at a time.In union we can access only one member of union at a time.
4Structure allocates separate storage space for its every members.Union allocates one common storage space for its all members. Union find which member need more memory than other member, then it allocate that much space

Memory Allocation in Structure and Union

Structure allocates separate storage space for its every members. Union allocates one common storage space for its all members. Union find which member need more memory than other member, then it allocate that much space
In case of Structure

Syntax

struct emp
{
int ID;
char name[10];
double salary;
};

Example

For above structure, memory allocation like below.
int ID -- 2B
char name[10] -- 10B
double salary -- 8B 
Total memory allocation = 2+6+8 = 16 Bytes
In case of Union

Syntax

union emp
{
int ID;
char name[10];
double salary;
};
For above union, only 8 bytes of memory will be allocated because double data type will occupy maximum space of memory over other data types.
Total memory allocation = 8 Bytes

When use Structure and Union

When need to manipulate the data for all member variables then use structure. When need to manipulate only one member then use union.
Note:
  1. All the properties of the structure are same for union, except initialization process.
  2. In case of structure initialize all data members at a time because memory location are different but in case of union only one member need to be initialize.
  3. In case of union if we initializing multiple member then compiler will gives an error.

Example of Union in C

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

union emp
{
int ID;
char name[10];
double salary;
}u; //  reference of union

void main()
{
clrscr();
printf("Enter emp Id: ");
scanf("%d",&u.ID);
printf("Enter emp Name: ");
scanf("%s",&u.name);
printf("Enter emp Salary: ");
scanf("%f",&u.salary);
printf("Emp ID: %d",u.ID);
printf("Emp Name: %s",u.name);
printf("Emp Salary: %f",u.salary);
getch();
}

Output

Output:
Emp ID: 100
Emp Name: Porter
Emp Salary: 20000








Strings

String is a collection of character or group of character, it is achieve in C language by using array character. The string in C language is one-dimensional array of character which is terminated by a null character '\0'. In other words string is a collection of character which is enclose between double cotes ( " " ).
Note: Strings are always enclosed within double quotes. Whereas, character is enclosed within single quotes in C.

Declaration of string

Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.

Example

 
char s[5];
String in C

Initializing Array string

String are initialize into various way in c language;

Example

char str[]="abcd";
        OR
char str[5]="abcd";
        OR
char str[5]={'a','b','c','d','\0'};
        OR
char str[]={'a','b','c','d','\0'};
        OR
char str[5]={'a','b','c','d','\0'};
In c language string can be initialize using pointer.

Example

char *c="abcd";
String in C

Reading String from user

Example

 
char str[5];
scanf("%s",&str);

Example

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

void main()
{
char str[10];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is: %s.",name);
getch();
}

Example of reading string

 
Enter name: Hitesh kumar
Your name is: Hitesh
Note: String variable str can only take only one word. It is because when white space is encountered, the scanf() function terminates. to over come this problem you can use gets() function.

Syntax

 
char str[5];
gets(str);

gets()

gets() are used to get input as a string from keyword, using gets() we can input more than one word at a time.

puts()

puts() are used to print output on screen, generally puts() function are used with gets() function.

Example of String program

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

void main()
{
char str[10];
printf("Enter any string: ");
gets(str);
printf("String are: ");
puts(str);
getch();
}
Explanation: Here gets() function are used for input string and puts() function are used to show string on console or monitor.

Output

Enter String: hello word
String are: hello word

C Library String functions

All the library function of String is available in String.h header file.
S.N.FunctionPurpose
1strcpy(s1, s2)Copies string s2 into string s1.
2strcat(s1, s2)Concatenates string s2 onto the end of string s1.
3strlen(s1)Returns the length of string s1.
4strcmp(s1, s2)Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5strchr(s1, ch)Returns a pointer to the first occurrence of character ch in string s1.
6strstr(s1, s2)Returns a pointer to the first occurrence of string s2 in string s1.

Important points for Declaration of string

  • In declaration of string size must be required to mention otherwise it gives an error.

Syntax

char str[];   // Invalid
char str[10]; // Valid
  • In declaration of the string size must be unsigned integer value (not -ve or zero value) which is greater than zero only.

Example

char str[];   // Invalid
char str[0];  // Invalid
char str[-1]; // Invalid
char str[10]; // Valid

Syntax

 
char variable_name[SIZE];
 
char str[5];

Important points for Initialization of the string

  • In Initialization of the string if the specific number of character are not initialized it then rest of all character will be initialized with NULL.

Example

char str[5]={'5','+','A'};
    str[0];  ---> 5
    str[1];  ---> +
    str[2];  ---> A
    str[3];  ---> NULL
    str[4];  ---> NULL
  • In initialization of the string we can not initialized more than size of string elements.

Example

 
char str[2]={'5','+','A','B'};  // Invalid
  • In initialization of the string the size is optional in this case how many variable elements are initialized it, that array element will created.

Example

 
char str[]={'5','+','A','B'};  // Valid
sizeof(str)  --> 4byte
When we are working with character array explicitly NULL character does not occupies any physical memory at the end of the character array.

Example

char str[]={'h','e','l','l','o'};
sizeof(str)  --> 5byte
String data at the end of the string NULL character occupies physical memory.

Example

char str[]="hello";
sizeof(str)  --> 6 byte

Why learning C Programming is a must?

C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and 1973. It was mainly developed as...