Thursday, March 31, 2016

Difference between Structures and Unions

Structure and union both are user defined data types. The main difference between structure and union is that union uses same memory location for all the member variables hence the size of the union is the size of the largest member variable but structure uses different memory location for all the members. Let’s take an example:
union my_union
{ int my_int;
char my_char2;
char my_char1; } my_union;
int my_int;
struct my_struct { char my_char1;
} my_struct;
char my_char2;
Now if we execute sizeof function over my_struct and my_union then we will see that the output as 4 for union and 6 for structure. As for structure it is simple 4 for integer and 2 for 2 character variables but if for union it happens because of the union’s property of sharing memory location to all members. Union allocates memory equal to the size of the member variable which takes largest in the memory. Here since integer takes 4 bytes and character takes 1 byte each that’s why it takes 4 bytes of memory hence it outputs 4.

Wednesday, March 30, 2016

Usage of Unions

The main characteristic of union is that it lets you to use same memory location for different data type. In real life C programming, you may encounter a situation where you need to store a value of say 4 byte but at different time according to situation you need to know the value of 1st byte or 3rd byte or may be 4th byte contained value. Yes there is bitwise operators to do that but if you define a union like given above, you can access any byte of value at any time without any logical or arithmetic operation.
#include<stdio.h>
int main() {
char my_char;
union my_union {
} my_union;
int my_int; float my_float;
printf("Here is the Output:\n%c\n%i\n%.3f\n", my_union.my_char, my_union.my_int, my_union.my_float );
my_union.my_char = 'A'; my_union.my_int = 57;
printf("Here is the Output:\n%c\n%i\n%.3f\n", my_union.my_char, my_union.my_int, my_union.my_float );
my_union.my_float = 101.357; printf("Here is the Output:\n%c\n%i\n%.3f\n", my_union.my_char, my_union.my_int, my_union.my_float ); return 0;
}

Tuesday, March 29, 2016

Unions in c programming with example

Union is another user defined data type in C. This is very similar to the structure but there is slight difference between them.
union my_union
{
int var1;
char ch1;
char ch2;
char ch3;
char ch3;
} union1;

union1.var1 = 220;
union1.ch1 = ‘A’;
printf(“value %d”,union1.var1);

Unions in C

To define union, you have to use keyword union. Other things in syntax for union are similar to the structure. Example of declaration and access of union is given below:
union my_union
{
char my_char;
int my_int;
float my_float;
} my_union;

Monday, March 28, 2016

Array of Structures

When we have to declare similar kind of user defined data types in C, we can use array of structures. As you know have already seen that, arrays are used to store similar kinds of data. In all aspects, the array of structures is same as the other arrays i.e. arrays of integers, float etc. Only you have to use dot(.) operator or reference operator(->) to access structure members.
For example, we can define an array to store 100 student details like below.
student array_of_student[100];
Now, to access the member variables, we have to use array index number and the dot operator. For example, to set and print the value of 2'nd student name, roll number would be like this:
strcpy(array_of_student[1].name,”Denis Ritchie”);
array_of_student[1].roll_number = 20;
printf(“Student’s Name : %s\n array_of_student[1].name);
printf(“Student’s Roll Number : %d\n”, array_of_student[1].roll_number);

Sunday, March 27, 2016

Pointers to Structures

Just like other primitive data types you know, you can also define pointers to the structure too. However, accessing member variables using pointer to structure would be different. In this case, instead of dot(.) operator you have to use arrow(->) operator which is also called reference operator. Here is the example given below:
student student_1 = {0} , *pstudent = NULL;
pstudent = &student_1;
pstudent->roll_number = 20;
strcpy(pstudent->name,” Denis Ritchie”);
pstudent->class = 12;
pstudent->section = ‘A’;
pstudent->marks = 96.9;
strcpy(student_1->school_name,”a4academics.com”);

printf(“Student’s Roll Number : %d\n”, pstudent->roll_number);
printf(“Student’s Name : %s\n”, pstudent->name);
printf(“Student ‘s Class : %d\n”, pstudent->class);
printf(“Student’s Section : %c\n”, pstudent->section);
printf(“Student’s Marks : %f\n”, pstudent->marks);
printf(“Student’s School Name : %s\n”, pstudent->school_name);
Output :
Student’s Roll Number 20
Student’s Name Denis Ritchie
Student ‘s Class 12
Student’s Section A
Student’s Marks 96.9
Student’s School Name a4academics.com
Another way to store structure is by allocating memory dynamically. The only thing you need to remember here is that you have to free that memory when you don’t need them. When you allocate memory using malloc, you have to typecast to the structure that you are going to use in a program. Rest of the stuff is same as above.
pstudent =(student*) malloc(sizeof(student));

