Saturday, 16 March 2019

LEARN UNION IN C : WITH VIDEO


Union in C


Union in C are exactly like the structure in C. Just like structure, the union is a user-defined data type. Syntax to define a union in C is similar to structure. There is only one difference in the structure and union that is the storage of memory. Each member has its own storage location in the structure, while the members of the union shared the same memory location, which size is equal to the largest data member. 

Union in C
Storage difference between structure and union in C


The syntax of Union in C


union name_of_union
{
data-type member1;
data-type member2;
data-type member3;
...............................
...............................
...............................
data-type member N;
};

The syntax of the union is similar to the syntax of structure in C. There is only one difference in the syntax of structure and union is only union keyword is used in place of struct keyword. 

Example
union data
{
int a;
int b;
};


Declaration of the union variable

Union variable can be declared as:

1. Union variable along with union definition

Union variable can be declared before the ending of union definition.

Syntax
union name_of_union
{
data-type member1;
data-type member2;
data-type member3;
..............................
..............................
..............................
data-type member N;
}union_variable;


Example:
union data;
{
int a;
int b;
}add;

2. Union variable after structure definition

Union variable can be declared anywhere in the program after the union definition based on the union scope.

Syntax
union name_of_union
{
data-type member1;
data-type member2;
data-type member3;
..............................
..............................
.............................
data-type member N;
};

main ( )
{
union name_of_union union variable;
}


Example
union data
{
int a;
int b;
}
main ( )
{
union data w,x,y;
}

Accessing a member of the union in C

Union members are also accessed as members of the structure using the dot operator(.).

Syntax
Union_variable.name_of member;

Program
#include <stdio.h>
//Declaration of union
union data
{
    int a;
    char b;
};

int main ( )
{
//A union variable q
    union data q;
    q.a = 132; // q.a gets value 132
    q.b = 'A'; //q.b gets value 'A'
    printf ("%d\n", q.a);
    printf ("%c\n", q.b);
    return 0;
}

Output
Union in C









As we can see that the value of 'a' does not occur as mention in the program while the value of  'b' is correct in our output. This is because of all the variables share the same memory. Hence, the only member whose value is currently stored will have the memory.

Pointer to unions

Union has pointers just like structures and with the help of arrow operator (->), we can access the members. 


C program demonstrates the working of pointers to the union.

#include <stdio.h>
union data
{
    int a;
    char b;
};
int main ( )
{
    union data q;
    q.a = 66;
    //q1 is a pointer to union q
    union data* q1=  &q;
    //Accessing union member using pointers
    printf ("%d %c", q1->a, q1->b);
    return 0;
}

Output
Union in C




The advantage of the union in C

Some programmers do not use the union properly. The main issue of the union is to save memory because the union members share the same memory.

Anonyms union and structure in C

The union and structure that do not have the name then they are called anonyms union/structure. The definition is similar to normal union or structure the only difference is defined without name or tag.

//Anonyms union example
union
{
int a;
char b;
};

//Anonyms structure example
struct
{
int a;
char b;
};

Because there are no variables and names, we access directly members. This accessibility works only inside the scope where the anonyms union is defined.

#include<stdio.h>
struct Scope
{
    // Anonymous union
    union
    {
        char a;
        int b;
    };
};

int main()
{
    struct Scope w;
    w.b = 66;

    //  members of union can accessed directly
    printf("w.a = %c, w.b = %d", w.a, w.b);

    return 0;
}


Output
Union in C







//C program demonstrate working of anonyms structure
#include<stdio.h>
struct Scope
{
    // Anonymous union
    struct
    {
        char a;
        int b;
    };
};

int main( )
{
    struct Scope w;
    w.a = 'B';
    w.b = 66;

    //  members of structure can accessed directly
    printf("w.a = %c, w.b = %d", w.a, w.b);

    return 0;
}


Output
Union in C




Difference between structure and union in C

1. Keyword: The keyword struct is used to define the structure in C and union keyword is to define union in C.
2. Size: Size of memory is allocated for each member define in structure but in the union, memory is allocated as per the largest member.
3. Memory: In structure, each member has its own space but in the union in C, all member shared the same memory. 
4. Altering value: Change in the value of the member will not affect the other members in structure but union in C it affects.
5. Accessing of members: Members of structure can be accessed at the same time but in the union, only one member can be accessed at the same time.
























































Monday, 11 March 2019

What is the structure in C?

