Showing posts with label C Programming Tutorial. Show all posts
Showing posts with label C Programming Tutorial. Show all posts

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.

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.

Wednesday, March 2, 2016

Concepts Associated with Functions in C

A function is not executed until it is called (invoked) from the program. By function call we mean, the program provides the function with input data in the form of arguments. The value of the argument is passed to the function and copied in the formal arguments. If the formal arguments are modified inside the function it will not affect the value of the actual arguments in the program unless the arguments are passed as pointers.
  1. #include<stdio.h>
  2. void function1(int a);
  3.  
  4. void main()
  5. {
  6. int i = 3;
  7. function1(i);
  8. printf("Value of i : %d", i);
  9. }
  10.  
  11. void function1(int a)
  12. {
  13. a++;
  14. printf("Value of a:%d\n", a);
  15. }
In the above example, value of variable 'a' will be printed as 4 but the value of 'i' will be printed as 3. Because, even if value of the argument is incremented inside the function, it would not affect the value of variable 'i' in 'main'. When the function is called, the program execution goes to the function and after executing the statements in the function, it returns to the same position.

Function parameters

The function parameter can be of any data type, char, int, float, string or even an array/user defined data type. The arguments passed from the caller (from where the function is called), must be of the same data type as of function parameters. If there is a mismatch between those two, it will generate a compiler error. Even sometimes the compiler may fail to spot the difference, in which case your program may act erroneously.

Variable Argument Functions in C

C function can also have variable number of arguments. For example functions like 'printf'and 'scanf' can take any number of arguments. The variable argument function has a function prototype like the one given below
data_type function_name(int, data_type argument1, …);
The three dots (…) in function prototype defines that it is variable argument. Note that the first argument is an integer which represents the number of arguments. Some utility methods are required to make use of variable arguments in C and it is defined inside header file 'stdarg.h'.

How to Use Variable Argument Function in C

First step in making use of variable arguments in the function definition is to use the macro,'va_start', which is defined in header file 'stdarg.h'. This macro initializes a variable of type'va_list' with the argument list. Then we need to use 'va_arg' macro and 'va_list'variable to access each individual parameters. When the processing is finished, use the macro'va_end' to release the memory used by 'va_list'.

Variable Argument Functions Example

  1. #include <stdio.h>
  2. #include <stdarg.h>
  3.  
  4. int calculateSum(int count,...)
  5. {
  6. va_list valist;
  7. int sum = 0.0;
  8. int i;
  9. va_start(valist, count);
  10. for (i = 0; i < count; i++)
  11. {
  12. sum += va_arg(valist, int);
  13. }
  14. va_end(valist);
  15. return sum;
  16. }
  17.  
  18. int main()
  19. {
  20. printf("Sum of 1, 2, 3 = %d\n", calculateSum(3, 1, 2, 3));
  21. printf("Sum of 1, 2, 3, 4 = %d\n", calculateSum(4, 1, 2, 3, 4));
  22. }