/* Your Code*/
free(pstudent);

Thursday, March 24, 2016

Member Variables

All the subfields i.e the primitive data type variables in structures are called member variables. We can access these member variables using dot(.) operator. We can set and retrieve the member variable of student structure as shown below.
student student_1 = {0};
student_1.roll_number = 20;
strcpy(student_1.name,”Denis Ritchie”);
student_1.class = 12;
student_1.section = ‘A’;
student_1.marks = 96.9;
strcpy(student_1.school_name,”a4academics.com”);

Wednesday, March 23, 2016

Structures in C

Using structures, you can define your own data type which can store multiple dissimilar primitive data types. Actually this type of data types is called user defined data types. For example, you can represent any real life object properties like student –
  • roll number – integer
  • name – character array
  • class – integer
  • section – character
  • last year marks in percentile – float
  • school name – character array
Here you can see that there are different data types which represent a particular student. So, using structure you can do this very easily in C.
Structure Declarations
In C, to define a structure there is a keyword “struct” is used. The syntax of the statement is like below.
struct 
{
 member_name;
 member_name;
 member_name;
...
} <one or more structure variables>;
For example, the above mentioned student declaration would be like this
struct student
{
int roll_number;
char name[50];
int class;
char section;
float marks;
char school_name[50];
} student_1;
Here, student_1 is the structure variable. You can also declare structure variable like below:
struct student student_2;
There is another good way to declare structure and its variables, using typedef keyword. The typedef keyword, actually defines a new data type by which you can use a data type the same way like other primitive data types.
typedef struct student
{
int roll_number;
char name[50];
int class;
char section;
float marks;
char school_name[50];
} student;
Here, using typedef we are defining a new data type called student. Now we can use this data type just like any other data types we know like int float etc. for variable declarations.
student student_1,student_2;
You can also initialize the structure variables also to zero like this:
student student_1 = {0};

Tuesday, March 22, 2016

Pointer Arithmetic

You are well aware about arithmetic of other variable like int, float, double etc. and you must think about whether those can be applied to a pointer variable or not. No, you can’t apply arithmetic operation like addition, subtraction, multiplications etc. between two pointer variables. The operations given below give you a Compiler Error.
int i=10;
int j=20;
int *pi = &i, *pj = &j;
int *res = *pi + *pj /* Compilation Error */
res = *pi - *pj /* Compilation Error */
res = *pi * *pj /* Compilation Error */
Only thing you can do is to increment and decrement operation to a pointer variable. This is mostly used by C programmers when dealing with arrays or strings.
char s[] = "a4academics.com";
char* ptr = s;

printf(“%s\n”,ptr);
printf(“%c\n”,*ptr);
printf(“%c\n”,*(ptr + 3));
ptr+=5;
printf(“%c\n”,ptr);
ptr--;
printf(“%c\n”,ptr);

The above gives following output:
a4academics.com
a
c
d
a

Monday, March 21, 2016

Void Pointers

You must have noticed that a pointer always holds an address of the same data type, like an integer, pointer always holds the address of integer type of variable, float of a float, double of a double etc.
But there is a special type of pointer called void pointer also known as generic pointer. This type of pointer can hold the memory address of any kind of data type or any object even functions too! This is declared like below:
void *void_ptr = &i;
But the only thing you need to remember is that you can’t dereference a pointer directly. You have to typecast it before you use it. Like if you want to print the value of the above declared void pointer, the memory address it contains point to is:
printf(“%d”,*(int *)void_ptr);
This is very useful when you want a pointer to point to data of different data types at different times.

Sunday, March 20, 2016

Dereferencing Pointers

As you seen earlier, "*" operator is used to declare the pointer type of the variable. "*" is also used to dereference the pointer also.
int j = *p;
It sets the value of "j" variable to the value contained at the memory address, the pointer p points to i.e. 10. You can also set a value to the memory address that a pointer holds like below.
*p = 20;
By this, the memory address that "p" pointer holds i.e. 0x2000 contains value 20 which is same as the value of i and *j, interesting right! That’s the beauty of the pointer, as you change the value that contains an address of a variable; it also changes the variable itself.

Thursday, March 17, 2016

Pointers in C

Pointers are often used to make C programming much easier and it helps programmers improve their program's efficiency. Not only that, by using the pointer's you can achieve unlimited amount of memory usage in your program, that’s cool right.

Definitions and Uses of Pointers