The C programming language has a fundamental and user-defined data type. But they can not solve the problems of our real world. For a lot of situations, we need a custom data type.

Suppose you want to record the details of 100 students such as their name, their roll number, their age and their marks. Then you have to create four variables of size 100 i.e. name[100], roll_number[100], age[100] and marks[100]. To record details of the student using these four variables may seem very easy to see, but actually, it is complicated. 

To solve this problem, we need to user-defined data type. In this article, we will read about the way in which we can solve the problem by using the structure in C.

Structure in C


















Define structure in C

A structure in C is a user-defined data type. A structure is a collection of variables of different data types.

Learn Data Types in C

The difference between array and structure in C is that array is a collection of the data item of the same data type but the structure is a collection of the different data type in C.

What is Array in C

Create a structure in C

struct keyword is used to define the structure in C. It is a reserved word in C compiler.



Syntax

struct name_of_structure
{
data type member1;
data type member2;
data type member3;
...............................
...............................
...............................
...............................
data type member N;
};

Example

struct details_of student
{
char name[100];
int roll_number;
int age;
float marks;
};


Structure definition should be terminated with the semicolon (;).

Values cannot be defined within the structure definition.
For example
struct details_of student
{
char name[100]="Sharon";
int roll_number= 45;
int age = 14;
float marks = 986;
};

Structure in C can be defined as a global scope or local scope.

Declare structure variable in C

Structure variable in C can be declared as:

1. Structure variable along with structure definition

Structure variable can be declared before the ending of a structure definition.

Syntax
struct name_of_structure
{
data type member1;
data type member2;
data type member3;
...............................
...............................
...............................
...............................
data type member N;
}Structure variable;

Example
struct details_of student
{
char name[100];
int roll_number;
int age;
float marks;

}details;

2.  Structure variable after structure definition

We can declare the structure variable anywhere in the program after the structure definition based on the structure scope.

Syntax
struct Name_of structure structure_variable;

Example
struct details_of student
{
char name[100];
int roll_number;
int age;
float marks;

};

//Declare structure variable
struct details_of_strudent details;


Initialize structure members

Structured members cannot be initialized with the declaration.

Example
struct student
{
char name[100] = "King";
int roll_number = 45;
float marks = 456;
};

Output would be COMPILER ERROR: cannot initialize member here.

When we declared variable then no memory is allocated to it. Memory is allocated when the variables are initialized.

struct data
{
int roll_number;
float marks;
};

int main ( )
{
struct data p = { 56, 589};
}

Access structure members

There are two operators that can access the structure members.
1. Member operator or Dot/period operator (.)

Operator in C

Syntax
structure_variable.name_of_member;

2. Structure pointer operator or Arrow operator (->)

Syntax
pointer_to_structure->member_name;


Here, we are discussing a program that will explain the declaration of structure, initialization of structure and how structure members can be accessed.


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//Structure definition
struct details_of_student
{
    char name[100];
    int roll_number;
    int age;
    float marks;
};
int main ()
{
struct details_of_student A = {"King",10,15,475}; //Simple structure variable A
struct details_of_student *ptr; //Pointer to details of student;
ptr =&A;

printf (" Name of student = %s\n Roll number of student =%d\n Age of student = %d\n Marks of student = %f\n\n\n",A.name, A.roll_number,A.age,A.marks);

printf (" Name of student %s\n Roll number of student %d\n Age of student %d\n Marks of student %f\n\n\n",ptr->name, ptr->roll_number, ptr->age, ptr->marks);

return 0;

}

Output
Structure in C












Program for array of structure in C

#include<stdio.h>
struct Analysis
{
   int a, b;
};

int main()
{
   // Create an array of structures
   struct Analysis array[10];

   // Access array members
   array[0].a = 120;
   array[0].b = 130;

   printf("%d %d", array[0].a, array[0].b);
   return 0;
}

Output
120 130


A bit field in C

A bit field in C is used to optimize memory usage. 

Syntax
struct
{
data-type member : size_of_bits;
};

Let us understand with the help of an example that how much memory consumed by a normal union/structure in C, and how much memory space will be required by structure in C when using bit field.

#include <stdio.h>
#include <string.h>
//Structure definition
struct
{
    int a;
    int b;
}p1;

int main()
{
    printf ("size of normal structure  = %d\n", sizeof(p1));
    return 0;
}

Output
Structure in C








//C program demonstrate working of structure with bit field.
#include <stdio.h>
#include <string.h>