Pointers are the variables that hold an address of another variable of the same data type. The cool thing about the address of a variable is that, you'll then be able to go to that address and access the data stored in it. Pointers are basically used in the C in different ways. Some of them are:
  • To create dynamic and flexible data structures.
  • To pass and handle variable arguments passed to functions (Call by reference).
  • To retrieve information stored in list like arrays.

Pointer Variables

As I said earlier, pointers indicate the memory address of any kind of object i.e. It can be address of any primitive data types or structures or even functions. The variable which holds the address is called the pointer variable.

Wednesday, March 16, 2016

Commonly Used Functions

The most commonly used functions in the string library ie. Using <string.h> are:
  • strcat - concatenate two strings
  • strchr - string scanning operation
  • strcmp - compare two strings
  • strcpy - copy a string
  • strlen - get string length
  • strncat - concatenate one string with part of another
  • strncmp - compare parts of two strings
  • strrchr - string scanning operation
strcat:
char *strcat(char *s1, const char *s2);
s1 is a pointer to a string that will be modified. s2 will be copied to the end of s1. s2 is a pointer to a string that will be appended to the end of s1. It returns a pointer to s1 (where the resulting concatenated string resides).
strcpy:
char *strcpy(char *s1, const char *s2);
s1 is a pointer to the destination. s2 will be copied to the end of s1. It returns a pointer to s1 (where the resulting copied string resides).
strlen:
int strlen(char *s1);
s1 is a pointer to the string. It returns the length of the string excluding ‘\0’ character.
Example –
#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
/* Define a temporary variable */
char MyString[100];

/* Copy the first string into the variable */
strcpy(MyString, "a4");

/* Concatenate the following two strings to the end of the first one */
strcat(MyString, "academics ");
strcat(MyString, ".com");

/* Display the concatenated strings */
printf("%s\n", MyString);

/* Display the length of the string */
printf(“Length : %d\n”,strlen(MyString));

return 0;
}
Output –
a4academics.com
Length : 15
strchr :
char *strchr(const char *s, int c);
s is a string (terminated by a null character).c is the character to be found. It returns a pointer to the first occurrence of the character c within the string pointed to by s. If c isn't found, it returns a null pointer.
strcmp :
char *strcmp(const char *s1, const char *s2);
s1 and s2 a string (terminated by a null character). It returns the ASCII value difference of the first index of mismatched characters of the given string.
Example -
strcmp(“Samiran”,Saha);
It will return the difference between ASCII value of ‘m’ and ‘a’ ie. 12. Because first mismatch occurs at 3rd index.
strcmp(“Saha”,Saha);
It will return 0 because there is no mismatch in the given string.

Tuesday, March 15, 2016

Array of Strings

You know that there are arrays of primitive data types like integers, characters, float etc. Question may be arise in your mind, array of strings is possible or not ?

Answer is yes.

One way to do this is using two dimensional character array and other is using array of character pointers.
Method 1 - using two dimensional char array :
char arr[][10] = {"We", "like", "to", "learn"};
0x2000‘W’‘e’‘\0’
0x200A‘l’‘i’‘k’‘e’‘\0’
0x2014‘t’‘o’‘\0’
0x201D‘l’‘e’‘a’‘r’‘n’‘\0’
Memory representation of two dimensional array
All the shaded cells contain garbage values. First Column indicates memory locations of first byte of each string. As you see that in this case memory locations are contiguous.
Method 2 –using array of character pointers:
char *arr[] = {"We", "like", "to", "learn"};
Here, the difference between earlier is that since it is the array of character pointer of string literals, you can’t modify the strings, but you can replace it with new string literals or strings.

Monday, March 14, 2016

C Strings - Internal Working and Functions with example

Unlike other languages like C++, Java, etc. C does not provide any dedicated data type, rather it uses a character array to store strings. Since, in programming practices, we encounter frequently to handle strings. It is good to know how to do this in C.
Strings in C
As mentioned earlier, in C handles strings in a different manner, uses a character array to store. Now, after reading the Chapter: Arrays in C Language, you might have confused that there was something called character array and C uses also a character array to store strings, then how both gets differ with each other ?

Actually, there is a slight difference between simple character array and strings. A string always ends with ‘\0’ or NULL character which is not mandatory for a simple character array. 

Initializing Strings in C

Strings in C can be initialized in various ways and for every method there are some important points you should remember.
char arr[] = {‘A’,’4’,’A’,’C’,’A’,’D’,’E’,’M’,’I’,’C’,’S’,’\0’};
This is the simplest way to initialize the strings. It is same like the character array initialization, but only difference is that there is a ‘\0’ character at the end. Here, the size of the array is not mentioned, so it will automatically allocate memory for 8 characters (8 bytes since a character takes 1 byte) including the ‘\0’ character.
Method 2:
char arr[] = “A4ACADEMICS”;
This is another way to initialize the array. Here, the compiler automatically inserts a ‘\0’ at the end.
Method 3:
char arr[10] = {‘A’,’4’,’A’,’C’,’A’,’D’,’E’,’M’,’I’,’C’,’S’,’\0’};
In this method, arr holds 10 byte of memory as per declaration. From the 0th index to 6th index it will hold the word “STRING” and 7th location holds ‘\0’ character and 8th and 9th location holds garbage values.
Method 4:
char *arr = “A4ACADEMICS”;
This is another interesting way to initialize strings. Specifically, this is called string literals. The most interesting thing in this method is that after this declaration you can’t change the value of the string. This will be constant string literals throughout its scope.

Sunday, March 13, 2016

Passing Arrays To Functions

Whenever we need to pass a list of elements as parameter to the function, it is preferred to do that using an array. 
Fundamentally, there is one way to do it. But, syntactically three ways to do it. You can pass entire array to a function using pointer. Usually, pointer variable is used to store memory addresses, so you can pass the location of first element of your array to the function using the pointer.
Usually, when you call a function from your current function then the current function is calledCalling Function and the function you are calling is called Called Function.
When you are passing the array to a function using pointer, you have to pass its size also. Otherwise, if you do some invalid access of array in the called function, it could be a serious problem! So it is best practice to pass the size of array also.
The syntax of the three ways are given below:
Method 1:
<return type> <Function name>(<data type> *<pointer variable name>)
{
/* Your Function Body Here */ ….............................. } Example : int function ( int *my_array, int size) /* size indicating my_array size */ { int i; for (i=0;i<size;i++) printf(“%d ”,my_array[i]); }
Method 2:
<return type> <Function name>(<data type> <pointer variable name>[])
{
 /* Your Function Body Here */
 …..............................
}

Example :
int function ( int my_array[], int size)  /* size indicating my_array size */
{
int i;
for (i=0;i<size;i++)
 printf(“%d ”,my_array[i]);
}
Method 3:
<return type> <Function name>(<data type> <array name>[<array size>])
{
 /* Your Function Body Here */
 …..............................
}

Example :
int function ( int my_array[10])  /* Here 10 indicates my_array size */
{
 int i;
 for (i=0;i<10;i++)
  printf(“%d ”,my_array[i]);
}

You can see that, there is a difference in syntax but all are actually passing the pointer. You can test it by modifying the the values of array in called function and printing the array in callingfunction after calling the called function. You will see that the values has been modified in all the three syntax given above.

Thursday, March 10, 2016

Accessing and Initialization of Two Dimensional Array

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is essentially, an array of one-dimensional arrays. To declare a two-dimensional integer array "S" of size 10,20, you would write.
int s[10][20];
Two-dimensional arrays are stored in a row-column matrix, where the first index indicates the row and the second indicates the column. This means that the rightmost index changes more quickly than the leftmost when accessing the elements in the array in the order in which they are actually stored in memory.

Suppose, you want to access element located at 3'rd row and 5'th column of the two dimensional array "S", store the value in a integer variable var then the statement would be like this :
int var =  s[2][4]; /* As Array index start from 0, 2 indicates 3'rd Row and 4 indicates 5'th Column*/

Wednesday, March 9, 2016

Multi-Dimensional Arrays

 C language also supports multi dimensional arrays. The number of maximum dimension you can use in your program is delimited by your compiler. The generic form of declaring a multi dimensional array is:
 [Size1][Size2][Size3]. . .[SizeN];

Elements of Multi-Dimensional Arrays

Arrays of more than three dimensions are not often used because of the amount of memory they require. For example, a four-dimensional character array with dimensions 10,9,8,7 requires 10 * 9 * 8 * 7 or 5040 bytes.
If it is an integer array, then it would take 4 times the memory. So you can imagine that how big the memory becomes.
In multidimensional arrays, computer takes more time to compute each index. This means that accessing an element in a multidimensional array can be slower than accessing an element in a single-dimensional array.
It is good to have a look at how the elements in multidimensional array stored in memory. For simplicity, take a three dimensional array. As you can see earlier, arrays are stored in continuous way in memory. For a three dimensional array, you can imagine the memory allocation like a Rubik’s cube. Memories are allocated from 1'st row followed by 2'nd level and so on. In this way memories are allocated one after another.

Tuesday, March 8, 2016

Initialization of Single Dimensional Array