//Structure definition
struct
{
    int a : 1;
    int b : 1;
}p1;

int main()
{
    printf ("size of structure with bit field = %d\n", sizeof(p1));
    return 0;
}


Output
Structure in C




After seeing at the output of these two programs, the question arises why this happened? The member 'a' and 'b' having the value either zero or one. This is not going to have all integers restrict the size of this to a particular number of bits. So, rather than giving 4 bytes of integer which happened in this particular case, for this 'a' and 'b' integer digit 1 is reserved. We will see that there is 4 byte only. So, up to 32-bit, no issues will occur. If the value of a is 16 and b is 17 then the total number of bits is 33, it will go to the next level it will become 8 bytes. Bit field has only one advantage that is it reduces the consumption of memory space.













Recommended Posts

Pointer Pointer
Function pointer in C

Strings in C




















































































Monday, 4 March 2019

Strings in C

Strings in C





















Strings in C are the collection of characters. Strings are also known as an "Array of Characters".


Strings in C is a one-dimensional array.


Strings in C are ended by the "NULL ('\0') character.

Strings in C
Strings in C







Strings are written in double quotes ("Programming") while the character is written inside a single quote ('A').


In C programming, strings are not used as a data type (like char, float, double, int etc.).

Declaration of Strings in C

Strings are declared like an array if you do not know what the arrays are? Then, first, you should read the arrays.




1. char str[5];
If we write char as "str[5]" then 5 bytes of memory are reserved for 'str'.


2. char str[ ];
If we write char as "str[ ]" then the memory is allocated at the time of the program's execution.


Initialization of Strings in C

Strings in C can be initialized in many ways,

Way 1
char str[8] = "PROGRAM";
or 
char str[ ] = "PROGRAM";

In the above initialization, NULL ('\0') character is automatically inserted at the end of the string.


Way 2
char str[8] = {'P', 'R', 'O', 'G', 'R', 'A', 'M', '\0'};
or
char str[ ] =  {'P', 'R', 'O', 'G', 'R', 'A', 'M', '\0'};




Strings in C
Representation of string in a one-dimensional form











Strings in C


A string variable 'str' always holds the base address of a character array. It is also known as internal pointers.


C program in which a string is declared and printed.

#include <stdio.h>
int main( )
{
    char str[8] ="Program";
    char str1[8] = {'P','r','o','g','r','a','m','\0'};
    printf ("String Literal is : %s\n", str);
    printf ("Character array is :%s\n", str1);
    return 0;
}


Output


Strings in C



Read string from the user

'Scanf' function is used to read strings in C from the user.

'Scanf' function reads strings continuously until whitespace occurs.  

Example

#include <stdio.h>
int main( )
{
    char str[10];
    printf ("Enter String");
    scanf ("%s", str);
    printf ("String is %s\n", str);
    return 0;
}


Output

Strings in C



If whitespace is given in the input then scanf will read the string coming from the first whitespace. You can read this in the given program below,

#include <stdio.h>
int main( )
{
    char str[30];
    printf ("Enter String");
    scanf ("%s", str);
    printf ("String is %s\n", str);
    return 0;
}



Output
Strings in C


If you want to read strings given with whitespace, then use the gets ( ) function and this function is available in 'stdio.h' header file.

#include <stdio.h>
int main( )
{
    char str[30];
    printf ("Enter String\n");
    gets (str);
    printf ("string is %s \n", str);
    return 0;
}


Output

Strings in C


puts( ) function is used to print the output on the screen.

#include <stdio.h>
#include <conio.h>
int main( )
{
    char str[10];
    printf ("Enter string\n\t");
    gets (str);
    puts (str);
    return 0;
}


Output


Strings in C



Library string functions


'String.h' header file consists of lots of library function like, strlen( ), strcpy( ), strcmp( ), strcat(), strtok( ) etc.

Strlen ( ): This function calculates the length of string excluding null ('\0') character.


Syntax:

Strlen (Name_of_string);

Program to calculate the length of the strings in C

#include <stdio.h>
#include <string.h>
int main ( )
{
    int length;
    char str[ ]="Program";
    length = strlen(str);
    printf ("Length of string is = %d\n", length);
    return 0;
}


Output
Length of string is 7

Strcat( ): This function connects two strings together.


Syntax

strcat (string1, string2);


Program to concatenates two strings in C.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str1[]="United";
    char str2[]="States";
    strcat (str1,str2);
    printf ("Concatenate string is %s", str1);
    return 0;
}