Single Dimensional Arrays in C can be initialized in the following way:
Method 1:
int rollnum[6]={5,3,32,9,2,10};
By this way, you specify the size of the array and initialize the values.
Method 2:
int rollnum[]={5,3,32,9,2,10};
You can even assign values to the array, without initializing the size of the array.
Method 3:
int rollnum[5];
int i;
for( i=0;i<5;i++ )
{
   rollnum[i] = i;
}
You can initialize the arrays this way too.

Accessing Array Elements

In C programming, you can access and operate arrays like variables in C. To access i'th element in the array you need to write as <array name>[i-1]. Since the array index starts from 0.
For example:
scanf("%d",&rollNum[3]);
/* statement to insert value in the forth element of array rollNum[]. */

scanf("%d",&rollNum[i]);
/* Statement to insert value in (i+1)th element of array rollNum[]. */
/* Because, the first element of array is rollNum[0], second is rollNum[1], ith is rollNum[i-1] and (i+1)th is rollNum[i]. */

printf("%d",rollNum[0]);
/* statement to print first element of an array. */

printf("%d",rollNum[i]);
/* statement to print (i+1)th element of an array. */
One thing you should remember is that, when you have declared roll_Number[6] array of size 6, your valid access to the array is only from 0 to 5. If you try to access any invalid index like 8, 10 etc. compiler do not throw any error, it will be throw a runtime error. Usually a program crash due to invalid memory manipulation i.e. it would cause a segmentation fault.

Monday, March 7, 2016

C Arrays

Suppose in your company, if you have 200 employees and you want to store salaries of all 200 employees. For that, declaring 200 different variable is tedious and is impossible to maintain. So, instead of declaring 200 variables you can declare a single array of 200 sizes, where each index refers to different employees.

Declaration of Arrays

Arrays in C can be declared in following way:
<data type> <array name>[<array size>];
For example:
int employees[200];
There are some properties you need to know about arrays in C.
  • Array index starts from 0 i.e. in the above example, array indexes would be from 0 to 199 in general 0 to n-1.
  • Array allocates memory in continuous way.
  • Arrays always have fixed size i.e. you cannot change its size after its declaration.
  • Arrays can be single dimensional as well as multi-dimensional also.

Sunday, March 6, 2016

Recursive Functions

Recursive functions are those functions which call themselves directly or indirectly. If a function calls itself again, that will make a repetition and will work like a loop. In order to make a logical end to the repetitive call, we have to add an expression to break the flow of recursive call. Consider the program of factorial which finds the factorial of the input number. It can be written using recursive function as given below.

Recursive Function Example in C

  1. #include<stdio.h>
  2. int factorial(int n);
  3.  
  4. void main()
  5. {
  6. int num;
  7. int fact;
  8. printf("Enter the number:");
  9. scanf("%d", &num);
  10.  
  11. fact = factorial(num);
  12. printf("Factorial of %d is %d", num, fact);
  13. }
  14.  
  15. int factorial(int n)
  16. {
  17. if(n == 1)
  18. {
  19. return 1;
  20. }
  21. else
  22. {
  23. return (n * factorial(n -1));
  24. }
  25. }
Let’s take the input number as 3. Then the factorial function is called with value 3. Inside the function it will check whether 3 is equal to 1 and then execute the 'else' statements. The return statement will look like 'return (3 * factorial (2))'. Now 'factorial(2)' will again enter the 'else' statement as the 'if' condition fails. This time it will return '(2 * factorial(1))'. Now 'factorial(1)' returns value 1 which will result the output (3 * (2 * 1)) i.e. 6.
One thing to remember while using recursive function is that if you omit the check expression or if the expression never be satisfied, it will cause an infinite loop. Recursion is another way to simulate loop and can be replaced by a simple loop statement (also called iteration)

Thursday, March 3, 2016

Function with Return Value

Function as mentioned earlier can return some value. The number of values that can be returned by a function is restricted to 1 in C. If a function calculates more number of output values, you can use a structure/union to hold each of them and return it. The type of value returned by the function must be defined in the function prototype and definition. To illustrate function with return value a simple program is presented below.

  1. #include<stdio.h>
  2. int add(int a, int b);
  3.  
  4. void main()
  5. {
  6. int sum = 0;
  7. sum = add(23, 35);
  8. printf("Sum : %d", sum);
  9. }
  10.  
  11. int add(int a, int b)
  12. {
  13. int c = a + b;
  14. return c;
  15. }
In the above example, the function 'add()' takes two arguments of integer type and returns an integer value. Notice the return statement in the 'add()' function which returns the value to the caller.