Output
Concatenate String is UnitedStates


Strcmp ( ): This function compares two strings. If the two strings are equal then it returns 0 otherwise it returns 1.


Syntax

strcmp (string1, string2);


  • When string1 is greater than string2, then it returns 1.
  • When string1 is less than string2, then it returns -1.
  • If string1 and string2 both are equal then strcmp ( ) function returns zero.

Program to compare two strings in C.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str1[]="come";
    char str2[]="Welcome";

    int w,x,y,z;
    w = strcmp (str1, "come");
    x = strcmp (str1, "Welcome");
    y = strcmp (str1,"f");
    z = strcmp (str1,"feel");
    printf ("w=%d\n x=%d\n y=%d\n z=%d\n", w,x,y,z);
    return 0;
}


Output:
w = 0
x = 1
y = -1
z = -1


Strcpy( ): This function moves or copy the content of one string into another string.


Syntax

strcpy (string1, string2);


Program to copy the content of one string to another string in C.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str1[] = "DIGITAl ";
    char str2[] = "INDIA";
    strcpy (str1,str2);
    printf ("Final String = %s\n", str1);
    return 0;
}


Output
Final string = INDIA


Note: If the length of the destination string is less than source string then source string is not copied into destination string.


Strchr ( ): This function helps you to find the first occurrence of the desired character in a string.


Syntax

strchr (string, i);


Program to find the desired character in a string.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str[]="The C programming languages";
    char *ptr;
    ptr = strchr (str,'m');
    printf ("String in which first character  is occur = %s\n", ptr);
    return 0;
}


Output
String in which the first character is occurring = mming languages


Strrchr ( ): This function tells about the last occurrence of the desired character in a string.


Syntax

strchr (Name_of_string, 'Desired Charcter');

Program to find out the last occurrence of the desired character in a string.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str[]="The C programming language";
    char *ptr;
    ptr = strrchr(str,'i');
    printf ("The Last occurence of character in a string = %s\n", ptr);
    return 0;
}


Output
The last occurrence of the character in a string = ing language


Strstr ( ): With the help of this function we can find the desired string in the given string.


Syntax

strstr (Name_of_string, "desired string");

C Program to find the desired string in given string.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str[]="the c programming language";
    char *ptr;
    ptr = strstr (str, "programming");
    printf ("First occurrence of string is =%s\n", ptr);
    return 0;
}


Output
The first occurrence of the string is = programming language.



Strlwr ( ): This function converts a given string into lower case.


Syntax
strlwr (string);


C program to convert the string in to lower case.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str[]="MANGO SEASON IS BACK";
    printf ("%s\n",strlwr(str));
    return 0;
}


Output
mango season is back


Strupr ( ): This function converts the string into upper case.


Syntax

strupr (Name_of_string);

C program to convert a string into uppercase.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str[]="delhi";
    printf ("%s\n",strupr(str));
    return 0;
}


Output
DELHI

Strrev( ): This function reverses the given string.


Syntax
strrev (Name_of_string);

C program reverse the given string.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str[]="Mumbai";
    printf ("%s\n",strrev(str));
    return 0;
}


Output
iabmuM


Strtok ( ): This function breaks the string using a delimiter.


Syntax

strtok (Name_of_string);


C program in which a string is broken into substring.

#include <stdio.h>
#include <string.h>
int main ( )
{
    char str[]="Hello:World:Hello:Hi:Meet:them";
    char *ptr;
    ptr = strtok(str,":");
    while (ptr!=NULL)
    {
    printf ("%s\n",ptr);
    ptr = strtok (NULL, ":");
    }
    return 0;
}



Output
Hello
World
Hello
Hi
Meet
them


Passing strings to function

Strings in C is also called the character of the array. Strings pass in a function is similar the way the array is passed.

#include <stdio.h>
//Declaration of print function
void print_string(char str[]);
int main ( )
{
    char str[]="string";
    print_string (str);  //Calling print function
}

//Definition of print function
void print_string(char str[])
{
    puts(str);
}


Output
string


Pointers and Character Strings

We understand the Pointers and strings with the help of a programming example.



#include <stdio.h>
int main ( )
{
    char *name ="Shona";
    int length = 0;
    char *ptr = name;
    while (*ptr!=0)
    {
        ptr++;
        length++;
    }
    printf ("\n length of the string = %d\n",length);
    return 0;
}


Output
length of the string = 5














Recommended Posts

Pointer Pointer
Function pointer in C